Merge branch '3.4' into 4.0

* 3.4:
  [Serializer] optims and cleanup
  do not mock the container builder in tests
  [PhpUnitBridge] Added support for PHPUnit 7 in Coverage Listener
  fix accessing request values
  Avoid running the remove command without any packages
  [Form] Add translations for Tagalog
This commit is contained in:
Nicolas Grekas 2018-02-14 15:11:10 +01:00
commit 8faf29f54e
33 changed files with 402 additions and 483 deletions

View File

@ -11,34 +11,10 @@
namespace Symfony\Bridge\PhpUnit;
use PHPUnit\Framework\BaseTestListener;
use PHPUnit\Framework\Test;
use Symfony\Bridge\PhpUnit\Legacy\CoverageListenerTrait;
if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version::id(), '6.0.0', '<')) {
class_alias('Symfony\Bridge\PhpUnit\Legacy\CoverageListener', 'Symfony\Bridge\PhpUnit\CoverageListener');
// Using an early return instead of a else does not work when using the PHPUnit
// phar due to some weird PHP behavior (the class gets defined without executing
// the code before it and so the definition is not properly conditional)
class_alias('Symfony\Bridge\PhpUnit\Legacy\CoverageListenerForV5', 'Symfony\Bridge\PhpUnit\CoverageListener');
} elseif (version_compare(\PHPUnit\Runner\Version::id(), '7.0.0', '<')) {
class_alias('Symfony\Bridge\PhpUnit\Legacy\CoverageListenerForV6', 'Symfony\Bridge\PhpUnit\CoverageListener');
} else {
/**
* CoverageListener adds `@covers <className>` on each test suite when possible
* to make the code coverage more accurate.
*
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
class CoverageListener extends BaseTestListener
{
private $trait;
public function __construct(callable $sutFqcnResolver = null, $warningOnSutNotFound = false)
{
$this->trait = new CoverageListenerTrait($sutFqcnResolver, $warningOnSutNotFound);
}
public function startTest(Test $test)
{
$this->trait->startTest($test);
}
}
class_alias('Symfony\Bridge\PhpUnit\Legacy\CoverageListenerForV7', 'Symfony\Bridge\PhpUnit\CoverageListener');
}

View File

@ -19,7 +19,7 @@ namespace Symfony\Bridge\PhpUnit\Legacy;
*
* @internal
*/
class CoverageListener extends \PHPUnit_Framework_BaseTestListener
class CoverageListenerForV5 extends \PHPUnit_Framework_BaseTestListener
{
private $trait;

View File

@ -0,0 +1,38 @@
<?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\Bridge\PhpUnit\Legacy;
use PHPUnit\Framework\BaseTestListener;
use PHPUnit\Framework\Test;
/**
* CoverageListener adds `@covers <className>` on each test suite when possible
* to make the code coverage more accurate.
*
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*
* @internal
*/
class CoverageListenerForV6 extends BaseTestListener
{
private $trait;
public function __construct(callable $sutFqcnResolver = null, $warningOnSutNotFound = false)
{
$this->trait = new CoverageListenerTrait($sutFqcnResolver, $warningOnSutNotFound);
}
public function startTest(Test $test)
{
$this->trait->startTest($test);
}
}

View File

@ -0,0 +1,41 @@
<?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\Bridge\PhpUnit\Legacy;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
use PHPUnit\Framework\TestSuite;
/**
* CoverageListener adds `@covers <className>` on each test suite when possible
* to make the code coverage more accurate.
*
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*
* @internal
*/
class CoverageListenerForV7 implements TestListener
{
use TestListenerDefaultImplementation;
private $trait;
public function __construct(callable $sutFqcnResolver = null, $warningOnSutNotFound = false)
{
$this->trait = new CoverageListenerTrait($sutFqcnResolver, $warningOnSutNotFound);
}
public function startTestSuite(TestSuite $suite): void
{
$this->trait->startTest($test);
}
}

View File

@ -12,7 +12,9 @@ class CoverageListenerTest extends TestCase
$this->markTestSkipped('This test cannot be run on Windows.');
}
if (\PHP_VERSION_ID >= 70000) {
exec('type phpdbg', $output, $returnCode);
if (\PHP_VERSION_ID >= 70000 && 0 === $returnCode) {
$php = 'phpdbg -qrr';
} else {
exec('php --ri xdebug -d zend_extension=xdebug.so 2> /dev/null', $output, $returnCode);

View File

@ -13,7 +13,13 @@ require __DIR__.'/../src/BarCov.php';
require __DIR__.'/../src/FooCov.php';
require __DIR__.'/../../../../Legacy/CoverageListenerTrait.php';
if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version::id(), '6.0.0', '<')) {
require __DIR__.'/../../../../Legacy/CoverageListener.php';
require_once __DIR__.'/../../../../Legacy/CoverageListenerForV5.php';
} elseif (version_compare(\PHPUnit\Runner\Version::id(), '7.0.0', '<')) {
require_once __DIR__.'/../../../../Legacy/CoverageListenerForV6.php';
} else {
require_once __DIR__.'/../../../../Legacy/CoverageListenerForV7.php';
}
require __DIR__.'/../../../../CoverageListener.php';

View File

@ -77,7 +77,9 @@ if (!file_exists("$PHPUNIT_DIR/phpunit-$PHPUNIT_VERSION/phpunit") || md5_file(__
$zip->extractTo(getcwd());
$zip->close();
chdir("phpunit-$PHPUNIT_VERSION");
passthru("$COMPOSER remove --no-update ".$SYMFONY_PHPUNIT_REMOVE);
if ($SYMFONY_PHPUNIT_REMOVE) {
passthru("$COMPOSER remove --no-update ".$SYMFONY_PHPUNIT_REMOVE);
}
if (5.1 <= $PHPUNIT_VERSION && $PHPUNIT_VERSION < 5.4) {
passthru("$COMPOSER require --no-update phpunit/phpunit-mock-objects \"~3.1.0\"");
}

View File

@ -44,27 +44,17 @@ class CachePoolPrunerPassTest extends TestCase
public function testCompilePassIsIgnoredIfCommandDoesNotExist()
{
$container = $this
->getMockBuilder(ContainerBuilder::class)
->setMethods(array('hasDefinition', 'getDefinition', 'findTaggedServiceIds'))
->getMock();
$container = new ContainerBuilder();
$container
->expects($this->atLeastOnce())
->method('hasDefinition')
->with(CachePoolPruneCommand::class)
->will($this->returnValue(false));
$container
->expects($this->never())
->method('getDefinition');
$container
->expects($this->never())
->method('findTaggedServiceIds');
$definitionsBefore = count($container->getDefinitions());
$aliasesBefore = count($container->getAliases());
$pass = new CachePoolPrunerPass();
$pass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
/**

View File

@ -13,96 +13,69 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\LoggingTranslatorPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class LoggingTranslatorPassTest extends TestCase
{
public function testProcess()
{
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
$parameterBag = $this->getMockBuilder('Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface')->getMock();
$container->expects($this->exactly(2))
->method('hasAlias')
->will($this->returnValue(true));
$container->expects($this->once())
->method('getParameter')
->will($this->returnValue(true));
$container->expects($this->once())
->method('getAlias')
->will($this->returnValue('translation.default'));
$container->expects($this->exactly(3))
->method('getDefinition')
->will($this->returnValue($definition));
$container->expects($this->once())
->method('hasParameter')
->with('translator.logging')
->will($this->returnValue(true));
$definition->expects($this->once())
->method('getClass')
->will($this->returnValue('Symfony\Bundle\FrameworkBundle\Translation\Translator'));
$parameterBag->expects($this->once())
->method('resolveValue')
->will($this->returnValue("Symfony\Bundle\FrameworkBundle\Translation\Translator"));
$container->expects($this->once())
->method('getParameterBag')
->will($this->returnValue($parameterBag));
$container->expects($this->once())
->method('getReflectionClass')
->with('Symfony\Bundle\FrameworkBundle\Translation\Translator')
->will($this->returnValue(new \ReflectionClass('Symfony\Bundle\FrameworkBundle\Translation\Translator')));
$definition->expects($this->once())
->method('getTag')
->with('container.service_subscriber')
->willReturn(array(array('id' => 'translator'), array('id' => 'foo')));
$definition->expects($this->once())
->method('clearTag')
->with('container.service_subscriber');
$definition->expects($this->any())
->method('addTag')
->withConsecutive(
array('container.service_subscriber', array('id' => 'foo')),
array('container.service_subscriber', array('key' => 'translator', 'id' => 'translator.logging.inner'))
);
$container = new ContainerBuilder();
$container->setParameter('translator.logging', true);
$container->setParameter('translator.class', 'Symfony\Component\Translation\Translator');
$container->register('monolog.logger');
$container->setAlias('logger', 'monolog.logger');
$container->register('translator.default', '%translator.class%');
$container->register('translator.logging', '%translator.class%');
$container->setAlias('translator', 'translator.default');
$translationWarmerDefinition = $container->register('translation.warmer')
->addArgument(new Reference('translator'))
->addTag('container.service_subscriber', array('id' => 'translator'))
->addTag('container.service_subscriber', array('id' => 'foo'));
$pass = new LoggingTranslatorPass();
$pass->process($container);
$this->assertEquals(
array('container.service_subscriber' => array(
array('id' => 'foo'),
array('key' => 'translator', 'id' => 'translator.logging.inner'),
)),
$translationWarmerDefinition->getTags()
);
}
public function testThatCompilerPassIsIgnoredIfThereIsNotLoggerDefinition()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
$container->expects($this->once())
->method('hasAlias')
->will($this->returnValue(false));
$container = new ContainerBuilder();
$container->register('identity_translator');
$container->setAlias('translator', 'identity_translator');
$definitionsBefore = count($container->getDefinitions());
$aliasesBefore = count($container->getAliases());
$pass = new LoggingTranslatorPass();
$pass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
public function testThatCompilerPassIsIgnoredIfThereIsNotTranslatorDefinition()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
$container->expects($this->at(0))
->method('hasAlias')
->will($this->returnValue(true));
$container = new ContainerBuilder();
$container->register('monolog.logger');
$container->setAlias('logger', 'monolog.logger');
$container->expects($this->at(0))
->method('hasAlias')
->will($this->returnValue(false));
$definitionsBefore = count($container->getDefinitions());
$aliasesBefore = count($container->getAliases());
$pass = new LoggingTranslatorPass();
$pass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
}

View File

@ -13,6 +13,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\UnusedTagsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class UnusedTagsPassTest extends TestCase
{
@ -20,24 +21,14 @@ class UnusedTagsPassTest extends TestCase
{
$pass = new UnusedTagsPass();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('findTaggedServiceIds', 'findUnusedTags', 'findTags', 'log'))->getMock();
$container->expects($this->once())
->method('log')
->with($pass, 'Tag "kenrel.event_subscriber" was defined on service(s) "foo", "bar", but was never used. Did you mean "kernel.event_subscriber"?');
$container->expects($this->once())
->method('findTags')
->will($this->returnValue(array('kenrel.event_subscriber')));
$container->expects($this->once())
->method('findUnusedTags')
->will($this->returnValue(array('kenrel.event_subscriber', 'form.type')));
$container->expects($this->once())
->method('findTaggedServiceIds')
->with('kenrel.event_subscriber')
->will($this->returnValue(array(
'foo' => array(),
'bar' => array(),
)));
$container = new ContainerBuilder();
$container->register('foo')
->addTag('kenrel.event_subscriber');
$container->register('bar')
->addTag('kenrel.event_subscriber');
$pass->process($container);
$this->assertSame(array(sprintf('%s: Tag "kenrel.event_subscriber" was defined on service(s) "foo", "bar", but was never used. Did you mean "kernel.event_subscriber"?', UnusedTagsPass::class)), $container->getCompiler()->getLog());
}
}

View File

@ -12,7 +12,6 @@
namespace Symfony\Bundle\TwigBundle\Tests\DependencyInjection\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\TwigLoaderPass;

View File

@ -12,7 +12,10 @@
namespace Symfony\Component\DependencyInjection\Tests\Compiler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ExtensionCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
/**
* @author Wouter J <wouter@wouterj.nl>
@ -24,33 +27,55 @@ class ExtensionCompilerPassTest extends TestCase
protected function setUp()
{
$this->container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
$this->container = new ContainerBuilder();
$this->pass = new ExtensionCompilerPass();
}
public function testProcess()
{
$extension1 = $this->createExtensionMock(true);
$extension1->expects($this->once())->method('process');
$extension2 = $this->createExtensionMock(false);
$extension3 = $this->createExtensionMock(false);
$extension4 = $this->createExtensionMock(true);
$extension4->expects($this->once())->method('process');
$extension1 = new CompilerPassExtension('extension1');
$extension2 = new DummyExtension('extension2');
$extension3 = new DummyExtension('extension3');
$extension4 = new CompilerPassExtension('extension4');
$this->container->expects($this->any())
->method('getExtensions')
->will($this->returnValue(array($extension1, $extension2, $extension3, $extension4)))
;
$this->container->registerExtension($extension1);
$this->container->registerExtension($extension2);
$this->container->registerExtension($extension3);
$this->container->registerExtension($extension4);
$this->pass->process($this->container);
}
private function createExtensionMock($hasInlineCompile)
{
return $this->getMockBuilder('Symfony\Component\DependencyInjection\\'.(
$hasInlineCompile
? 'Compiler\CompilerPassInterface'
: 'Extension\ExtensionInterface'
))->getMock();
$this->assertTrue($this->container->hasDefinition('extension1'));
$this->assertFalse($this->container->hasDefinition('extension2'));
$this->assertFalse($this->container->hasDefinition('extension3'));
$this->assertTrue($this->container->hasDefinition('extension4'));
}
}
class DummyExtension extends Extension
{
private $alias;
public function __construct($alias)
{
$this->alias = $alias;
}
public function getAlias()
{
return $this->alias;
}
public function load(array $configs, ContainerBuilder $container)
{
}
public function process(ContainerBuilder $container)
{
$container->register($this->alias);
}
}
class CompilerPassExtension extends DummyExtension implements CompilerPassInterface
{
}

View File

@ -27,29 +27,10 @@ class RegisterListenersPassTest extends TestCase
*/
public function testEventSubscriberWithoutInterface()
{
// one service, not implementing any interface
$services = array(
'my_event_subscriber' => array(0 => array()),
);
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('stdClass'));
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.event_listener here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->onConsecutiveCalls(array(), $services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->returnValue($definition));
$builder = new ContainerBuilder();
$builder->register('event_dispatcher');
$builder->register('my_event_subscriber', 'stdClass')
->addTag('kernel.event_subscriber');
$registerListenersPass = new RegisterListenersPass();
$registerListenersPass->process($builder);
@ -61,31 +42,25 @@ class RegisterListenersPassTest extends TestCase
'my_event_subscriber' => array(0 => array()),
);
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService'));
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition', 'findDefinition'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.event_listener here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->onConsecutiveCalls(array(), $services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->returnValue($definition));
$builder->expects($this->atLeastOnce())
->method('findDefinition')
->will($this->returnValue($definition));
$builder = new ContainerBuilder();
$eventDispatcherDefinition = $builder->register('event_dispatcher');
$builder->register('my_event_subscriber', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService')
->addTag('kernel.event_subscriber');
$registerListenersPass = new RegisterListenersPass();
$registerListenersPass->process($builder);
$expectedCalls = array(
array(
'addListener',
array(
'event',
array(new ServiceClosureArgument(new Reference('my_event_subscriber')), 'onEvent'),
0,
),
),
);
$this->assertEquals($expectedCalls, $eventDispatcherDefinition->getMethodCalls());
}
/**

View File

@ -0,0 +1,19 @@
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="28">
<source>This form should not contain extra fields.</source>
<target>Ang pormang itong ay hindi dapat magkarron ng dagdag na mga patlang.</target>
</trans-unit>
<trans-unit id="29">
<source>The uploaded file was too large. Please try to upload a smaller file.</source>
<target>Ang ini-upload na file ay masyadong malaki. Pakiulit muling mag-upload ng mas maliit na file.</target>
</trans-unit>
<trans-unit id="30">
<source>The CSRF token is invalid. Please try to resubmit the form.</source>
<target>Hindi balido ang CSRF token. Maagpasa muli ng isang pang porma.</target>
</trans-unit>
</body>
</file>
</xliff>

View File

@ -12,8 +12,10 @@
namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\DependencyInjection\FragmentRendererPass;
use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
@ -22,73 +24,37 @@ class FragmentRendererPassTest extends TestCase
{
/**
* Tests that content rendering not implementing FragmentRendererInterface
* trigger an exception.
* triggers an exception.
*
* @expectedException \InvalidArgumentException
*/
public function testContentRendererWithoutInterface()
{
// one service, not implementing any interface
$services = array(
'my_content_renderer' => array(array('alias' => 'foo')),
);
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.fragment_renderer here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->returnValue($definition));
$builder = new ContainerBuilder();
$fragmentHandlerDefinition = $builder->register('fragment.handler');
$builder->register('my_content_renderer', 'Symfony\Component\DependencyInjection\Definition')
->addTag('kernel.fragment_renderer', array('alias' => 'foo'));
$pass = new FragmentRendererPass();
$pass->process($builder);
$this->assertEquals(array(array('addRendererService', array('foo', 'my_content_renderer'))), $fragmentHandlerDefinition->getMethodCalls());
}
public function testValidContentRenderer()
{
$services = array(
'my_content_renderer' => array(array('alias' => 'foo')),
);
$renderer = new Definition('', array(null));
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('Symfony\Component\HttpKernel\Tests\DependencyInjection\RendererService'));
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition', 'getReflectionClass'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
// We don't test kernel.fragment_renderer here
$builder->expects($this->atLeastOnce())
->method('findTaggedServiceIds')
->will($this->returnValue($services));
$builder->expects($this->atLeastOnce())
->method('getDefinition')
->will($this->onConsecutiveCalls($renderer, $definition));
$builder->expects($this->atLeastOnce())
->method('getReflectionClass')
->with('Symfony\Component\HttpKernel\Tests\DependencyInjection\RendererService')
->will($this->returnValue(new \ReflectionClass('Symfony\Component\HttpKernel\Tests\DependencyInjection\RendererService')));
$builder = new ContainerBuilder();
$fragmentHandlerDefinition = $builder->register('fragment.handler')
->addArgument(null);
$builder->register('my_content_renderer', 'Symfony\Component\HttpKernel\Tests\DependencyInjection\RendererService')
->addTag('kernel.fragment_renderer', array('alias' => 'foo'));
$pass = new FragmentRendererPass();
$pass->process($builder);
$this->assertInstanceOf(Reference::class, $renderer->getArgument(0));
$serviceLocatorDefinition = $builder->getDefinition((string) $fragmentHandlerDefinition->getArgument(0));
$this->assertSame(ServiceLocator::class, $serviceLocatorDefinition->getClass());
$this->assertEquals(array('foo' => new ServiceClosureArgument(new Reference('my_content_renderer'))), $serviceLocatorDefinition->getArgument(0));
}
}

