FileResource example

public function testDatEnglishLoad()
    {
        // bundled resource is build using pkgdata command which at least in ICU 4.2 comes in extremely! buggy form         // you must specify an temporary build directory which is not the same as current directory and         // MUST reside on the same partition. pkgdata -p resources -T /srv -d.packagelist.txt         $loader = new IcuDatFileLoader();
        $resource = __DIR__.'/../fixtures/resourcebundle/dat/resources';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(['symfony' => 'Symfony 2 is great']$catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals([new FileResource($resource.'.dat')]$catalogue->getResources());
    }

    public function testDatFrenchLoad()
    {
        $loader = new IcuDatFileLoader();
        $resource = __DIR__.'/../fixtures/resourcebundle/dat/resources';
        $catalogue = $loader->load($resource, 'fr', 'domain1');

        $this->assertEquals(['symfony' => 'Symfony 2 est gĂ©nial']$catalogue->all('domain1'));
        $this->assertEquals('fr', $catalogue->getLocale());
        $this->assertEquals([new FileResource($resource.'.dat')]$catalogue->getResources());
    }
return include $file;
        }, null, ProtectedPhpFileLoader::class);

        $result = $load($path);

        if (\is_object($result) && \is_callable($result)) {
            $collection = $this->callConfigurator($result$path$file);
        } else {
            $collection = $result;
        }

        $collection->addResource(new FileResource($path));

        return $collection;
    }

    public function supports(mixed $resource, string $type = null): bool
    {
        return \is_string($resource) && 'php' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'php' === $type);
    }

    protected function callConfigurator(callable $result, string $path, string $file): RouteCollection
    {
        
class FileResourceTest extends TestCase
{
    protected FileResource $resource;
    protected string $file;
    protected int $time;

    protected function setUp(): void
    {
        $this->file = sys_get_temp_dir().'/tmp.xml';
        $this->time = time();
        touch($this->file, $this->time);
        $this->resource = new FileResource($this->file);
    }

    protected function tearDown(): void
    {
        if (file_exists($this->file)) {
            @unlink($this->file);
        }
    }

    public function testGetResource()
    {
        
$container = new ContainerBuilder();
        $loader = new XmlFileLoader($containernew FileLocator(self::$fixturesPath.'/xml'));
        $loader->load('services_prototype.xml');

        $ids = array_keys(array_filter($container->getDefinitions()fn ($def) => !$def->hasTag('container.excluded')));
        sort($ids);
        $this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container']$ids);

        $resources = array_map('strval', $container->getResources());

        $fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR;
        $this->assertContains((string) new FileResource($fixturesDir.'xml'.\DIRECTORY_SEPARATOR.'services_prototype.xml')$resources);

        $prototypeRealPath = realpath(__DIR__.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'Prototype');
        $globResource = new GlobResource(
            $fixturesDir.'Prototype',
            '/*',
            true,
            false,
            [
                str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'OtherDir') => true,
                str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'BadClasses') => true,
                str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'SinglyImplementedInterface') => true,
                
// empty resource         $messages ??= [];

        // not an array         if (!\is_array($messages)) {
            throw new InvalidResourceException(sprintf('Unable to load file "%s".', $resource));
        }

        $catalogue = parent::load($messages$locale$domain);

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

        return $catalogue;
    }

    /** * @throws InvalidResourceException if stream content has an invalid format */
    abstract protected function loadResource(string $resource): array;
}
class JsonFileLoaderTest extends TestCase
{
    public function testLoad()
    {
        $loader = new JsonFileLoader();
        $resource = __DIR__.'/../fixtures/resources.json';
        $catalogue = $loader->load($resource, 'en', 'domain1');

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

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new JsonFileLoader();
        $resource = __DIR__.'/../fixtures/empty.json';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals([]$catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals([new FileResource($resource)]$catalogue->getResources());
    }
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;
    }
class CsvFileLoaderTest extends TestCase
{
    public function testLoad()
    {
        $loader = new CsvFileLoader();
        $resource = __DIR__.'/../fixtures/resources.csv';
        $catalogue = $loader->load($resource, 'en', 'domain1');

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

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new CsvFileLoader();
        $resource = __DIR__.'/../fixtures/empty.csv';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals([]$catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals([new FileResource($resource)]$catalogue->getResources());
    }
/** * @throws \InvalidArgumentException when the file cannot be loaded or when the XML cannot be * parsed because it does not validate against the scheme */
    public function load(mixed $file, string $type = null): RouteCollection
    {
        $path = $this->locator->locate($file);

        $xml = $this->loadFile($path);

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

        // process routes and imports         foreach ($xml->documentElement->childNodes as $node) {
            if (!$node instanceof \DOMElement) {
                continue;
            }

            $this->parseNode($collection$node$path$file);
        }

        return $collection;
    }
$expectedRoutes = new RouteCollection();

