bug #24732 [DependencyInjection] Prevent service:method factory notation in PHP config (vudaltsov)

This PR was merged into the 3.4 branch.

Discussion
----------

[DependencyInjection] Prevent service:method factory notation in PHP config

| Q             | A
| ------------- | ---
| Branch?       | 3.4
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #24704
| License       | MIT
| Doc PR        |

Started working on fixing #24704.

@nicolas-grekas, am I on the right way? If yes I will look at the tests and try to add this case.

Commits
-------

49fc677 Throw on service:method factory notation in PHP-based DI configuration
This commit is contained in:
Nicolas Grekas 2017-11-17 11:59:25 +02:00
commit 5766e1dc93
3 changed files with 30 additions and 0 deletions

View File

@ -11,6 +11,8 @@
namespace Symfony\Component\DependencyInjection\Loader\Configurator\Traits;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
trait FactoryTrait
{
/**
@ -22,6 +24,12 @@ trait FactoryTrait
*/
final public function factory($factory)
{
if (is_string($factory) && 1 === substr_count($factory, ':')) {
$factoryParts = explode(':', $factory);
throw new InvalidArgumentException(sprintf('Invalid factory "%s": the `service:method` notation is not available when using PHP-based DI configuration. Use "[ref(\'%s\'), \'%s\']" instead.', $factory, $factoryParts[0], $factoryParts[1]));
}
$this->definition->setFactory(static::processValue($factory, true));
return $this;

View File

@ -0,0 +1,9 @@
<?php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
return function (ContainerConfigurator $c) {
$c->services()
->set('service', \stdClass::class)
->factory('factory:method');
};

View File

@ -89,4 +89,17 @@ class PhpFileLoaderTest extends TestCase
$loader->load($fixtures.'/config/services_autoconfigure_with_parent.php');
$container->compile();
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessage Invalid factory "factory:method": the `service:method` notation is not available when using PHP-based DI configuration. Use "[ref('factory'), 'method']" instead.
*/
public function testFactoryShortNotationNotAllowed()
{
$fixtures = realpath(__DIR__.'/../Fixtures');
$container = new ContainerBuilder();
$loader = new PhpFileLoader($container, new FileLocator());
$loader->load($fixtures.'/config/factory_short_notation.php');
$container->compile();
}
}