Skip to content
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
16 changes: 16 additions & 0 deletions doc/04-schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,22 @@ Example:
}
```

#### Exclude files from classmap

If you want to exclude some files or folders from the classmap you can use the 'exclude-from-classmap' property.
This might be useful to exclude UnitTest classes from the classmap in your live environment, for example.

The classmap generator will ignore all files which match your configured regex pattern.
Please note that configured regex pattern will be interpreted as case sensitive.

```json
{
"autoload": {
"exclude-from-classmap": ["/Tests/", "/test/", "/tests/"]
}
}
```

### autoload-dev <span>(root-only)</span>

This section allows to define autoload rules for development purposes.
Expand Down
4 changes: 4 additions & 0 deletions res/composer-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,10 @@
"files": {
"type": "array",
"description": "This is an array of files that are always required on every request."
},
"exclude-from-classmap": {
"type": "array",
"description": "This is an array of patterns to exclude from autoload classmap generation. (e.g. \"exclude-from-classmap\": [\"/test/\", \"/tests/\", \"/Tests/\"]"
}
}
},
Expand Down
43 changes: 35 additions & 8 deletions src/Composer/Autoload/AutoloadGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
*/
class AutoloadGenerator
{
const EXCLUDE_PATTERN = '.*%s';

/**
* @var EventDispatcher
*/
Expand Down Expand Up @@ -171,6 +173,11 @@ public static function autoload(\$class)
EOF;
}

$blacklist = '';
if (!empty($autoloads['exclude-from-classmap'])) {
$blacklist = '{(' . implode('|', $autoloads['exclude-from-classmap']) . ')}';
}

// flatten array
$classMap = array();
if ($scanPsr0Packages) {
Expand All @@ -182,14 +189,9 @@ public static function autoload(\$class)
if (!is_dir($dir)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I can see the removal of this block still has not been accounted for..

The problem is such, if you use psr-0, right now the dir is usually src/ and the namespace prefix Foo\Bar. So it will build up a classmap for all of src/ but exclude files not matching the whitelist (i.e. anything not in src/Foo/Bar).

Removing the whitelist is ok but then I think the $dir should be modified to have the namespace prefix appended if $psrType === 'psr-0' && strpos($namespace, '_') === false is true, that way we only scan the relevant files.

continue;
}
$whitelist = sprintf(
'{%s/%s.+(?<!(?<!/)Test\.php)$}',
preg_quote($dir),
($psrType === 'psr-0' && strpos($namespace, '_') === false) ? preg_quote(strtr($namespace, '\\', '/')) : ''
);

$namespaceFilter = $namespace === '' ? null : $namespace;
foreach (ClassMapGenerator::createMap($dir, $whitelist, $this->io, $namespaceFilter) as $class => $path) {
foreach (ClassMapGenerator::createMap($dir, $blacklist, $this->io, $namespaceFilter) as $class => $path) {
if (!isset($classMap[$class])) {
$path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
$classMap[$class] = $path.",\n";
Expand All @@ -201,7 +203,7 @@ public static function autoload(\$class)
}

foreach ($autoloads['classmap'] as $dir) {
foreach (ClassMapGenerator::createMap($dir, null, $this->io) as $class => $path) {
foreach (ClassMapGenerator::createMap($dir, $blacklist, $this->io) as $class => $path) {
$path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
$classMap[$class] = $path.",\n";
}
Expand Down Expand Up @@ -312,11 +314,19 @@ public function parseAutoloads(array $packageMap, PackageInterface $mainPackage)
$psr4 = $this->parseAutoloadsType($packageMap, 'psr-4', $mainPackage);
$classmap = $this->parseAutoloadsType($sortedPackageMap, 'classmap', $mainPackage);
$files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage);
$exclude = $this->parseAutoloadsType($sortedPackageMap, 'exclude-from-classmap', $mainPackage);

krsort($psr0);
krsort($psr4);

return array('psr-0' => $psr0, 'psr-4' => $psr4, 'classmap' => $classmap, 'files' => $files);
return
array(
'psr-0' => $psr0,
'psr-4' => $psr4,
'classmap' => $classmap,
'files' => $files,
'exclude-from-classmap' => $exclude
);
}

/**
Expand Down Expand Up @@ -621,6 +631,23 @@ protected function parseAutoloadsType(array $packageMap, $type, PackageInterface
}
}

if ($type === 'exclude-from-classmap') {
// first escape user input
$path = sprintf(self::EXCLUDE_PATTERN, preg_quote($path));

if ($package === $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
// remove target-dir from classmap entries of the root package
$targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
$path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
}
elseif($package !== $mainPackage && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
// add target-dir to exclude entries that don't have it
$path = preg_quote($package->getTargetDir()) . '/' . $path;
}
$autoloads[] = empty($installPath) ? $path : preg_quote($installPath) . '/' . $path;
continue;
}

$relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path;

if ($type === 'files' || $type === 'classmap') {
Expand Down
6 changes: 3 additions & 3 deletions src/Composer/Autoload/ClassMapGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ public static function dump($dirs, $file)
* Iterate over all files in the given directory searching for classes
*
* @param \Iterator|string $path The path to search in or an iterator
* @param string $whitelist Regex that matches against the file path
* @param string $blacklist Regex that matches against the file path that exclude from the classmap.
* @param IOInterface $io IO object
* @param string $namespace Optional namespace prefix to filter by
*
* @return array A class map array
*
* @throws \RuntimeException When the path is neither an existing file nor directory
*/
public static function createMap($path, $whitelist = null, IOInterface $io = null, $namespace = null)
public static function createMap($path, $blacklist = '', IOInterface $io = null, $namespace = null)
{
if (is_string($path)) {
if (is_file($path)) {
Expand All @@ -77,7 +77,7 @@ public static function createMap($path, $whitelist = null, IOInterface $io = nul
continue;
}

if ($whitelist && !preg_match($whitelist, strtr($filePath, '\\', '/'))) {
if ($blacklist && preg_match($blacklist, strtr($filePath, '\\', '/'))) {
continue;
}

Expand Down
44 changes: 44 additions & 0 deletions tests/Composer/Test/Autoload/AutoloadGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1195,6 +1195,50 @@ public function testVendorSubstringPath()
$this->assertEquals($expectedPsr4, file_get_contents($this->vendorDir.'/composer/autoload_psr4.php'));
}

public function testExcludeFromClassmap()
{
$package = new Package('a', '1.0', '1.0');
$package->setAutoload(array(
'psr-0' => array(
'Main' => 'src/',
'Lala' => array('src/', 'lib/'),
),
'psr-4' => array(
'Acme\Fruit\\' => 'src-fruit/',
'Acme\Cake\\' => array('src-cake/', 'lib-cake/'),
),
'classmap' => array('composersrc/'),
'exclude-from-classmap' => array('/tests/', 'Exclude.php'),
));

$this->repository->expects($this->once())
->method('getCanonicalPackages')
->will($this->returnValue(array()));

$this->fs->ensureDirectoryExists($this->workingDir.'/composer');
$this->fs->ensureDirectoryExists($this->workingDir.'/src/Lala');
$this->fs->ensureDirectoryExists($this->workingDir.'/lib');
file_put_contents($this->workingDir.'/src/Lala/ClassMapMain.php', '<?php namespace Lala; class ClassMapMain {}');

$this->fs->ensureDirectoryExists($this->workingDir.'/src-fruit');
$this->fs->ensureDirectoryExists($this->workingDir.'/src-cake');
$this->fs->ensureDirectoryExists($this->workingDir.'/lib-cake');
file_put_contents($this->workingDir.'/src-cake/ClassMapBar.php', '<?php namespace Acme\Cake; class ClassMapBar {}');

$this->fs->ensureDirectoryExists($this->workingDir.'/composersrc');
$this->fs->ensureDirectoryExists($this->workingDir.'/composersrc/tests');
file_put_contents($this->workingDir.'/composersrc/foo.php', '<?php class ClassMapFoo {}');

// this classes should not be found in the classmap
file_put_contents($this->workingDir.'/composersrc/tests/bar.php', '<?php class ClassExcludeMapFoo {}');
file_put_contents($this->workingDir.'/composersrc/ClassToExclude.php', '<?php class ClassClassToExclude {}');

$this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_1');

// Assert that autoload_classmap.php was correctly generated.
$this->assertAutoloadFiles('classmap', $this->vendorDir.'/composer', 'classmap');
}

private function assertAutoloadFiles($name, $dir, $type = 'namespaces')
{
$a = __DIR__.'/Fixtures/autoload_'.$name.'.php';
Expand Down