Skip to content

Commit 3ab0b8d

Browse files
loic425soyuka
authored andcommitted
feat(metadata): use PHP file as resource format
1 parent c022b44 commit 3ab0b8d

File tree

14 files changed

+334
-3
lines changed

14 files changed

+334
-3
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Metadata\Extractor;
15+
16+
use ApiPlatform\Metadata\ApiResource;
17+
18+
/**
19+
* Extracts an array of metadata from a list of PHP files.
20+
*
21+
* @author Loïc Frémont <[email protected]>
22+
*/
23+
final class PhpFileResourceExtractor extends AbstractResourceExtractor
24+
{
25+
use ResourceExtractorTrait;
26+
27+
/**
28+
* {@inheritdoc}
29+
*/
30+
protected function extractPath(string $path): void
31+
{
32+
$resource = $this->getPHPFileClosure($path)();
33+
34+
if (!$resource instanceof ApiResource) {
35+
return;
36+
}
37+
38+
$resourceReflection = new \ReflectionClass($resource);
39+
40+
foreach ($resourceReflection->getProperties() as $property) {
41+
$property->setAccessible(true);
42+
$resolvedValue = $this->resolve($property->getValue($resource));
43+
$property->setValue($resource, $resolvedValue);
44+
}
45+
46+
$this->resources = [$resource];
47+
}
48+
49+
/**
50+
* Scope isolated include.
51+
*
52+
* Prevents access to $this/self from included files.
53+
*/
54+
private function getPHPFileClosure(string $filePath): \Closure
55+
{
56+
return \Closure::bind(function () use ($filePath): mixed {
57+
return require $filePath;
58+
}, null, null);
59+
}
60+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Metadata\Resource\Factory;
15+
16+
use ApiPlatform\Metadata\Extractor\ResourceExtractorInterface;
17+
use ApiPlatform\Metadata\Operation;
18+
use ApiPlatform\Metadata\Operations;
19+
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
20+
21+
final class PhpFileResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
22+
{
23+
use OperationDefaultsTrait;
24+
25+
public function __construct(
26+
private readonly ResourceExtractorInterface $metadataExtractor,
27+
private readonly ?ResourceMetadataCollectionFactoryInterface $decorated = null,
28+
) {
29+
}
30+
31+
/**
32+
* {@inheritdoc}
33+
*/
34+
public function create(string $resourceClass): ResourceMetadataCollection
35+
{
36+
$resourceMetadataCollection = new ResourceMetadataCollection($resourceClass);
37+
if ($this->decorated) {
38+
$resourceMetadataCollection = $this->decorated->create($resourceClass);
39+
}
40+
41+
foreach ($this->metadataExtractor->getResources() as $resource) {
42+
if ($resourceClass !== $resource->getClass()) {
43+
continue;
44+
}
45+
46+
$shortName = (false !== $pos = strrpos($resourceClass, '\\')) ? substr($resourceClass, $pos + 1) : $resourceClass;
47+
$resource = $this->getResourceWithDefaults($resourceClass, $shortName, $resource);
48+
49+
$operations = [];
50+
/** @var Operation $operation */
51+
foreach ($resource->getOperations() ?? new Operations() as $operation) {
52+
[$key, $operation] = $this->getOperationWithDefaults($resource, $operation);
53+
$operations[$key] = $operation;
54+
}
55+
56+
if ($operations) {
57+
$resource = $resource->withOperations(new Operations($operations));
58+
}
59+
60+
$resourceMetadataCollection[] = $resource;
61+
}
62+
63+
return $resourceMetadataCollection;
64+
}
65+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Metadata\Resource\Factory;
15+
16+
use ApiPlatform\Metadata\Extractor\ResourceExtractorInterface;
17+
use ApiPlatform\Metadata\Resource\ResourceNameCollection;
18+
19+
/**
20+
* @internal
21+
*/
22+
final class PhpFileResourceNameCollectionFactory implements ResourceNameCollectionFactoryInterface
23+
{
24+
public function __construct(
25+
private readonly ResourceExtractorInterface $metadataExtractor,
26+
private readonly ?ResourceNameCollectionFactoryInterface $decorated = null,
27+
) {
28+
}
29+
30+
/**
31+
* {@inheritdoc}
32+
*/
33+
public function create(): ResourceNameCollection
34+
{
35+
$classes = [];
36+
37+
if ($this->decorated) {
38+
foreach ($this->decorated->create() as $resourceClass) {
39+
$classes[$resourceClass] = true;
40+
}
41+
}
42+
43+
foreach ($this->metadataExtractor->getResources() as $resource) {
44+
$resourceClass = $resource->getClass();
45+
46+
if (null === $resourceClass) {
47+
continue;
48+
}
49+
50+
$classes[$resourceClass] = true;
51+
}
52+
53+
return new ResourceNameCollection(array_keys($classes));
54+
}
55+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Metadata\Tests\Extractor;
15+
16+
use ApiPlatform\Metadata\ApiResource;
17+
use ApiPlatform\Metadata\Extractor\PhpFileResourceExtractor;
18+
use PHPUnit\Framework\TestCase;
19+
20+
final class PhpFileResourceExtractorTest extends TestCase
21+
{
22+
public function testItGetsResourcesFromPhpFileThatReturnsAnApiResource(): void
23+
{
24+
$extractor = new PhpFileResourceExtractor([__DIR__.'/php/valid_php_file.php']);
25+
26+
$expectedResource = new ApiResource(shortName: 'dummy');
27+
28+
$this->assertEquals([$expectedResource], $extractor->getResources());
29+
}
30+
31+
public function testItExcludesResourcesFromPhpFileThatDoesNotReturnAnApiResource(): void
32+
{
33+
$extractor = new PhpFileResourceExtractor([__DIR__.'/php/invalid_php_file.php']);
34+
35+
$this->assertEquals([], $extractor->getResources());
36+
}
37+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
return new stdClass();
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
use ApiPlatform\Metadata\ApiResource;
15+
16+
return new ApiResource(shortName: 'dummy');

src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ private function normalizeDefaults(array $defaults): array
320320

321321
private function registerMetadataConfiguration(ContainerBuilder $container, array $config, XmlFileLoader $loader): void
322322
{
323-
[$xmlResources, $yamlResources] = $this->getResourcesToWatch($container, $config);
323+
[$xmlResources, $yamlResources, $phpResources] = $this->getResourcesToWatch($container, $config);
324324

325325
$container->setParameter('api_platform.class_name_resources', $this->getClassNameResources());
326326

@@ -335,6 +335,7 @@ private function registerMetadataConfiguration(ContainerBuilder $container, arra
335335
}
336336

337337
// V3 metadata
338+
$loader->load('metadata/php.xml');
338339
$loader->load('metadata/xml.xml');
339340
$loader->load('metadata/links.xml');
340341
$loader->load('metadata/property.xml');
@@ -353,6 +354,8 @@ private function registerMetadataConfiguration(ContainerBuilder $container, arra
353354
$container->getDefinition('api_platform.metadata.resource_extractor.yaml')->replaceArgument(0, $yamlResources);
354355
$container->getDefinition('api_platform.metadata.property_extractor.yaml')->replaceArgument(0, $yamlResources);
355356
}
357+
358+
$container->getDefinition('api_platform.metadata.resource_extractor.php_file')->replaceArgument(0, $phpResources);
356359
}
357360

358361
private function getClassNameResources(): array
@@ -417,7 +420,32 @@ private function getResourcesToWatch(ContainerBuilder $container, array $config)
417420
}
418421
}
419422

420-
$resources = ['yml' => [], 'xml' => [], 'dir' => []];
423+
$resources = ['yml' => [], 'xml' => [], 'php' => [], 'dir' => []];
424+
425+
foreach ($config['mapping']['imports'] ?? [] as $path) {
426+
if (is_dir($path)) {
427+
foreach (Finder::create()->followLinks()->files()->in($path)->name('/\.php$/')->sortByName() as $file) {
428+
$resources[$file->getExtension()][] = $file->getRealPath();
429+
}
430+
431+
$resources['dir'][] = $path;
432+
$container->addResource(new DirectoryResource($path, '/\.php$/'));
433+
434+
continue;
435+
}
436+
437+
if ($container->fileExists($path, false)) {
438+
if (!str_ends_with($path, '.php')) {
439+
throw new RuntimeException(\sprintf('Unsupported mapping type in "%s", supported type is PHP.', $path));
440+
}
441+
442+
$resources['php'][] = $path;
443+
444+
continue;
445+
}
446+
447+
throw new RuntimeException(\sprintf('Could not open file or directory "%s".', $path));
448+
}
421449

422450
foreach ($paths as $path) {
423451
if (is_dir($path)) {
@@ -446,7 +474,7 @@ private function getResourcesToWatch(ContainerBuilder $container, array $config)
446474

447475
$container->setParameter('api_platform.resource_class_directories', $resources['dir']);
448476

449-
return [$resources['xml'], $resources['yml']];
477+
return [$resources['xml'], $resources['yml'], $resources['php']];
450478
}
451479

452480
private function registerOAuthConfiguration(ContainerBuilder $container, array $config): void

src/Symfony/Bundle/DependencyInjection/Configuration.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,9 @@ public function getConfigTreeBuilder(): TreeBuilder
136136
->arrayNode('mapping')
137137
->addDefaultsIfNotSet()
138138
->children()
139+
->arrayNode('imports')
140+
->prototype('scalar')->end()
141+
->end()
139142
->arrayNode('paths')
140143
->prototype('scalar')->end()
141144
->end()
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?xml version="1.0" ?>
2+
3+
<container xmlns="http://symfony.com/schema/dic/services"
4+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5+
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
6+
7+
<services>
8+
<service id="api_platform.metadata.resource_extractor.php_file" class="ApiPlatform\Metadata\Extractor\PhpFileResourceExtractor" public="false">
9+
<argument type="collection" />
10+
<argument type="service" id="service_container" />
11+
</service>
12+
</services>
13+
</container>

src/Symfony/Bundle/Resources/config/metadata/resource.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@
2424
<argument>%api_platform.graphql.enabled%</argument>
2525
</service>
2626

27+
<service id="api_platform.metadata.resource.metadata_collection_factory.php_file" class="ApiPlatform\Metadata\Resource\Factory\PhpFileResourceMetadataCollectionFactory" decorates="api_platform.metadata.resource.metadata_collection_factory" decoration-priority="800" public="false">
28+
<argument type="service" id="api_platform.metadata.resource_extractor.php_file" />
29+
<argument type="service" id="api_platform.metadata.resource.metadata_collection_factory.php_file.inner" />
30+
<argument type="service" id="service_container" on-invalid="null" />
31+
</service>
32+
2733
<service id="api_platform.metadata.resource.metadata_collection_factory.concerns" class="ApiPlatform\Metadata\Resource\Factory\ConcernsResourceMetadataCollectionFactory" decorates="api_platform.metadata.resource.metadata_collection_factory" decoration-priority="800" public="false">
2834
<argument type="service" id="api_platform.metadata.resource.metadata_collection_factory.concerns.inner" />
2935
</service>

0 commit comments

Comments
 (0)