Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
use ApiPlatform\Metadata\McpTool;
use ApiPlatform\Metadata\NotExposed;
use ApiPlatform\Metadata\OperationMutatorInterface;
use ApiPlatform\Metadata\Parameter;
use ApiPlatform\Metadata\Parameters;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
Expand Down Expand Up @@ -439,9 +441,66 @@ private function normalizeDefaults(array $defaults): array
$normalizedDefaults['extra_properties'][$option] = $value;
}

if (isset($normalizedDefaults['parameters']) && \is_array($normalizedDefaults['parameters'])) {
$normalizedDefaults['parameters'] = $this->normalizeParametersConfig($normalizedDefaults['parameters']);
}

return $normalizedDefaults;
}

private function normalizeParametersConfig(array $parametersConfig): Parameters|array
{
$parameters = [];
$hasClassNames = false;

foreach ($parametersConfig as $key => $config) {
if (class_exists($key) && is_subclass_of($key, Parameter::class)) {
$hasClassNames = true;
$parameterClass = $key;
$parameterConfig = \is_array($config) ? $config : [];

try {
$reflection = new \ReflectionClass($parameterClass);
$constructor = $reflection->getConstructor();

if (null === $constructor) {
continue;
}

$args = [];
foreach ($constructor->getParameters() as $param) {
$paramName = $param->getName();
if (isset($parameterConfig[$paramName])) {
$args[$paramName] = $parameterConfig[$paramName];
} elseif ($param->isDefaultValueAvailable()) {
$args[$paramName] = $param->getDefaultValue();
}
}

$instance = $reflection->newInstance(...$args);

if (null !== $instance->getKey()) {
$parameters[$instance->getKey()] = $instance;
}
} catch (\ReflectionException|\TypeError $e) {
continue;
}
} else {
$parameters[$key] = $config;
}
}

if ($hasClassNames || !empty($parameters)) {
try {
return new Parameters($parameters);
} catch (\Throwable $e) {
return $parameters;
}
}

return $parameters;
}

