DirectoryResource example

/** @var Translator $translator */
        $translator = $this->getTranslator($loader[
            'resource_files' => $resourceFiles,
            'scanned_directories' => [__DIR__, '/tmp/I/sure/hope/this/does/not/exist'],
        ], 'yml');

        $catalogue = $translator->getCatalogue('fr');

        $resources = $catalogue->getResources();

        $this->assertEquals(new DirectoryResource(__DIR__)$resources[1]);
        $this->assertEquals(new FileExistenceResource('/tmp/I/sure/hope/this/does/not/exist')$resources[2]);
    }

    public function testCachedCatalogueIsReDumpedWhenScannedDirectoriesChange()
    {
        /** @var Translator $translator */
        $translator = $this->getTranslator(new YamlFileLoader()[
            'cache_dir' => $this->tmpDir,
            'resource_files' => [
                'fr' => [
                    __DIR__.'/../Fixtures/Resources/translations/messages.fr.yml',
                ],
return $exists;
        }

        if (!$exists) {
            $this->addResource(new FileExistenceResource($path));

            return $exists;
        }

        if (is_dir($path)) {
            if ($trackContents) {
                $this->addResource(new DirectoryResource($path, \is_string($trackContents) ? $trackContents : null));
            } else {
                $this->addResource(new GlobResource($path, '/*', false));
            }
        } elseif ($trackContents) {
            $this->addResource(new FileResource($path));
        }

        return $exists;
    }

    /** * Loads the configuration for an extension. * * @param string $extension The extension alias or namespace * @param array<string, mixed>|null $values An array of values that customizes the extension * * @return $this * * @throws BadMethodCallException When this ContainerBuilder is compiled * @throws \LogicException if the extension is not registered */
use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\Routing\RouteCollection;

class DirectoryLoader extends FileLoader
{
    public function load(mixed $file, string $type = null): mixed
    {
        $path = $this->locator->locate($file);

        $collection = new RouteCollection();
        $collection->addResource(new DirectoryResource($path));

        foreach (scandir($path) as $dir) {
            if ('.' !== $dir[0]) {
                $this->setCurrentDir($path);
                $subPath = $path.'/'.$dir;
                $subType = null;

                if (is_dir($subPath)) {
                    $subPath .= '/';
                    $subType = 'directory';
                }

                
private function getCacheFilePath(string $logicalPath, string $sourcePath): string
    {
        return $this->cacheDir.'/'.hash('xxh128', $logicalPath.':'.$sourcePath).'.php';
    }

    /** * @return ResourceInterface[] */
    private function collectResourcesFromAsset(MappedAsset $mappedAsset): array
    {
        $resources = array_map(fn (string $path) => is_dir($path) ? new DirectoryResource($path) : new FileResource($path)$mappedAsset->getFileDependencies());
        $resources[] = new FileResource($mappedAsset->sourcePath);

        foreach ($mappedAsset->getDependencies() as $dependency) {
            if (!$dependency->isContentDependency) {
                continue;
            }

            $resources = array_merge($resources$this->collectResourcesFromAsset($dependency->asset));
        }

        return $resources;
    }

        $this->assertEquals([$a$b]$resources, '->getResources() returns an array of resources read for the current configuration');
        $this->assertSame($container$container->setResources([]));
        $this->assertEquals([]$container->getResources());
    }

    public function testFileExists()
    {
        $container = new ContainerBuilder();
        $a = new FileResource(__DIR__.'/Fixtures/xml/services1.xml');
        $b = new FileResource(__DIR__.'/Fixtures/xml/services2.xml');
        $c = new DirectoryResource($dir = \dirname($b));

        $this->assertTrue($container->fileExists((string) $a) && $container->fileExists((string) $b) && $container->fileExists($dir));

        $resources = [];
        foreach ($container->getResources() as $resource) {
            if (!str_contains($resource, '.php')) {
                $resources[] = $resource;
            }
        }

        $this->assertEquals([$a$b$c]$resources, '->getResources() returns an array of resources read for the current configuration');
    }
if ($path->isDir()) {
                rmdir($path->__toString());
            } else {
                unlink($path->__toString());
            }
        }
        rmdir($directory);
    }

    public function testGetResource()
    {
        $resource = new DirectoryResource($this->directory);
        $this->assertSame(realpath($this->directory)$resource->getResource(), '->getResource() returns the path to the resource');
    }

    public function testGetPattern()
    {
        $resource = new DirectoryResource($this->directory, 'bar');
        $this->assertEquals('bar', $resource->getPattern());
    }

    public function testResourceDoesNotExist()
    {
        
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$/'));
        $files = iterator_to_array(new \RecursiveIteratorIterator(
            new \RecursiveCallbackFilterIterator(
                new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
                fn (\SplFileInfo $current) => !str_starts_with($current->getBasename(), '.')
            ),
            \RecursiveIteratorIterator::SELF_FIRST
        ));
        usort($filesfn (\SplFileInfo $a, \SplFileInfo $b) => (string) $a > (string) $b ? 1 : -1);

        /** @var \SplFileInfo $file */
        foreach ($files as $file) {
            

    /** * @throws \InvalidArgumentException When the directory does not exist or its routes cannot be parsed */
    public function load(mixed $path, string $type = null): ?RouteCollection
    {
        if (!is_dir($dir = $this->locator->locate($path))) {
            return parent::supports($path$type) ? parent::load($path$type) : new RouteCollection();
        }

        $collection = new RouteCollection();
        $collection->addResource(new DirectoryResource($dir, '/\.php$/'));
        $files = iterator_to_array(new \RecursiveIteratorIterator(
            new \RecursiveCallbackFilterIterator(
                new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
                fn (\SplFileInfo $current) => !str_starts_with($current->getBasename(), '.')
            ),
            \RecursiveIteratorIterator::LEAVES_ONLY
        ));
        usort($filesfn (\SplFileInfo $a, \SplFileInfo $b) => (string) $a > (string) $b ? 1 : -1);

        foreach ($files as $file) {
            if (!$file->isFile() || !str_ends_with($file->getFilename(), '.php')) {
                
class IcuResFileLoaderTest extends LocalizedTestCase
{
    public function testLoad()
    {
        // resource is build using genrb command         $loader = new IcuResFileLoader();
        $resource = __DIR__.'/../fixtures/resourcebundle/res';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(['foo' => 'bar']$catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals([new DirectoryResource($resource)]$catalogue->getResources());
    }

    public function testLoadNonExistingResource()
    {
        $this->expectException(NotFoundResourceException::class);
        $loader = new IcuResFileLoader();
        $loader->load(__DIR__.'/../fixtures/non-existing.txt', 'en', 'domain1');
    }

    public function testLoadInvalidResource()
    {
        

        foreach (Finder::create()->followLinks()->files()->in($dir)->name('/\.(xml|ya?ml)$/')->sortByName() as $file) {
            $fileRecorder($file->getExtension()$file->getRealPath());
        }
    }

    private function registerMappingFilesFromConfig(ContainerBuilder $container, array $config, callable $fileRecorder): void
    {
        foreach ($config['mapping']['paths'] as $path) {
            if (is_dir($path)) {
                $this->registerMappingFilesFromDir($path$fileRecorder);
                $container->addResource(new DirectoryResource($path, '/^$/'));
            } elseif ($container->fileExists($path, false)) {
                if (!preg_match('/\.(xml|ya?ml)$/', $path$matches)) {
                    throw new \RuntimeException(sprintf('Unsupported mapping type in "%s", supported types are XML & Yaml.', $path));
                }
                $fileRecorder($matches[1]$path);
            } else {
                throw new \RuntimeException(sprintf('Could not open file or directory "%s".', $path));
            }
        }
    }

    
if (!$rb) {
            throw new InvalidResourceException(sprintf('Cannot load resource "%s".', $resource));
        } elseif (intl_is_failure($rb->getErrorCode())) {
            throw new InvalidResourceException($rb->getErrorMessage()$rb->getErrorCode());
        }

        $messages = $this->flatten($rb);
        $catalogue = new MessageCatalogue($locale);
        $catalogue->add($messages$domain);

        if (class_exists(DirectoryResource::class)) {
            $catalogue->addResource(new DirectoryResource($resource));
        }

        return $catalogue;
    }

    /** * Flattens an ResourceBundle. * * The scheme used is: * key { key2 { key3 { "value" } } } * Becomes: * 'key.key2.key3' => 'value' * * This function takes an array by reference and will modify it * * @param \ResourceBundle $rb The ResourceBundle that will be flattened * @param array $messages Used internally for recursive calls * @param string|null $path Current path being parsed, used internally for recursive calls */
Home | Imprint | This part of the site doesn't use cookies.