addLoader example


class ChainLoader extends Loader
{
    protected $loaders = [];

    /** * @param LoaderInterface[] $loaders */
    public function __construct(array $loaders = [])
    {
        foreach ($loaders as $loader) {
            $this->addLoader($loader);
        }
    }

    /** * @return void */
    public function addLoader(LoaderInterface $loader)
    {
        $this->loaders[] = $loader;
    }

    
public function testGetCatalogueReturnsConsolidatedCatalogue()
    {
        /* * This will be useful once we refactor so that different domains will be loaded lazily (on-demand). * In that case, getCatalogue() will probably have to load all missing domains in order to return * one complete catalogue. */

        $locale = 'whatever';
        $translator = new Translator($locale);
        $translator->addLoader('loader-a', new ArrayLoader());
        $translator->addLoader('loader-b', new ArrayLoader());
        $translator->addResource('loader-a', ['foo' => 'foofoo']$locale, 'domain-a');
        $translator->addResource('loader-b', ['bar' => 'foobar']$locale, 'domain-b');

        /* * Test that we get a single catalogue comprising messages * from different loaders and different domains */
        $catalogue = $translator->getCatalogue($locale);
        $this->assertTrue($catalogue->defines('foo', 'domain-a'));
        $this->assertTrue($catalogue->defines('bar', 'domain-b'));
    }
/** * @var LoaderInterface[] An array of LoaderInterface objects */
    private array $loaders = [];

    /** * @param LoaderInterface[] $loaders An array of loaders */
    public function __construct(array $loaders = [])
    {
        foreach ($loaders as $loader) {
            $this->addLoader($loader);
        }
    }

    public function resolve(mixed $resource, string $type = null): LoaderInterface|false
    {
        foreach ($this->loaders as $loader) {
            if ($loader->supports($resource$type)) {
                return $loader;
            }
        }

        
use Symfony\Component\Validator\Validation;

/** * @author Kévin Dunglas <dunglas@gmail.com> */
class DoctrineLoaderTest extends TestCase
{
    public function testLoadClassMetadata()
    {
        $validator = Validation::createValidatorBuilder()
            ->enableAttributeMapping()
            ->addLoader(new DoctrineLoader(DoctrineTestHelper::createTestEntityManager(), '{^Symfony\\\\Bridge\\\\Doctrine\\\\Tests\\\\Fixtures\\\\DoctrineLoader}'))
            ->getValidator()
        ;

        $classMetadata = $validator->getMetadataFor(new DoctrineLoaderEntity());

        $classConstraints = $classMetadata->getConstraints();
        $this->assertCount(2, $classConstraints);
        $this->assertInstanceOf(UniqueEntity::class$classConstraints[0]);
        $this->assertInstanceOf(UniqueEntity::class$classConstraints[1]);
        $this->assertSame(['alreadyMappedUnique']$classConstraints[0]->fields);
        $this->assertSame('unique', $classConstraints[1]->fields);

        
final class ChainLoader implements LoaderInterface
{
    private $hasSourceCache = [];
    private $loaders = [];

    /** * @param LoaderInterface[] $loaders */
    public function __construct(array $loaders = [])
    {
        foreach ($loaders as $loader) {
            $this->addLoader($loader);
        }
    }

    public function addLoader(LoaderInterface $loader): void
    {
        $this->loaders[] = $loader;
        $this->hasSourceCache = [];
    }

    /** * @return LoaderInterface[] */
$localTranslatorBag->addCatalogue($xliffLoader->load($filenameFr, 'fr'));

        $provider->expects($this->once())
            ->method('write')
            ->with($localTranslatorBag->diff($providerReadTranslatorBag));

        $provider->expects($this->once())
            ->method('__toString')
            ->willReturn('null://default');

        $reader = new TranslationReader();
        $reader->addLoader('xlf', new XliffFileLoader());

        $command = new TranslationPushCommand(
            new TranslationProviderCollection([
                'loco' => $provider,
            ]),
            $reader,
            [$this->translationAppDir.'/translations'],
            $locales
        );

        $application = new Application();
        
true,
                true,
                false,
                true
            ))
        ;

        $propertyInfoLoader = new PropertyInfoLoader($propertyInfoStub$propertyInfoStub$propertyInfoStub, '{.*}');

        $validator = Validation::createValidatorBuilder()
            ->enableAttributeMapping()
            ->addLoader($propertyInfoLoader)
            ->getValidator()
        ;

        $classMetadata = $validator->getMetadataFor(new PropertyInfoLoaderEntity());

        $nullableStringMetadata = $classMetadata->getPropertyMetadata('nullableString');
        $this->assertCount(1, $nullableStringMetadata);
        $nullableStringConstraints = $nullableStringMetadata[0]->getConstraints();
        $this->assertCount(1, $nullableStringConstraints);
        $this->assertInstanceOf(TypeConstraint::class$nullableStringConstraints[0]);
        $this->assertSame('string', $nullableStringConstraints[0]->type);

        
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Component\Translation\Translator;

class TranslatableTest extends TestCase
{
    /** * @dataProvider getTransTests */
    public function testTrans(string $expected, TranslatableMessage $translatable, array $translation, string $locale)
    {
        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', $translation$locale$translatable->getDomain());

        $this->assertSame($expected$translatable->trans($translator$locale));
    }

    /** * @dataProvider getFlattenedTransTests */
    public function testFlattenedTrans($expected$messages$translatable)
    {
        $translator = new Translator('en');
        


            'base' => ' {%- block content "" %} ',
        ];

        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', ['foo' => 'foo (messages)'], 'en');
        $translator->addResource('array', ['foo' => 'foo (custom)'], 'en', 'custom');
        $translator->addResource('array', ['foo' => 'foo (foo)'], 'en', 'foo');

        $template = $this->getTemplate($templates$translator);

        $this->assertEquals('foo (foo)foo (custom)foo (foo)foo (custom)foo (foo)foo (custom)', trim($template->render([])));
    }

    public function testDefaultTranslationDomainWithNamedArguments()
    {
        
'state' => DataCollectorTranslator::MESSAGE_EQUALS_FALLBACK,
            'parameters' => ['foo' => 'bar'],
            'transChoiceNumber' => null,
        ];

        $this->assertEquals($expectedMessages$collector->getCollectedMessages());
    }

    private function createCollector()
    {
        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', ['foo' => 'foo (en)'], 'en');
        $translator->addResource('array', ['bar' => 'bar (fr)'], 'fr');
        $translator->addResource('array', ['bar_ru' => 'bar (ru)'], 'ru');

        return new DataCollectorTranslator($translator);
    }
}
if ($this->resourceFiles) {
            $this->addResourceFiles();
        }
        foreach ($this->resources as $params) {
            [$format$resource$locale$domain] = $params;
            parent::addResource($format$resource$locale$domain);
        }
        $this->resources = [];

