Skip to content

[Config][Routing] Fix delegating to PSR-4 loader from subdirectory #47953

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 23, 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
@@ -0,0 +1,22 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Config\Loader;

/**
* A loader that can be scoped to a given filesystem directory.
*
* @author Alexander M. Turek <me@derrabus.de>
*/
interface DirectoryAwareLoaderInterface
{
public function forDirectory(string $currentDirectory): static;
}
6 changes: 4 additions & 2 deletions src/Symfony/Component/Config/Loader/FileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,6 @@ public function getLocator(): FileLocatorInterface
* @param string|null $sourceResource The original resource importing the new resource
* @param string|string[]|null $exclude Glob patterns to exclude from the import
*
* @return mixed
*
* @throws LoaderLoadException
* @throws FileLoaderImportCircularReferenceException
* @throws FileLocatorFileNotFoundException
Expand Down Expand Up @@ -136,6 +134,10 @@ private function doImport(mixed $resource, string $type = null, bool $ignoreErro
try {
$loader = $this->resolve($resource, $type);

if ($loader instanceof DirectoryAwareLoaderInterface) {
$loader = $loader->forDirectory($this->currentDir);
}

if (!$loader instanceof self) {
return $loader->load($resource, $type);
}
Expand Down
31 changes: 28 additions & 3 deletions src/Symfony/Component/Routing/Loader/Psr4DirectoryLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,20 @@
namespace Symfony\Component\Routing\Loader;

use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Config\Loader\DirectoryAwareLoaderInterface;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Config\Resource\DirectoryResource;
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 Loader
final class Psr4DirectoryLoader extends Loader implements DirectoryAwareLoaderInterface
{
private ?string $currentDirectory = null;

public function __construct(
private readonly FileLocatorInterface $locator,
) {
Expand All @@ -34,7 +38,7 @@ public function __construct(
*/
public function load(mixed $resource, string $type = null): ?RouteCollection
{
$path = $this->locator->locate($resource['path']);
$path = $this->locator->locate($resource['path'], $this->currentDirectory);
if (!is_dir($path)) {
return new RouteCollection();
}
Expand All @@ -47,12 +51,33 @@ public function supports(mixed $resource, string $type = null): bool
return ('attribute' === $type || 'annotation' === $type) && \is_array($resource) && isset($resource['path'], $resource['namespace']);
}

public function forDirectory(string $currentDirectory): static
{
$loader = clone $this;
$loader->currentDirectory = $currentDirectory;

return $loader;
}

private function loadFromDirectory(string $directory, string $psr4Prefix): RouteCollection
{
$collection = new RouteCollection();
$collection->addResource(new DirectoryResource($directory, '/\.php$/'));
Copy link
Member

Choose a reason for hiding this comment

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

This was missing

$files = iterator_to_array(new \RecursiveIteratorIterator(
Copy link
Member

Choose a reason for hiding this comment

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

I've copy/pasted the logic from the annotation directory loader to keep the same file order. If not, the routes won't be registered in the same order and that could be a BC break.
I haven't shared the logic between the classes as I supposed that we will deprecate the annotation loader soon enough.

new \RecursiveCallbackFilterIterator(
new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
function (\SplFileInfo $current) {
return !str_starts_with($current->getBasename(), '.');
}
),
\RecursiveIteratorIterator::LEAVES_ONLY
));
usort($files, function (\SplFileInfo $a, \SplFileInfo $b) {
return (string) $a > (string) $b ? 1 : -1;
});

/** @var \SplFileInfo $file */
foreach (new \FilesystemIterator($directory) as $file) {
foreach ($files as $file) {
if ($file->isDir()) {
$collection->addCollection($this->loadFromDirectory($file->getPathname(), $psr4Prefix.'\\'.$file->getFilename()));

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing
https://symfony.com/schema/routing/routing-1.0.xsd">

<import resource="psr4-controllers-redirection/psr4-attributes.xml" />
</routes>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
controllers:
resource: psr4-controllers-redirection/psr4-attributes.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing
https://symfony.com/schema/routing/routing-1.0.xsd">

<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
@@ -0,0 +1,6 @@
my_controllers:
resource:
path: ../Psr4Controllers
namespace: Symfony\Component\Routing\Tests\Fixtures\Psr4Controllers
type: attribute
prefix: /my-prefix
15 changes: 13 additions & 2 deletions src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,10 @@ public function testImportingAliases()
$this->assertEquals($expectedRoutes('xml'), $routes);
}

public function testImportAttributesWithPsr4Prefix()
/**
* @dataProvider providePsr4ConfigFiles
*/
public function testImportAttributesWithPsr4Prefix(string $configFile)
{
$locator = new FileLocator(\dirname(__DIR__).'/Fixtures');
new LoaderResolver([
Expand All @@ -611,11 +614,19 @@ protected function configureRoute(Route $route, \ReflectionClass $class, \Reflec
},
]);

$route = $loader->load('psr4-attributes.xml')->get('my_route');
$route = $loader->load($configFile)->get('my_route');
$this->assertSame('/my-prefix/my/route', $route->getPath());
$this->assertSame(MyController::class.'::__invoke', $route->getDefault('_controller'));
}

public function providePsr4ConfigFiles(): array
{
return [
['psr4-attributes.xml'],
['psr4-controllers-redirection.xml'],
];
}

public function testImportAttributesFromClass()
{
new LoaderResolver([
Expand Down
15 changes: 13 additions & 2 deletions src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,10 @@ public function testImportingAliases()
$this->assertEquals($expectedRoutes('yaml'), $routes);
}

public function testImportAttributesWithPsr4Prefix()
/**
* @dataProvider providePsr4ConfigFiles
*/
public function testImportAttributesWithPsr4Prefix(string $configFile)
{
$locator = new FileLocator(\dirname(__DIR__).'/Fixtures');
new LoaderResolver([
Expand All @@ -477,11 +480,19 @@ protected function configureRoute(Route $route, \ReflectionClass $class, \Reflec
},
]);

$route = $loader->load('psr4-attributes.yaml')->get('my_route');
$route = $loader->load($configFile)->get('my_route');
$this->assertSame('/my-prefix/my/route', $route->getPath());
$this->assertSame(MyController::class.'::__invoke', $route->getDefault('_controller'));
}

public function providePsr4ConfigFiles(): array
{
return [
['psr4-attributes.yaml'],
['psr4-controllers-redirection.yaml'],
];
}

public function testImportAttributesFromClass()
{
new LoaderResolver([
Expand Down