private function registerMetadataConfiguration(ContainerBuilder $container, array $config, PhpFileLoader $loader): void
{
[$xmlResources, $yamlResources, $phpResources] = $this->getResourcesToWatch($container, $config);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Symfony\Tests\Bundle\DependencyInjection;

use ApiPlatform\Metadata\HeaderParameter;
use ApiPlatform\Metadata\Parameters;
// use ApiPlatform\Metadata\QueryParameter;
use ApiPlatform\Symfony\Bundle\DependencyInjection\ApiPlatformExtension;
use ApiPlatform\Tests\Fixtures\TestBundle\TestBundle;
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\SecurityBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

/**
* Test that parameters can be defined using Parameter class names as keys.
*
* Example:
* ```yaml
* defaults:
* parameters:
* 'ApiPlatform\Metadata\HeaderParameter':
* key: 'X-Api-Version'
* required: true
* ```
*/
class ApiPlatformExtensionParameterClassNameTest extends TestCase
{
private ContainerBuilder $container;

protected function setUp(): void
{
$containerParameterBag = new ParameterBag([
'kernel.bundles' => [
'DoctrineBundle' => DoctrineBundle::class,
'SecurityBundle' => SecurityBundle::class,
'TwigBundle' => TwigBundle::class,
],
'kernel.bundles_metadata' => [
'TestBundle' => [
'parent' => null,
'path' => realpath(__DIR__.'/../../../Fixtures/TestBundle'),
'namespace' => TestBundle::class,
],
],
'kernel.project_dir' => __DIR__.'/../../../Fixtures/app',
'kernel.debug' => false,
'kernel.environment' => 'test',
]);

$this->container = new ContainerBuilder($containerParameterBag);
}

public function testParametersWithClassNameAsKey(): void
{
$config = [
'api_platform' => [
'defaults' => [
'parameters' => [
'ApiPlatform\Metadata\HeaderParameter' => [
'key' => 'X-Api-Version',
'required' => true,
'description' => 'API Version',
],
// 'ApiPlatform\Metadata\QueryParameter' => [
// 'key' => 'q',
// 'description' => 'Search query',
// ],
],
],
],
];

(new ApiPlatformExtension())->load($config, $this->container);

$defaults = $this->container->getParameter('api_platform.defaults');
$this->assertArrayHasKey('parameters', $defaults);

$parameters = $defaults['parameters'];
$this->assertInstanceOf(Parameters::class, $parameters);

$paramArray = iterator_to_array($parameters);
$this->assertNotEmpty($paramArray);

$this->assertArrayHasKey('X-Api-Version', $paramArray);
$headerParam = $paramArray['X-Api-Version'];
$this->assertInstanceOf(HeaderParameter::class, $headerParam);
$this->assertTrue($headerParam->getRequired());

// $this->assertArrayHasKey('q', $paramArray);
// $queryParam = $paramArray['q'];
// $this->assertInstanceOf(QueryParameter::class, $queryParam);
}

public function testMixedParameterDefinitions(): void
{
$config = [
'api_platform' => [
'defaults' => [
'parameters' => [
'ApiPlatform\Metadata\HeaderParameter' => [
'key' => 'X-Api-Version',
'required' => true,
],
// 'ApiPlatform\Metadata\QueryParameter' => [
// 'key' => 'q',
// 'description' => 'Search query',
// ],
],
],
],
];

(new ApiPlatformExtension())->load($config, $this->container);

$defaults = $this->container->getParameter('api_platform.defaults');
$this->assertArrayHasKey('parameters', $defaults);

$parameters = $defaults['parameters'];
$this->assertInstanceOf(Parameters::class, $parameters);

$paramArray = iterator_to_array($parameters);

$this->assertArrayHasKey('X-Api-Version', $paramArray);
$this->assertInstanceOf(HeaderParameter::class, $paramArray['X-Api-Version']);

// $this->assertArrayHasKey('q', $paramArray);
// $this->assertInstanceOf(QueryParameter::class, $paramArray['q']);
}

public function testMultipleHeaderParameters(): void
{
$config = [
'api_platform' => [
'defaults' => [
'parameters' => [
'ApiPlatform\Metadata\HeaderParameter' => [
'key' => 'X-Api-Version',
'required' => true,
],
],
],
],
];

(new ApiPlatformExtension())->load($config, $this->container);

$defaults = $this->container->getParameter('api_platform.defaults');
$this->assertArrayHasKey('parameters', $defaults);

$parameters = $defaults['parameters'];
$this->assertInstanceOf(Parameters::class, $parameters);

$paramArray = iterator_to_array($parameters);
$this->assertNotEmpty($paramArray);
}
}
3 changes: 2 additions & 1 deletion tests/Fixtures/TestBundle/Entity/Book.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use Doctrine\ORM\Mapping as ORM;

/**
* Book.
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
#[ApiResource(operations: [new Get(), new Get(uriTemplate: '/books/by_isbn/{isbn}{._format}', requirements: ['isbn' => '.+'], uriVariables: 'isbn')])]
#[ApiResource(operations: [new Get(), new Get(uriTemplate: '/books/by_isbn/{isbn}{._format}', requirements: ['isbn' => '.+'], uriVariables: 'isbn'), new GetCollection()])]
#[ORM\Entity]
class Book
{
Expand Down
5 changes: 5 additions & 0 deletions tests/Fixtures/app/config/config_common.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ api_platform:
Made with love
enable_swagger: true
enable_swagger_ui: true
defaults:
parameters:
'ApiPlatform\Metadata\HeaderParameter':
key: 'X-Request-ID'
description: 'A unique request identifier'
formats:
jsonld: ['application/ld+json']
jsonhal: ['application/hal+json']
Expand Down
92 changes: 92 additions & 0 deletions tests/Functional/OpenApi/GlobalDefaultsParametersOpenApiTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Functional\OpenApi;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Book;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Dummy;
use ApiPlatform\Tests\RecreateSchemaTrait;
use ApiPlatform\Tests\SetupClassResourcesTrait;

/**
* Test that global default parameters are applied to ALL resources in OpenAPI spec.
*
* When parameters are defined in api_platform.defaults.parameters with class names as keys,
* they should appear in the OpenAPI documentation for EVERY resource, not just specific ones.
*/
class GlobalDefaultsParametersOpenApiTest extends ApiTestCase
{
use RecreateSchemaTrait;
use SetupClassResourcesTrait;

protected static ?bool $alwaysBootKernel = false;

/**
* @return class-string[]
*/
public static function getResources(): array
{
return [
Book::class,
Dummy::class,
];
}

/**
* Test that global HeaderParameter with description appears in schema.
*
* If we configured global parameters like:
* ```yaml
* defaults:
* parameters:
* 'ApiPlatform\Metadata\HeaderParameter':
* description: 'A unique request identifier'
* ```
*
* Then this parameter should appear in OpenAPI for all resources.
*/
public function testGlobalHeaderParameterAppearsInSchema(): void
{
$globalHeaderParameterDescription = 'A unique request identifier';
$globalHeaderParameterKey = 'X-Request-ID';

$bookResponse = self::createClient()->request('GET', '/docs', [
'headers' => ['Accept' => 'application/vnd.openapi+json'],
]);

$this->assertResponseIsSuccessful();
$bookRes = $bookResponse->toArray();

$bookParameters = $bookRes['paths']['/books']['get']['parameters'];
$this->assertTrue(isset($bookParameters));

$bookParametersHeader = $bookParameters[4];
$this->assertSame($globalHeaderParameterDescription, $bookParametersHeader['description']);
$this->assertSame($globalHeaderParameterKey, $bookParametersHeader['name']);

$dummyResponse = self::createClient()->request('GET', '/docs', [
'headers' => ['Accept' => 'application/vnd.openapi+json'],
]);

$this->assertResponseIsSuccessful();
$dummyRes = $dummyResponse->toArray();

$dummyParameters = $dummyRes['paths']['/dummies/{id}']['get']['parameters'];
$this->assertTrue(isset($dummyParameters));

$dummyParametersHeader = $dummyParameters[1];
$this->assertSame($globalHeaderParameterDescription, $dummyParametersHeader['description']);
$this->assertSame($globalHeaderParameterKey, $dummyParametersHeader['name']);
}
}
Loading