View File

@ -54,24 +54,16 @@ class PropertyInfoPassTest extends TestCase
public function testReturningEmptyArrayWhenNoService()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('findTaggedServiceIds'))->getMock();
$container
->expects($this->any())
->method('findTaggedServiceIds')
->will($this->returnValue(array()))
;
$container = new ContainerBuilder();
$propertyInfoExtractorDefinition = $container->register('property_info')
->setArguments(array(array(), array(), array(), array()));
$propertyInfoPass = new PropertyInfoPass();
$propertyInfoPass->process($container);
$method = new \ReflectionMethod(
'Symfony\Component\PropertyInfo\DependencyInjection\PropertyInfoPass',
'findAndSortTaggedServices'
);
$method->setAccessible(true);
$actual = $method->invoke($propertyInfoPass, 'tag', $container);
$this->assertEquals(array(), $actual);
$this->assertEquals(new IteratorArgument(array()), $propertyInfoExtractorDefinition->getArgument(0));
$this->assertEquals(new IteratorArgument(array()), $propertyInfoExtractorDefinition->getArgument(1));
$this->assertEquals(new IteratorArgument(array()), $propertyInfoExtractorDefinition->getArgument(2));
$this->assertEquals(new IteratorArgument(array()), $propertyInfoExtractorDefinition->getArgument(3));
}
}