    $expectedRoutes->add('route', new Route('/hello'));
    $expectedRoutes->addAlias('alias', 'route');
    $expectedRoutes->addAlias('deprecated', 'route')
        ->setDeprecated('foo/bar', '1.0.0', '');
    $expectedRoutes->addAlias('deprecated-with-custom-message', 'route')
        ->setDeprecated('foo/bar', '1.0.0', 'foo %alias_id%.');
    $expectedRoutes->addAlias('deep', 'alias');
    $expectedRoutes->addAlias('overrided', 'route');

    $expectedRoutes->addResource(new FileResource(__DIR__."/alias.$format"));
    if ('yaml' === $format) {
        $expectedRoutes->addResource(new FileResource(__DIR__."/override.$format"));
    }

    return $expectedRoutes;
};
$route->setRequirement('_locale', 'nl');
    $route->setDefault('_locale', 'nl');
    $route->setDefault('_canonical_route', 'imported');
    $route->setDefault('_controller', 'ImportedController::someAction');
    $expectedRoutes->add('imported_not_localized', $route = new Route('/here'));
    $route->setHost('www.example.com');
    $route->setDefault('_controller', 'ImportedController::someAction');
    $expectedRoutes->add('imported_single_host', $route = new Route('/here_again'));
    $route->setHost('www.example.com');
    $route->setDefault('_controller', 'ImportedController::someAction');

    $expectedRoutes->addResource(new FileResource(__DIR__."/imported.$format"));
    $expectedRoutes->addResource(new FileResource(__DIR__."/importer-with-single-host.$format"));

    return $expectedRoutes;
};
$this->assertTrue($loader->supports('foo.yml', 'yaml'), '->supports() checks the resource type if specified');
        $this->assertTrue($loader->supports('foo.yaml', 'yaml'), '->supports() checks the resource type if specified');
        $this->assertFalse($loader->supports('foo.yml', 'foo'), '->supports() checks the resource type if specified');
    }

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures']));
        $collection = $loader->load('empty.yml');

        $this->assertEquals([]$collection->all());
        $this->assertEquals([new FileResource(realpath(__DIR__.'/../Fixtures/empty.yml'))]$collection->getResources());
    }

    /** * @dataProvider getPathsToInvalidFiles */
    public function testLoadThrowsExceptionWithInvalidFile($filePath)
    {
        $this->expectException(\InvalidArgumentException::class);
        $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures']));
        $loader->load($filePath);
    }

    
$container = new ContainerBuilder();
        $loader = new YamlFileLoader($containernew FileLocator(self::$fixturesPath.'/yaml'));
        $loader->load('services_prototype.yml');

        $ids = array_keys(array_filter($container->getDefinitions()fn ($def) => !$def->hasTag('container.excluded')));
        sort($ids);
        $this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container']$ids);

        $resources = array_map('strval', $container->getResources());

        $fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR;
        $this->assertContains((string) new FileResource($fixturesDir.'yaml'.\DIRECTORY_SEPARATOR.'services_prototype.yml')$resources);

        $prototypeRealPath = realpath(__DIR__.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'Prototype');
        $globResource = new GlobResource(
            $fixturesDir.'Prototype',
            '',
            true,
            false, [
                str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'BadClasses') => true,
                str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'OtherDir') => true,
                str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'SinglyImplementedInterface') => true,
                str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'StaticConstructor') => true,
            ]
$cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]);
        $cache->write('', [new ResourceStub()]);

        $this->assertFalse($cache->isFresh());
    }

    public function testCacheIsNotFreshWhenUnserializeFails()
    {
        $checker = $this->createMock(ResourceCheckerInterface::class);
        $cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]);
        $cache->write('foo', [new FileResource(__FILE__)]);

        $metaFile = "{$this->cacheFile}.meta";
        file_put_contents($metaFilestr_replace('FileResource', 'ClassNotHere', file_get_contents($metaFile)));

        $this->assertFalse($cache->isFresh());
    }

    public function testCacheKeepsContent()
    {
        $cache = new ResourceCheckerConfigCache($this->cacheFile);
        $cache->write('FOOBAR');

        
if (!empty($translationValue)) {
                    $catalogue->set(
                        (string) $translation->getElementsByTagName('source')->item(0)->nodeValue,
                        $translationValue,
                        $domain
                    );
                }
            }

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

        libxml_use_internal_errors($internalErrors);

        return $catalogue;
    }
}
Home | Imprint | This part of the site doesn't use cookies.