|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[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 | +namespace Symfony\Component\Routing\Loader; |
| 13 | + |
| 14 | +use Symfony\Component\Config\FileLocatorInterface; |
| 15 | +use Symfony\Component\Config\Loader\FileLoader; |
| 16 | +use Symfony\Component\Routing\RouteCollection; |
| 17 | + |
| 18 | +/** |
| 19 | + * A loader that discovers controller classes in a directory that follows PSR-4. |
| 20 | + * |
| 21 | + * @author Alexander M. Turek <[email protected]> |
| 22 | + */ |
| 23 | +final class Psr4DirectoryLoader extends FileLoader |
| 24 | +{ |
| 25 | + public function __construct(FileLocatorInterface $locator) |
| 26 | + { |
| 27 | + // PSR-4 directory loader has no env-aware logic, so we drop the $env constructor parameter. |
| 28 | + parent::__construct($locator); |
| 29 | + } |
| 30 | + |
| 31 | + public function load(mixed $resource, string $type = null): ?RouteCollection |
| 32 | + { |
| 33 | + $path = $this->locator->locate($resource); |
| 34 | + if (!is_dir($path)) { |
| 35 | + return new RouteCollection(); |
| 36 | + } |
| 37 | + |
| 38 | + return $this->loadFromDirectory($path, trim(substr($type, 5), ' \\')); |
| 39 | + } |
| 40 | + |
| 41 | + public function supports(mixed $resource, string $type = null): bool |
| 42 | + { |
| 43 | + return \is_string($resource) && null !== $type && str_starts_with($type, 'psr4@'); |
| 44 | + } |
| 45 | + |
| 46 | + private function loadFromDirectory(string $directory, string $psr4Prefix): RouteCollection |
| 47 | + { |
| 48 | + $collection = new RouteCollection(); |
| 49 | + |
| 50 | + /** @var \SplFileInfo $file */ |
| 51 | + foreach (new \FilesystemIterator($directory) as $file) { |
| 52 | + if ($file->isDir()) { |
| 53 | + $collection->addCollection($this->loadFromDirectory($file->getPathname(), $psr4Prefix.'\\'.$file->getFilename())); |
| 54 | + |
| 55 | + continue; |
| 56 | + } |
| 57 | + if ('php' !== $file->getExtension() || !class_exists($className = $psr4Prefix.'\\'.$file->getBasename('.php'))) { |
| 58 | + continue; |
| 59 | + } |
| 60 | + |
| 61 | + $collection->addCollection($this->import($className, 'attribute')); |
| 62 | + } |
| 63 | + |
| 64 | + return $collection; |
| 65 | + } |
| 66 | +} |
0 commit comments