8000 [Config][Routing] Nicer config syntax for PSR-4 route loading by derrabus · Pull Request #47943 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Config][Routing] Nicer config syntax for PSR-4 route loading #47943

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 22, 2022
Merged
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
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
test_bundle:
prefix: /annotated
resource: "@TestBundle/Controller"
type: attribute@Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller
resource:
path: "@TestBundle/Controller"
namespace: Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller
type: attribute
12 changes: 10 additions & 2 deletions src/Symfony/Component/Config/Exception/LoaderLoadException.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,22 @@
class LoaderLoadException extends \Exception
{
/**
* @param string $resource The resource that could not be imported
* @param mixed $resource The resource that could not be imported
* @param string|null $sourceResource The original resource importing the new resource
* @param int $code The error code
* @param \Throwable|null $previous A previous exception
* @param string|null $type The type of resource
*/
public function __construct(string $resource, string $sourceResource = null, int $code = 0, \Throwable $previous = null, string $type = null)
public function __construct(mixed $resource, string $sourceResource = null, int $code = 0, \Throwable $previous = null, string $type = null)
{
if (!\is_string($resource)) {
try {
$resource = json_encode($resource, \JSON_THROW_ON_ERROR);
} catch (\JsonException) {
$resource = sprintf('resource of type "%s"', get_debug_type($resource));
}
}

$message = '';
if ($previous) {
// Include the previous exception, to help the user see what might be the underlying cause
Expand Down
6 changes: 5 additions & 1 deletion src/Symfony/Component/Config/Loader/FileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,11 @@ private function doImport(mixed $resource, string $type = null, bool $ignoreErro
try {
$loader = $this->resolve($resource, $type);

if ($loader instanceof self && null !== $this->currentDir) {
if (!$loader instanceof self) {
return $loader->load($resource, $type);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@derrabus That does not work as the PSR-4 loader uses the locator but without the current dir, so the resource cannot be found. Or am I missing something?

}

if (null !== $this->currentDir) {
$resource = $loader->getLocator()->locate($resource, $this->currentDir, false);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,15 @@ function (\SplFileInfo $current) {

public function supports(mixed $resource, string $type = null): bool
{
if (!\is_string($resource)) {
return false;
}

if (\in_array($type, ['annotation', 'attribute'], true)) {
return true;
}

if ($type || !\is_string($resource)) {
if ($type) {
return false;
}

Expand Down
20 changes: 12 additions & 8 deletions src/Symfony/Component/Routing/Loader/Psr4DirectoryLoader.php
8000
Original file line number Diff line number Diff line change
Expand Up @@ -12,35 +12,39 @@
namespace Symfony\Component\Routing\Loader;

use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\RouteCollection;

/**
* A loader that discovers controller classes in a directory that follows PSR-4.
*
* @author Alexander M. Turek <me@derrabus.de>
*/
final class Psr4DirectoryLoader extends FileLoader
final class Psr4DirectoryLoader extends Loader
{
public function __construct(FileLocatorInterface $locator)
{
public function __construct(
private readonly FileLocatorInterface $locator,
) {
// PSR-4 directory loader has no env-aware logic, so we drop the $env constructor parameter.
parent::__construct($locator);
parent::__construct();
}

/**
* @param array{path: string, namespace: string} $resource
*/
public function load(mixed $resource, string $type = null): ?RouteCollection
{
$path = $this->locator->locate($resource);
$path = $this->locator->locate($resource['path']);
if (!is_dir($path)) {
return new RouteCollection();
}

return $this->loadFromDirectory($path, trim(substr($type, 10), ' \\'));
return $this->loadFromDirectory($path, trim($resource['namespace'], '\\'));
}

public function supports(mixed $resource, string $type = null): bool
{
return \is_string($resource) && null !== $type && str_starts_with($type, 'attribute@');
return ('attribute' === $type || 'annotation' === $type) && \is_array($resource) && isset($resource['path'], $resource['namespace']);
}

private function loadFromDirectory(string $directory, string $psr4Prefix): RouteCollection
Expand Down
15 changes: 13 additions & 2 deletions src/Symfony/Component/Routing/Loader/XmlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,17 @@ protected function parseRoute(RouteCollection $collection, \DOMElement $node, st
*/
protected function parseImport(RouteCollection $collection, \DOMElement $node, string $path, string $file)
{
if ('' === $resource = $node->getAttribute('resource')) {
throw new \InvalidArgumentException(sprintf('The <import> element in file "%s" must have a "resource" attribute.', $path));
/** @var \DOMElement $resourceElement */
if (!($resource = $node->getAttribute('resource') ?: null) &&a 9E88 mp; $resourceElement = $node->getElementsByTagName('resource')[0] ?? null) {
$resource = [];
/** @var \DOMAttr $attribute */
foreach ($resourceElement->attributes as $attribute) {
$resource[$attribute->name] = $attribute->value;
}
}

if (!$resource) {
throw new \InvalidArgumentException(sprintf('The <import> element in file "%s" must have a "resource" attribute or element.', $path));
}

$type = $node->getAttribute('type');
Expand Down Expand Up @@ -276,6 +285,8 @@ private function parseConfigs(\DOMElement $node, string $path): array
case 'condition':
$condition = trim($n->textContent);
break;
case 'resource':
break;
default:
throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@
<xsd:element name="prefix" type="localized-path" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="exclude" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="host" type="localized-path" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="resource" type="resource" minOccurs="0" maxOccurs="1" />
</xsd:sequence>
<xsd:attribute name="resource" type="xsd:string" use="required" />
<xsd:attribute name="resource" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="exclude" type="xsd:string" />
<xsd:attribute name="prefix" type="xsd:string" />
Expand All @@ -93,6 +94,12 @@
<xsd:attribute name="stateless" type="xsd:boolean" />
</xsd:complexType>

<xsd:complexType name="resource">
<xsd:attribute name="path" type="xsd:string" />
<xsd:attribute name="namespace" type="xsd:string" />
<xsd:anyAttribute />
</xsd:complexType>

<xsd:complexType name="default" mixed="true">
<xsd:choice minOccurs="0" maxOccurs="1">
<xsd:element name="bool" type="xsd:boolean" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
xsi:schemaLocation="http://symfony.com/schema/routing
https://symfony.com/schema/routing/routing-1.0.xsd">

<import resource="./Psr4Controllers" prefix="/my-prefix"
type="attribute@Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers" />
<import prefix="/my-prefix" type="attribute">
<resource path="./Psr4Controllers" namespace="Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers" />
</import>
</routes>
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
my_controllers:
resource: ./Psr4Controllers
type: attribute@Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers
resource:
path: ./Psr4Controllers
namespace: Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers
type: attribute
prefix: /my-prefix
Original file line number Diff line number Diff line change
Expand Up @@ -57,34 +57,35 @@ public function testTraitController()
}

/**
* @dataProvider provideResourceTypesThatNeedTrimming
* @dataProvider provideNamespacesThatNeedTrimming
*/
public function testPsr4NamespaceTrim(string $resourceType)
public function testPsr4NamespaceTrim(string $namespace)
{
$route = $this->getLoader()
->load('Psr4Controllers', $resourceType)
->load(
['path' => 'Psr4Controllers', 'namespace' => $namespace],
'attribute',
)
->get('my_route');

$this->assertSame('/my/route', $route->getPath());
$this->assertSame(MyController::class.'::__invoke', $route->getDefault('_controller'));
}

public function provideResourceTypesThatNeedTrimming(): array
public function provideNamespacesThatNeedTrimming(): array
{
return [
['attribute@ Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers'],
['attribute@\\Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers'],
['attribute@Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers\\'],
['attribute@\\Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers\\'],
['attribute@ \\Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers'],
['\\Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers'],
['Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers\\'],
['\\Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers\\'],
];
}

private function loadPsr4Controllers(): RouteCollection
{
return $this->getLoader()->load(
'Psr4Controllers',
'attribute@Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers'
['path' => 'Psr4Controllers', 'namespace' => 'Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers'],
'attribute'
);
}

Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/Routing/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"php": ">=8.1"
},
"require-dev": {
"symfony/config": "^5.4|^6.0",
"symfony/config": "^6.2",
"symfony/http-foundation": "^5.4|^6.0",
"symfony/yaml": "^5.4|^6.0",
"symfony/expression-language": "^5.4|^6.0",
Expand All @@ -29,7 +29,7 @@
},
"conflict": {
"doctrine/annotations": "<1.12",
"symfony/config": "<5.4",
"symfony/config": "<6.2",
"symfony/dependency-injection": "<5.4",
"symfony/yaml": "<5.4"
},
Expand Down
304A
0