Skip to content

[DI] Fixing missing "exclude" functionality from PSR4 loader #22680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions src/Symfony/Component/DependencyInjection/Loader/FileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ public function __construct(ContainerBuilder $container, FileLocatorInterface $l
* @param Definition $prototype A definition to use as template
* @param string $namespace The namespace prefix of classes in the scanned directory
* @param string $resource The directory to look for classes, glob-patterns allowed
* @param string $exclude A globed path of files to exclude
*/
public function registerClasses(Definition $prototype, $namespace, $resource)
public function registerClasses(Definition $prototype, $namespace, $resource, $exclude = null)
{
if ('\\' !== substr($namespace, -1)) {
throw new InvalidArgumentException(sprintf('Namespace prefix must end with a "\\": %s.', $namespace));
Expand All @@ -57,7 +58,7 @@ public function registerClasses(Definition $prototype, $namespace, $resource)
throw new InvalidArgumentException(sprintf('Namespace is not a valid PSR-4 prefix: %s.', $namespace));
}

$classes = $this->findClasses($namespace, $resource);
$classes = $this->findClasses($namespace, $resource, $exclude);
// prepare for deep cloning
$prototype = serialize($prototype);

Expand All @@ -84,16 +85,39 @@ protected function setDefinition($id, Definition $definition)
}
}

private function findClasses($namespace, $pattern)
private function findClasses($namespace, $pattern, $excludePattern)
{
$parameterBag = $this->container->getParameterBag();

$excludePaths = array();
$excludePrefix = null;
if ($excludePattern) {
$excludePattern = $parameterBag->unescapeValue($parameterBag->resolveValue($excludePattern));
foreach ($this->glob($excludePattern, true, $resource) as $path => $info) {
if (null === $excludePrefix) {
$excludePrefix = $resource->getPrefix();
}

// normalize Windows slashes
$excludePaths[str_replace('\\', '/', $path)] = true;
}
}

$pattern = $parameterBag->unescapeValue($parameterBag->resolveValue($pattern));
$classes = array();
$extRegexp = defined('HHVM_VERSION') ? '/\\.(?:php|hh)$/' : '/\\.php$/';
$prefixLen = null;
foreach ($this->glob($pattern, true, $resource) as $path => $info) {
if (null === $prefixLen) {
$prefixLen = strlen($resource->getPrefix());

if ($excludePrefix && strpos($excludePrefix, $resource->getPrefix()) !== 0) {
throw new InvalidArgumentException(sprintf('Invalid "exclude" pattern when importing classes for "%s": make sure your "exclude" pattern (%s) is a subset of the "resource" pattern (%s)', $namespace, $excludePattern, $pattern));
}
}

if (isset($excludePaths[str_replace('\\', '/', $path)])) {
continue;
}

if (!preg_match($extRegexp, $path, $m) || !$info->isReadable()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ private function parseDefinitions(\DOMDocument $xml, $file, $defaults)
foreach ($services as $service) {
if (null !== $definition = $this->parseDefinition($service, $file, $defaults)) {
if ('prototype' === $service->tagName) {
$this->registerClasses($definition, (string) $service->getAttribute('namespace'), (string) $service->getAttribute('resource'));
$this->registerClasses($definition, (string) $service->getAttribute('namespace'), (string) $service->getAttribute('resource'), (string) $service->getAttribute('exclude'));
} else {
$this->setDefinition((string) $service->getAttribute('id'), $definition);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ class YamlFileLoader extends FileLoader

private static $prototypeKeywords = array(
'resource' => 'resource',
'exclude' => 'exclude',
'parent' => 'parent',
'shared' => 'shared',
'lazy' => 'lazy',
Expand Down Expand Up @@ -528,7 +529,8 @@ private function parseDefinition($id, $service, $file, array $defaults)
if (!is_string($service['resource'])) {
throw new InvalidArgumentException(sprintf('A "resource" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file));
}
$this->registerClasses($definition, $id, $service['resource']);
$exclude = isset($service['exclude']) ? $service['exclude'] : null;
$this->registerClasses($definition, $id, $service['resource'], $exclude);
} else {
$this->setDefinition($id, $definition);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@
</xsd:choice>
<xsd:attribute name="namespace" type="xsd:string" use="required" />
<xsd:attribute name="resource" type="xsd:string" use="required" />
<xsd:attribute name="exclude" type="xsd:string" />
<xsd:attribute name="shared" type="boolean" />
<xsd:attribute name="public" type="boolean" />
<xsd:attribute name="lazy" type="boolean" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDir\AnotherSub;

class DeeperBaz
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDir;

class Baz
{
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<prototype namespace="Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\" resource="../Prototype/*" />
<prototype namespace="Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\" resource="../Prototype/*" exclude="../Prototype/{OtherDir}" />
</services>
</container>
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
services:
Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\:
resource: ../Prototype
exclude: '../Prototype/{OtherDir}'
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Loader\FileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDir\AnotherSub\DeeperBaz;
use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDir\Baz;
use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar;

class FileLoaderTest extends TestCase
Expand Down Expand Up @@ -90,6 +93,26 @@ public function testRegisterClasses()
);
}

public function testRegisterClassesWithExclude()
{
$container = new ContainerBuilder();
$container->setParameter('other_dir', 'OtherDir');
$loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures'));

$loader->registerClasses(
new Definition(),
'Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\\',
'Prototype/*',
// load everything, except OtherDir/AnotherSub & Foo.php
'Prototype/{%other_dir%/AnotherSub,Foo.php}'
);

$this->assertTrue($container->has(Bar::class));
$this->assertTrue($container->has(Baz::class));
$this->assertFalse($container->has(Foo::class));
$this->assertFalse($container->has(DeeperBaz::class));
}

/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedExceptionMessageRegExp /Expected to find class "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\Prototype\\Bar" in file ".+" while importing services from resource "Prototype\/Sub\/\*", but it was not found\! Check the namespace prefix used with the resource/
Expand All @@ -102,6 +125,35 @@ public function testRegisterClassesWithBadPrefix()
// the Sub is missing from namespace prefix
$loader->registerClasses(new Definition(), 'Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\\', 'Prototype/Sub/*');
}

/**
* @dataProvider getIncompatibleExcludeTests
*/
public function testRegisterClassesWithIncompatibleExclude($resourcePattern, $excludePattern)
{
$container = new ContainerBuilder();
$loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures'));

try {
$loader->registerClasses(
new Definition(),
'Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\\',
$resourcePattern,
$excludePattern
);
} catch (InvalidArgumentException $e) {
$this->assertEquals(
sprintf('Invalid "exclude" pattern when importing classes for "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\": make sure your "exclude" pattern (%s) is a subset of the "resource" pattern (%s)', $excludePattern, $resourcePattern),
$e->getMessage()
);
}
}

public function getIncompatibleExcludeTests()
{
yield array('Prototype/*', 'yaml/*', false);
yield array('Prototype/OtherDir/*', 'Prototype/*', false);
}
}

class TestFileLoader extends FileLoader
Expand Down