        foreach ($this->loaderIds as $id => $aliases) {
            foreach ($aliases as $alias) {
                $this->addLoader($alias$this->container->get($id));
            }
        }
    }

    private function addResourceFiles(): void
    {
        $filesByLocale = $this->resourceFiles;
        $this->resourceFiles = [];

        foreach ($filesByLocale as $files) {
            foreach ($files as $file) {
                
return new CommandTester($application->find('translation:pull'));
    }

    private function createCommand(ProviderInterface $provider, array $locales = ['en'], array $domains = ['messages']$defaultLocale = 'en', array $providerNames = ['loco']): TranslationPullCommand
    {
        $writer = new TranslationWriter();
        $writer->addDumper('xlf', new XliffFileDumper());
        $writer->addDumper('yml', new YamlFileDumper());

        $reader = new TranslationReader();
        $reader->addLoader('xlf', new XliffFileLoader());
        $reader->addLoader('yml', new YamlFileLoader());

        return new TranslationPullCommand(
            $this->getProviderCollection($provider$providerNames$locales$domains),
            $writer,
            $reader,
            $defaultLocale,
            [$this->translationAppDir.'/translations'],
            $locales
        );
    }
}


    public function testConstructor()
    {
        $loader = new ProjectTemplateChainLoader([$this->loader1, $this->loader2]);
        $this->assertEquals([$this->loader1, $this->loader2]$loader->getLoaders(), '__construct() takes an array of template loaders as its second argument');
    }

    public function testAddLoader()
    {
        $loader = new ProjectTemplateChainLoader([$this->loader1]);
        $loader->addLoader($this->loader2);
        $this->assertEquals([$this->loader1, $this->loader2]$loader->getLoaders(), '->addLoader() adds a template loader at the end of the loaders');
    }

    public function testLoad()
    {
        $loader = new ProjectTemplateChainLoader([$this->loader1, $this->loader2]);
        $this->assertFalse($loader->load(new TemplateReference('bar', 'php')), '->load() returns false if the template is not found');
        $this->assertFalse($loader->load(new TemplateReference('foo', 'php')), '->load() returns false if the template does not exist for the given renderer');
        $this->assertInstanceOf(
            'Symfony\Component\Templating\Storage\FileStorage',
            $loader->load(new TemplateReference('foo.php', 'php')),
            

        if (!class_exists(\MessageFormatter::class)) {
            $this->markTestSkipped(sprintf('Skipping test as the required "%s" class does not exist. Consider installing the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.', \MessageFormatter::class));
        }

        $locale = 'any_locale';
        $format = 'some_format';
        $msgid = 'test';

        // Prime the cache         $translator = new Translator($locale, null, $this->tmpDir, $debug);
        $translator->addLoader($formatnew ArrayLoader());
        $translator->addResource($format[$msgid => 'OK']$locale);
        $translator->addResource($format[$msgid.'+intl' => 'OK']$locale, 'messages+intl-icu');
        $translator->trans($msgid);
        $translator->trans($msgid.'+intl', [], 'messages+intl-icu');

        // Try again and see we get a valid result whilst no loader can be used         $translator = new Translator($locale, null, $this->tmpDir, $debug);
        $translator->addLoader($format$this->createFailingLoader());
        $translator->addResource($format[$msgid => 'OK']$locale);
        $translator->addResource($format[$msgid.'+intl' => 'OK']$locale, 'messages+intl-icu');
        $this->assertEquals('OK', $translator->trans($msgid), '-> caching does not work in '.($debug ? 'debug' : 'production'));
        
$this->assertFalse($resolver->resolve('foo.foo'), '->resolve() returns false if no loader is able to load the resource');

        $loader = $this->createMock(LoaderInterface::class);
        $loader->expects($this->once())->method('supports')->willReturn(true);
        $resolver = new LoaderResolver([$loader]);
        $this->assertEquals($loader$resolver->resolve(function D) {}), '->resolve() returns the loader for the given resource');
    }

    public function testLoaders()
    {
        $resolver = new LoaderResolver();
        $resolver->addLoader($loader = $this->createMock(LoaderInterface::class));

        $this->assertEquals([$loader]$resolver->getLoaders(), 'addLoader() adds a loader');
    }
}
Home | Imprint | This part of the site doesn't use cookies.