View File

@ -85,9 +85,13 @@ class SimpleFormAuthenticationListener extends AbstractAuthenticationListener
}
}
$requestBag = $this->options['post_only'] ? $request->request : $request;
$username = ParameterBagUtils::getParameterBagValue($requestBag, $this->options['username_parameter']);
$password = ParameterBagUtils::getParameterBagValue($requestBag, $this->options['password_parameter']);
if ($this->options['post_only']) {
$username = ParameterBagUtils::getParameterBagValue($request->request, $this->options['username_parameter']);
$password = ParameterBagUtils::getParameterBagValue($request->request, $this->options['password_parameter']);
} else {
$username = ParameterBagUtils::getRequestParameterValue($request, $this->options['username_parameter']);
$password = ParameterBagUtils::getRequestParameterValue($request, $this->options['password_parameter']);
}
if (!\is_string($username) || (\is_object($username) && !\method_exists($username, '__toString'))) {
throw new BadRequestHttpException(sprintf('The key "%s" must be a string, "%s" given.', $this->options['username_parameter'], \gettype($username)));

View File

@ -34,13 +34,13 @@ class Groups
public function __construct(array $data)
{
if (!isset($data['value']) || !$data['value']) {
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" cannot be empty.', get_class($this)));
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" cannot be empty.', \get_class($this)));
}
$value = (array) $data['value'];
foreach ($value as $group) {
if (!is_string($group)) {
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" must be a string or an array of strings.', get_class($this)));
if (!\is_string($group)) {
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" must be a string or an array of strings.', \get_class($this)));
}
}

View File

@ -245,17 +245,17 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa
$value = $this->parseXmlValue($node, $context);
if (!count($data)) {
if (!\count($data)) {
return $value;
}
if (!is_array($value)) {
if (!\is_array($value)) {
$data['#'] = $value;
return $data;
}
if (1 === count($value) && key($value)) {
if (1 === \count($value) && key($value)) {
$data[key($value)] = current($value);
return $data;
@ -310,7 +310,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa
return $node->nodeValue;
}
if (1 === $node->childNodes->length && in_array($node->firstChild->nodeType, array(XML_TEXT_NODE, XML_CDATA_SECTION_NODE))) {
if (1 === $node->childNodes->length && \in_array($node->firstChild->nodeType, array(XML_TEXT_NODE, XML_CDATA_SECTION_NODE))) {
return $node->firstChild->nodeValue;
}
@ -335,7 +335,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa
}
foreach ($value as $key => $val) {
if (is_array($val) && 1 === count($val)) {
if (\is_array($val) && 1 === \count($val)) {
$value[$key] = current($val);
}
}
@ -355,7 +355,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa
{
$append = true;
if (is_array($data) || ($data instanceof \Traversable && !$this->serializer->supportsNormalization($data, $this->format))) {
if (\is_array($data) || ($data instanceof \Traversable && !$this->serializer->supportsNormalization($data, $this->format))) {
foreach ($data as $key => $data) {
//Ah this is the magic @ attribute types.
if (0 === strpos($key, '@') && $this->isElementNameValid($attributeName = substr($key, 1))) {
@ -365,7 +365,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa
$parentNode->setAttribute($attributeName, $data);
} elseif ('#' === $key) {
$append = $this->selectNodeType($parentNode, $data);
} elseif (is_array($data) && false === is_numeric($key)) {
} elseif (\is_array($data) && false === is_numeric($key)) {
// Is this array fully numeric keys?
if (ctype_digit(implode('', array_keys($data)))) {
/*
@ -389,7 +389,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa
return $append;
}
if (is_object($data)) {
if (\is_object($data)) {
$data = $this->serializer->normalize($data, $this->format, $this->context);
if (null !== $data && !is_scalar($data)) {
return $this->buildXml($parentNode, $data, $xmlRootNodeName);
@ -448,22 +448,22 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa
*/
private function selectNodeType(\DOMNode $node, $val): bool
{
if (is_array($val)) {
if (\is_array($val)) {
return $this->buildXml($node, $val);
} elseif ($val instanceof \SimpleXMLElement) {
$child = $this->dom->importNode(dom_import_simplexml($val), true);
$node->appendChild($child);
} elseif ($val instanceof \Traversable) {
$this->buildXml($node, $val);
} elseif (is_object($val)) {
} elseif (\is_object($val)) {
return $this->selectNodeType($node, $this->serializer->normalize($val, $this->format, $this->context));
} elseif (is_numeric($val)) {
return $this->appendText($node, (string) $val);
} elseif (is_string($val) && $this->needsCdataWrapping($val)) {
} elseif (\is_string($val) && $this->needsCdataWrapping($val)) {
return $this->appendCData($node, $val);
} elseif (is_string($val)) {
} elseif (\is_string($val)) {
return $this->appendText($node, $val);
} elseif (is_bool($val)) {
} elseif (\is_bool($val)) {
return $this->appendText($node, (int) $val);
} elseif ($val instanceof \DOMNode) {
$child = $this->dom->importNode($val, true);

View File

@ -59,7 +59,7 @@ class AttributeMetadata implements AttributeMetadataInterface
*/
public function addGroup($group)
{
if (!in_array($group, $this->groups)) {
if (!\in_array($group, $this->groups)) {
$this->groups[] = $group;
}
}

View File

@ -40,7 +40,7 @@ class LoaderChain implements LoaderInterface
{
foreach ($loaders as $loader) {
if (!$loader instanceof LoaderInterface) {
throw new MappingException(sprintf('Class %s is expected to implement LoaderInterface', get_class($loader)));
throw new MappingException(sprintf('Class %s is expected to implement LoaderInterface', \get_class($loader)));
}
}

View File

@ -30,7 +30,7 @@ class YamlFileLoader extends FileLoader
*
* @var array
*/
private $classes = null;
private $classes;
/**
* {@inheritdoc}
@ -51,7 +51,7 @@ class YamlFileLoader extends FileLoader
$yaml = $this->classes[$classMetadata->getName()];
if (isset($yaml['attributes']) && is_array($yaml['attributes'])) {
if (isset($yaml['attributes']) && \is_array($yaml['attributes'])) {
$attributesMetadata = $classMetadata->getAttributesMetadata();
foreach ($yaml['attributes'] as $attribute => $data) {
@ -63,12 +63,12 @@ class YamlFileLoader extends FileLoader
}
if (isset($data['groups'])) {
if (!is_array($data['groups'])) {
if (!\is_array($data['groups'])) {
throw new MappingException(sprintf('The "groups" key must be an array of strings in "%s" for the attribute "%s" of the class "%s".', $this->file, $attribute, $classMetadata->getName()));
}
foreach ($data['groups'] as $group) {
if (!is_string($group)) {
if (!\is_string($group)) {
throw new MappingException(sprintf('Group names must be strings in "%s" for the attribute "%s" of the class "%s".', $this->file, $attribute, $classMetadata->getName()));
}
@ -119,7 +119,7 @@ class YamlFileLoader extends FileLoader
return array();
}
if (!is_array($classes)) {
if (!\is_array($classes)) {
throw new MappingException(sprintf('The file "%s" must contain a YAML array.', $this->file));
}

View File

@ -36,7 +36,7 @@ class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface
*/
public function normalize($propertyName)
{
if (null === $this->attributes || in_array($propertyName, $this->attributes)) {
if (null === $this->attributes || \in_array($propertyName, $this->attributes)) {
return strtolower(preg_replace('/[A-Z]/', '_\\0', lcfirst($propertyName)));
}
@ -56,7 +56,7 @@ class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface
$camelCasedName = lcfirst($camelCasedName);
}
if (null === $this->attributes || in_array($camelCasedName, $this->attributes)) {
if (null === $this->attributes || \in_array($camelCasedName, $this->attributes)) {
return $camelCasedName;
}

View File

@ -121,7 +121,7 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
public function setCallbacks(array $callbacks)
{
foreach ($callbacks as $attribute => $callback) {
if (!is_callable($callback)) {
if (!\is_callable($callback)) {
throw new InvalidArgumentException(sprintf(
'The given callback for attribute "%s" is not callable.',
$attribute
@ -189,10 +189,10 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
protected function handleCircularReference($object)
{
if ($this->circularReferenceHandler) {
return call_user_func($this->circularReferenceHandler, $object);
return \call_user_func($this->circularReferenceHandler, $object);
}
throw new CircularReferenceException(sprintf('A circular reference has been detected when serializing the object of class "%s" (configured limit: %d)', get_class($object), $this->circularReferenceLimit));
throw new CircularReferenceException(sprintf('A circular reference has been detected when serializing the object of class "%s" (configured limit: %d)', \get_class($object), $this->circularReferenceLimit));
}
/**
@ -211,7 +211,7 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
}
$groups = false;
if (isset($context[static::GROUPS]) && is_array($context[static::GROUPS])) {
if (isset($context[static::GROUPS]) && \is_array($context[static::GROUPS])) {
$groups = $context[static::GROUPS];
} elseif (!isset($context[static::ALLOW_EXTRA_ATTRIBUTES]) || $context[static::ALLOW_EXTRA_ATTRIBUTES]) {
return false;
@ -222,7 +222,7 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
$name = $attributeMetadata->getName();
if (
(false === $groups || count(array_intersect($attributeMetadata->getGroups(), $groups))) &&
(false === $groups || array_intersect($attributeMetadata->getGroups(), $groups)) &&
$this->isAllowedAttribute($classOrObject, $name, null, $context)
) {
$allowedAttributes[] = $attributesAsString ? $name : $attributeMetadata;
@ -326,11 +326,11 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
$paramName = $constructorParameter->name;
$key = $this->nameConverter ? $this->nameConverter->normalize($paramName) : $paramName;
$allowed = false === $allowedAttributes || in_array($paramName, $allowedAttributes);
$allowed = false === $allowedAttributes || \in_array($paramName, $allowedAttributes);
$ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
if ($constructorParameter->isVariadic()) {
if ($allowed && !$ignored && (isset($data[$key]) || array_key_exists($key, $data))) {
if (!is_array($data[$paramName])) {
if (!\is_array($data[$paramName])) {
throw new RuntimeException(sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name));
}

View File

@ -74,7 +74,7 @@ class GetSetMethodNormalizer extends AbstractObjectNormalizer
*/
private function isGetMethod(\ReflectionMethod $method): bool
{
$methodLength = strlen($method->name);
$methodLength = \strlen($method->name);
return
!$method->isStatic() &&
@ -119,17 +119,17 @@ class GetSetMethodNormalizer extends AbstractObjectNormalizer
$ucfirsted = ucfirst($attribute);
$getter = 'get'.$ucfirsted;
if (is_callable(array($object, $getter))) {
if (\is_callable(array($object, $getter))) {
return $object->$getter();
}
$isser = 'is'.$ucfirsted;
if (is_callable(array($object, $isser))) {
if (\is_callable(array($object, $isser))) {
return $object->$isser();
}
$haser = 'has'.$ucfirsted;
if (is_callable(array($object, $haser))) {
if (\is_callable(array($object, $haser))) {
return $object->$haser();
}
}
@ -140,10 +140,10 @@ class GetSetMethodNormalizer extends AbstractObjectNormalizer
protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = array())
{
$setter = 'set'.ucfirst($attribute);
$key = get_class($object).':'.$setter;
$key = \get_class($object).':'.$setter;
if (!isset(self::$setterAccessibleCache[$key])) {
self::$setterAccessibleCache[$key] = is_callable(array($object, $setter)) && !(new \ReflectionMethod($object, $setter))->isStatic();
self::$setterAccessibleCache[$key] = \is_callable(array($object, $setter)) && !(new \ReflectionMethod($object, $setter))->isStatic();
}
if (self::$setterAccessibleCache[$key]) {

View File

@ -30,7 +30,7 @@ class ObjectNormalizer extends AbstractObjectNormalizer
public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null)
{
if (!class_exists('Symfony\Component\PropertyAccess\PropertyAccess')) {
if (!\class_exists(PropertyAccess::class)) {
throw new RuntimeException('The ObjectNormalizer class requires the "PropertyAccess" component. Install "symfony/property-access" to use it.');
}

View File

@ -137,7 +137,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface
return $data;
}
if (is_array($data) || $data instanceof \Traversable) {
if (\is_array($data) || $data instanceof \Traversable) {
$normalized = array();
foreach ($data as $key => $val) {
$normalized[$key] = $this->normalize($val, $format, $context);
@ -146,12 +146,12 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface
return $normalized;
}
if (is_object($data)) {
if (\is_object($data)) {
if (!$this->normalizers) {
throw new LogicException('You must register at least one normalizer to be able to normalize objects.');
}
throw new NotNormalizableValueException(sprintf('Could not normalize object of type %s, no supporting normalizer found.', get_class($data)));
throw new NotNormalizableValueException(sprintf('Could not normalize object of type %s, no supporting normalizer found.', \get_class($data)));
}
throw new NotNormalizableValueException(sprintf('An unexpected value could not be normalized: %s', var_export($data, true)));

View File

@ -23,48 +23,30 @@ use Symfony\Component\Serializer\DependencyInjection\SerializerPass;
*/
class SerializerPassTest extends TestCase
{
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage You must tag at least one service as "serializer.normalizer" to use the "serializer" service
*/
public function testThrowExceptionWhenNoNormalizers()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds'))->getMock();
$container->expects($this->once())
->method('hasDefinition')
->with('serializer')
->will($this->returnValue(true));
$container->expects($this->once())
->method('findTaggedServiceIds')
->with('serializer.normalizer')
->will($this->returnValue(array()));
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(\RuntimeException::class);
$container = new ContainerBuilder();
$container->register('serializer');
$serializerPass = new SerializerPass();
$serializerPass->process($container);
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage You must tag at least one service as "serializer.encoder" to use the "serializer" service
*/
public function testThrowExceptionWhenNoEncoders()
{
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$container->expects($this->once())
->method('hasDefinition')
->with('serializer')
->will($this->returnValue(true));
$container->expects($this->any())
->method('findTaggedServiceIds')
->will($this->onConsecutiveCalls(
array('n' => array('serializer.normalizer')),
array()
));
$container->expects($this->any())
->method('getDefinition')
->will($this->returnValue($definition));
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(\RuntimeException::class);
$container = new ContainerBuilder();
$container->register('serializer')
->addArgument(array())
->addArgument(array());
$container->register('normalizer')->addTag('serializer.normalizer');
$serializerPass = new SerializerPass();
$serializerPass->process($container);

View File

@ -12,6 +12,7 @@
namespace Symfony\Component\Translation\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Translation\DependencyInjection\TranslationDumperPass;
@ -19,48 +20,29 @@ class TranslationDumperPassTest extends TestCase
{
public function testProcess()
{
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->disableOriginalConstructor()->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->disableOriginalConstructor()->getMock();
$container->expects($this->once())
->method('hasDefinition')
->with('translation.writer')
->will($this->returnValue(true));
$container->expects($this->once())
->method('getDefinition')
->with('translation.writer')
->will($this->returnValue($definition));
$valueTaggedServiceIdsFound = array(
'foo.id' => array(
array('alias' => 'bar.alias'),
),
);
$container->expects($this->once())
->method('findTaggedServiceIds')
->with('translation.dumper', true)
->will($this->returnValue($valueTaggedServiceIdsFound));
$definition->expects($this->once())->method('addMethodCall')->with('addDumper', array('bar.alias', new Reference('foo.id')));
$container = new ContainerBuilder();
$writerDefinition = $container->register('translation.writer');
$container->register('foo.id')
->addTag('translation.dumper', array('alias' => 'bar.alias'));
$translationDumperPass = new TranslationDumperPass();
$translationDumperPass->process($container);
$this->assertEquals(array(array('addDumper', array('bar.alias', new Reference('foo.id')))), $writerDefinition->getMethodCalls());
}
public function testProcessNoDefinitionFound()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->disableOriginalConstructor()->getMock();
$container = new ContainerBuilder();
$container->expects($this->once())
->method('hasDefinition')
->with('translation.writer')
->will($this->returnValue(false));
$container->expects($this->never())->method('getDefinition');
$container->expects($this->never())->method('findTaggedServiceIds');
$definitionsBefore = count($container->getDefinitions());
$aliasesBefore = count($container->getAliases());
$translationDumperPass = new TranslationDumperPass();
$translationDumperPass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
}

View File

@ -12,6 +12,7 @@
namespace Symfony\Component\Translation\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Translation\DependencyInjection\TranslationExtractorPass;
@ -19,49 +20,30 @@ class TranslationExtractorPassTest extends TestCase
{
public function testProcess()
{
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->disableOriginalConstructor()->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->disableOriginalConstructor()->getMock();
$container->expects($this->once())
->method('hasDefinition')
->with('translation.extractor')
->will($this->returnValue(true));
$container->expects($this->once())
->method('getDefinition')
->with('translation.extractor')
->will($this->returnValue($definition));
$valueTaggedServiceIdsFound = array(
'foo.id' => array(
array('alias' => 'bar.alias'),
),
);
$container->expects($this->once())
->method('findTaggedServiceIds')
->with('translation.extractor', true)
->will($this->returnValue($valueTaggedServiceIdsFound));
$definition->expects($this->once())->method('addMethodCall')->with('addExtractor', array('bar.alias', new Reference('foo.id')));
$container = new ContainerBuilder();
$extractorDefinition = $container->register('translation.extractor');
$container->register('foo.id')
->addTag('translation.extractor', array('alias' => 'bar.alias'));
$translationDumperPass = new TranslationExtractorPass();
$translationDumperPass->process($container);
$this->assertEquals(array(array('addExtractor', array('bar.alias', new Reference('foo.id')))), $extractorDefinition->getMethodCalls());
}
public function testProcessNoDefinitionFound()
{
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->disableOriginalConstructor()->getMock();
$container = new ContainerBuilder();
$container->expects($this->once())
->method('hasDefinition')
->with('translation.extractor')
->will($this->returnValue(false));
$container->expects($this->never())->method('getDefinition');
$container->expects($this->never())->method('findTaggedServiceIds');
$definitionsBefore = count($container->getDefinitions());
$aliasesBefore = count($container->getAliases());
$translationDumperPass = new TranslationExtractorPass();
$translationDumperPass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
/**
@ -71,25 +53,10 @@ class TranslationExtractorPassTest extends TestCase
public function testProcessMissingAlias()
{
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->disableOriginalConstructor()->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->disableOriginalConstructor()->getMock();
$container->expects($this->once())
->method('hasDefinition')
->with('translation.extractor')
->will($this->returnValue(true));
$container->expects($this->once())
->method('getDefinition')
->with('translation.extractor')
->will($this->returnValue($definition));
$valueTaggedServiceIdsFound = array(
'foo.id' => array(),
);
$container->expects($this->once())
->method('findTaggedServiceIds')
->with('translation.extractor', true)
->will($this->returnValue($valueTaggedServiceIdsFound));
$container = new ContainerBuilder();
$container->register('translation.extractor');
$container->register('foo.id')
->addTag('translation.extractor', array());
$definition->expects($this->never())->method('addMethodCall');

View File

@ -13,7 +13,6 @@ namespace Symfony\Component\Validator\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Blank as BlankConstraint;
use Symfony\Component\Validator\ConstraintValidator;
@ -23,16 +22,8 @@ class ContainerConstraintValidatorFactoryTest extends TestCase
{
public function testGetInstanceCreatesValidator()
{
$class = get_class($this->getMockForAbstractClass(ConstraintValidator::class));
$constraint = $this->getMockBuilder(Constraint::class)->getMock();
$constraint
->expects($this->once())
->method('validatedBy')
->will($this->returnValue($class));
$factory = new ContainerConstraintValidatorFactory(new Container());
$this->assertInstanceOf($class, $factory->getInstance($constraint));
$this->assertInstanceOf(DummyConstraintValidator::class, $factory->getInstance(new DummyConstraint()));
}
public function testGetInstanceReturnsExistingValidator()
@ -45,30 +36,13 @@ class ContainerConstraintValidatorFactoryTest extends TestCase
public function testGetInstanceReturnsService()
{
$service = 'validator_constraint_service';
$validator = $this->getMockForAbstractClass(ConstraintValidator::class);
// mock ContainerBuilder b/c it implements TaggedContainerInterface
$container = $this->getMockBuilder(ContainerBuilder::class)->setMethods(array('get', 'has'))->getMock();
$container
->expects($this->once())
->method('get')
->with($service)
->willReturn($validator);
$container
->expects($this->once())
->method('has')
->with($service)
->willReturn(true);
$constraint = $this->getMockBuilder(Constraint::class)->getMock();
$constraint
->expects($this->once())
->method('validatedBy')
->will($this->returnValue($service));
$validator = new DummyConstraintValidator();
$container = new Container();
$container->set(DummyConstraintValidator::class, $validator);
$factory = new ContainerConstraintValidatorFactory($container);
$this->assertSame($validator, $factory->getInstance($constraint));
$this->assertSame($validator, $factory->getInstance(new DummyConstraint()));
}
/**
@ -86,3 +60,18 @@ class ContainerConstraintValidatorFactoryTest extends TestCase
$factory->getInstance($constraint);
}
}
class DummyConstraint extends Constraint
{
public function validatedBy()
{
return DummyConstraintValidator::class;
}
}
class DummyConstraintValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
}
}

View File

@ -50,7 +50,7 @@ class AddConstraintValidatorsPassTest extends TestCase
public function testAbstractConstraintValidator()
{
$container = new ContainerBuilder();
$validatorFactory = $container->register('validator.validator_factory')
$container->register('validator.validator_factory')
->addArgument(array());
$container->register('my_abstract_constraint_validator')
@ -63,18 +63,16 @@ class AddConstraintValidatorsPassTest extends TestCase
public function testThatCompilerPassIsIgnoredIfThereIsNoConstraintValidatorFactoryDefinition()
{
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$container = new ContainerBuilder();
$container->expects($this->never())->method('findTaggedServiceIds');
$container->expects($this->never())->method('getDefinition');
$container->expects($this->atLeastOnce())
->method('hasDefinition')
->with('validator.validator_factory')
->will($this->returnValue(false));
$definition->expects($this->never())->method('replaceArgument');
$definitionsBefore = count($container->getDefinitions());
$aliasesBefore = count($container->getAliases());
$addConstraintValidatorsPass = new AddConstraintValidatorsPass();
$addConstraintValidatorsPass->process($container);
// the container is untouched (i.e. no new definitions or aliases)
$this->assertCount($definitionsBefore, $container->getDefinitions());
$this->assertCount($aliasesBefore, $container->getAliases());
}
}

View File

@ -4,7 +4,8 @@ namespace Symfony\Component\Workflow\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Workflow\Definition;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Workflow\Definition as WorkflowDefinition;
use Symfony\Component\Workflow\DependencyInjection\ValidateWorkflowsPass;
use Symfony\Component\Workflow\Transition;
@ -12,19 +13,20 @@ class ValidateWorkflowsPassTest extends TestCase
{
public function testProcess()
{
$container = $this->getMockBuilder(ContainerBuilder::class)->getMock();
$container
->expects($this->once())
->method('findTaggedServiceIds')
->with('workflow.definition')
->willReturn(array('definition1' => array('workflow.definition' => array('name' => 'wf1', 'type' => 'state_machine', 'marking_store' => 'foo'))));
$container
->expects($this->once())
->method('get')
->with('definition1')
->willReturn(new Definition(array('a', 'b', 'c'), array(new Transition('t1', 'a', 'b'), new Transition('t2', 'a', 'c'))));
$container = new ContainerBuilder();
$container->register('definition1', WorkflowDefinition::class)
->addArgument(array('a', 'b', 'c'))
->addArgument(array(
new Definition(Transition::class, array('t1', 'a', 'b')),
new Definition(Transition::class, array('t2', 'a', 'c')),
))
->addTag('workflow.definition', array('name' => 'wf1', 'type' => 'state_machine', 'marking_store' => 'foo'));
(new ValidateWorkflowsPass())->process($container);
$workflowDefinition = $container->get('definition1');
$this->assertSame(array('a' => 'a', 'b' => 'b', 'c' => 'c'), $workflowDefinition->getPlaces());
$this->assertEquals(array(new Transition('t1', 'a', 'b'), new Transition('t2', 'a', 'c')), $workflowDefinition->getTransitions());
}
}