bug #15161 avoid duplicated path with addPrefix (remicollet)

This PR was submitted for the 2.7 branch but it was merged into the 2.3 branch instead (closes #15161).

Discussion
----------

avoid duplicated path with addPrefix

 Q             | A
| ------------- | ---
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | [n/a
| License       | MIT
| Doc PR        | n/a

Having UniversalClassLoader deprecated raise various issues... and ClassLoader doesn't provide the same features... :(

This one avoid duplication of paths for a given prefix, so can improve perf is such case.

Notice: I open this PR against 2.7, first version where UniversalClassLoader is deprecated, but feel free to apply only if 2.8 or 3.0, as you prefer.

Context on how this class is used in various fedora packages, see
http://blog.remirepo.net/post/2015/06/30/PHP-SIG-autoloader

Commits
-------

af420c1 avoid duplicated path with addPrefix
This commit is contained in:
Fabien Potencier 2015-10-06 17:11:44 +02:00
commit 2a0f6fbea3
2 changed files with 32 additions and 6 deletions

View File

@ -91,12 +91,16 @@ class ClassLoader
return;
}
if (isset($this->prefixes[$prefix])) {
$this->prefixes[$prefix] = array_merge(
$this->prefixes[$prefix],
(array) $paths
);
if (is_array($paths)) {
$this->prefixes[$prefix] = array_unique(array_merge(
$this->prefixes[$prefix],
$paths
));
} else if (!in_array($paths, $this->prefixes[$prefix])) {
$this->prefixes[$prefix][] = $paths;
}
} else {
$this->prefixes[$prefix] = (array) $paths;
$this->prefixes[$prefix] = array_unique((array) $paths);
}
}

View File

@ -76,14 +76,36 @@ class ClassLoaderTest extends \PHPUnit_Framework_TestCase
);
}
public function testAddPrefix()
public function testAddPrefixSingle()
{
$loader = new ClassLoader();
$loader->addPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
$loader->addPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
$prefixes = $loader->getPrefixes();
$this->assertArrayHasKey('Foo', $prefixes);
$this->assertCount(1, $prefixes['Foo']);
}
public function testAddPrefixesSingle()
{
$loader = new ClassLoader();
$loader->addPrefixes(array('Foo' => array('foo', 'foo')));
$loader->addPrefixes(array('Foo' => array('foo')));
$prefixes = $loader->getPrefixes();
$this->assertArrayHasKey('Foo', $prefixes);
$this->assertCount(1, $prefixes['Foo'], print_r($prefixes, true));
}
public function testAddPrefixMulti()
{
$loader = new ClassLoader();
$loader->addPrefix('Foo', 'foo');
$loader->addPrefix('Foo', 'bar');
$prefixes = $loader->getPrefixes();
$this->assertArrayHasKey('Foo', $prefixes);
$this->assertCount(2, $prefixes['Foo']);
$this->assertContains('foo', $prefixes['Foo']);
$this->assertContains('bar', $prefixes['Foo']);
}
public function testUseIncludePath()