/**
  * @param \Composer\Composer
  * @param string
  * @param string
  */
 public function dumpFiles(Composer $composer, $paths, $targetDir = 'composer')
 {
     $installationManager = $composer->getInstallationManager();
     $localRepo = $composer->getRepositoryManager()->getLocalRepository();
     $mainPackage = $composer->getPackage();
     $config = $composer->getConfig();
     $filesystem = new Filesystem();
     $basePath = $filesystem->normalizePath(realpath(getcwd()));
     $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
     $targetDir = $vendorPath . '/' . $targetDir;
     $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
     $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
     $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
     $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
     $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages());
     $autoloads = $this->parseAutoloads($packageMap, $mainPackage);
     $paths = $this->parseAutoloadsTypeFiles($paths, $mainPackage);
     $autoloads['files'] = array_merge($paths, $autoloads['files']);
     $includeFilesFilePath = $targetDir . '/autoload_files.php';
     if ($includeFilesFileContents = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
         file_put_contents($includeFilesFilePath, $includeFilesFileContents);
     } elseif (file_exists($includeFilesFilePath)) {
         unlink($includeFilesFilePath);
     }
 }
    public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
    {
        $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode);
        $filesystem = new Filesystem();
        $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
        $basePath = $filesystem->normalizePath(realpath(getcwd()));
        $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
        $useGlobalIncludePath = (bool) $config->get('use-include-path');
        $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
        $targetDir = $vendorPath . '/' . $targetDir;
        $filesystem->ensureDirectoryExists($targetDir);
        $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
        $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
        $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
        $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
        $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
        $namespacesFile = <<<EOF
<?php

// autoload_namespaces.php @generated by Composer

\$vendorDir = {$vendorPathCode52};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        $psr4File = <<<EOF
<?php

// autoload_psr4.php @generated by Composer

\$vendorDir = {$vendorPathCode52};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        // Collect information from all packages.
        $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages());
        $autoloads = $this->parseAutoloads($packageMap, $mainPackage);
        // Process the 'psr-0' base directories.
        foreach ($autoloads['psr-0'] as $namespace => $paths) {
            $exportedPaths = array();
            foreach ($paths as $path) {
                $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
            }
            $exportedPrefix = var_export($namespace, true);
            $namespacesFile .= "    {$exportedPrefix} => ";
            $namespacesFile .= "array(" . implode(', ', $exportedPaths) . "),\n";
        }
        $namespacesFile .= ");\n";
        // Process the 'psr-4' base directories.
        foreach ($autoloads['psr-4'] as $namespace => $paths) {
            $exportedPaths = array();
            foreach ($paths as $path) {
                $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
            }
            $exportedPrefix = var_export($namespace, true);
            $psr4File .= "    {$exportedPrefix} => ";
            $psr4File .= "array(" . implode(', ', $exportedPaths) . "),\n";
        }
        $psr4File .= ");\n";
        $classmapFile = <<<EOF
<?php

// autoload_classmap.php @generated by Composer

\$vendorDir = {$vendorPathCode52};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        // add custom psr-0 autoloading if the root package has a target dir
        $targetDirLoader = null;
        $mainAutoload = $mainPackage->getAutoload();
        if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
            $levels = count(explode('/', $filesystem->normalizePath($mainPackage->getTargetDir())));
            $prefixes = implode(', ', array_map(function ($prefix) {
                return var_export($prefix, true);
            }, array_keys($mainAutoload['psr-0'])));
            $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
            $targetDirLoader = <<<EOF

    public static function autoload(\$class)
    {
        \$dir = {$baseDirFromTargetDirCode} . '/';
        \$prefixes = array({$prefixes});
        foreach (\$prefixes as \$prefix) {
            if (0 !== strpos(\$class, \$prefix)) {
                continue;
            }
            \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), {$levels})).'.php';
            if (!\$path = stream_resolve_include_path(\$path)) {
                return false;
            }
            require \$path;

            return true;
        }
    }

EOF;
        }
        // flatten array
        $classMap = array();
        if ($scanPsr0Packages) {
            // Scan the PSR-0/4 directories for class files, and add them to the class map
            foreach (array('psr-0', 'psr-4') as $psrType) {
                foreach ($autoloads[$psrType] as $namespace => $paths) {
                    foreach ($paths as $dir) {
                        $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath . '/' . $dir);
                        if (!is_dir($dir)) {
                            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) {
                            if (!isset($classMap[$class])) {
                                $path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
                                $classMap[$class] = $path . ",\n";
                            }
                        }
                    }
                }
            }
        }
        foreach ($autoloads['classmap'] as $dir) {
            foreach (ClassMapGenerator::createMap($dir, null, $this->io) as $class => $path) {
                $path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
                $classMap[$class] = $path . ",\n";
            }
        }
        ksort($classMap);
        foreach ($classMap as $class => $code) {
            $classmapFile .= '    ' . var_export($class, true) . ' => ' . $code;
        }
        $classmapFile .= ");\n";
        if (!$suffix) {
            $suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
        }
        file_put_contents($targetDir . '/autoload_namespaces.php', $namespacesFile);
        file_put_contents($targetDir . '/autoload_psr4.php', $psr4File);
        file_put_contents($targetDir . '/autoload_classmap.php', $classmapFile);
        if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
            file_put_contents($targetDir . '/include_paths.php', $includePathFile);
        }
        if ($includeFilesFile = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
            file_put_contents($targetDir . '/autoload_files.php', $includeFilesFile);
        }
        file_put_contents($vendorPath . '/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
        file_put_contents($targetDir . '/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFile, $targetDirLoader, (bool) $includeFilesFile, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader));
        // use stream_copy_to_stream instead of copy
        // to work around https://bugs.php.net/bug.php?id=64634
        $sourceLoader = fopen(__DIR__ . '/ClassLoader.php', 'r');
        $targetLoader = fopen($targetDir . '/ClassLoader.php', 'w+');
        stream_copy_to_stream($sourceLoader, $targetLoader);
        fclose($sourceLoader);
        fclose($targetLoader);
        unset($sourceLoader, $targetLoader);
        $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode);
    }
Beispiel #3
0
 /**
  * @dataProvider providePathCouplesAsCode
  */
 public function testFindShortestPathCode($a, $b, $directory, $expected)
 {
     $fs = new Filesystem();
     $this->assertEquals($expected, $fs->findShortestPathCode($a, $b, $directory));
 }
Beispiel #4
0
    public function dump(Config $config, RepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
    {
        $filesystem = new Filesystem();
        $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
        $vendorPath = strtr(realpath($config->get('vendor-dir')), '\\', '/');
        $targetDir = $vendorPath . '/' . $targetDir;
        $filesystem->ensureDirectoryExists($targetDir);
        $relVendorPath = $filesystem->findShortestPath(getcwd(), $vendorPath, true);
        $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
        $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
        $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, getcwd(), true);
        $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
        $namespacesFile = <<<EOF
<?php

// autoload_namespaces.php generated by Composer

\$vendorDir = {$vendorPathCode};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getPackages());
        $autoloads = $this->parseAutoloads($packageMap);
        foreach ($autoloads['psr-0'] as $namespace => $paths) {
            $exportedPaths = array();
            foreach ($paths as $path) {
                $exportedPaths[] = $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $path);
            }
            $exportedPrefix = var_export($namespace, true);
            $namespacesFile .= "    {$exportedPrefix} => ";
            if (count($exportedPaths) > 1) {
                $namespacesFile .= "array(" . implode(', ', $exportedPaths) . "),\n";
            } else {
                $namespacesFile .= $exportedPaths[0] . ",\n";
            }
        }
        $namespacesFile .= ");\n";
        $classmapFile = <<<EOF
<?php

// autoload_classmap.php generated by Composer

\$vendorDir = {$vendorPathCode};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        // add custom psr-0 autoloading if the root package has a target dir
        $targetDirLoader = null;
        $mainAutoload = $mainPackage->getAutoload();
        if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
            $levels = count(explode('/', trim(strtr($mainPackage->getTargetDir(), '\\', '/'), '/')));
            $prefixes = implode(', ', array_map(function ($prefix) {
                return var_export($prefix, true);
            }, array_keys($mainAutoload['psr-0'])));
            $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, getcwd(), true);
            $targetDirLoader = <<<EOF

    public static function autoload(\$class)
    {
        \$dir = {$baseDirFromTargetDirCode} . '/';
        \$prefixes = array({$prefixes});
        foreach (\$prefixes as \$prefix) {
            if (0 !== strpos(\$class, \$prefix)) {
                continue;
            }
            \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), {$levels})).'.php';
            if (!\$path = stream_resolve_include_path(\$path)) {
                return false;
            }
            require \$path;

            return true;
        }
    }

EOF;
        }
        // flatten array
        $classMap = array();
        $autoloads['classmap'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['classmap']));
        if ($scanPsr0Packages) {
            foreach ($autoloads['psr-0'] as $namespace => $paths) {
                foreach ($paths as $dir) {
                    $dir = $this->getPath($filesystem, $relVendorPath, $vendorPath, $dir);
                    $whitelist = sprintf('{%s/%s.+(?<!(?<!/)Test\\.php)$}', preg_quote(rtrim($dir, '/')), strpos($namespace, '_') === false ? preg_quote(strtr($namespace, '\\', '/')) : '');
                    foreach (ClassMapGenerator::createMap($dir, $whitelist) as $class => $path) {
                        if ('' === $namespace || 0 === strpos($class, $namespace)) {
                            $path = '/' . $filesystem->findShortestPath(getcwd(), $path, true);
                            if (!isset($classMap[$class])) {
                                $classMap[$class] = '$baseDir . ' . var_export($path, true) . ",\n";
                            }
                        }
                    }
                }
            }
        }
        foreach ($autoloads['classmap'] as $dir) {
            foreach (ClassMapGenerator::createMap($dir) as $class => $path) {
                $path = '/' . $filesystem->findShortestPath(getcwd(), $path, true);
                $classMap[$class] = '$baseDir . ' . var_export($path, true) . ",\n";
            }
        }
        foreach ($classMap as $class => $code) {
            $classmapFile .= '    ' . var_export($class, true) . ' => ' . $code;
        }
        $classmapFile .= ");\n";
        $filesCode = "";
        $autoloads['files'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['files']));
        foreach ($autoloads['files'] as $functionFile) {
            $filesCode .= '        require ' . $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $functionFile) . ";\n";
        }
        file_put_contents($targetDir . '/autoload_namespaces.php', $namespacesFile);
        file_put_contents($targetDir . '/autoload_classmap.php', $classmapFile);
        if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $relVendorPath, $vendorPath, $vendorPathCode, $appBaseDirCode)) {
            file_put_contents($targetDir . '/include_paths.php', $includePathFile);
        }
        file_put_contents($vendorPath . '/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
        file_put_contents($targetDir . '/autoload_real' . $suffix . '.php', $this->getAutoloadRealFile(true, true, (bool) $includePathFile, $targetDirLoader, $filesCode, $vendorPathCode, $appBaseDirCode, $suffix));
        copy(__DIR__ . '/ClassLoader.php', $targetDir . '/ClassLoader.php');
    }
    public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
    {
        if ($this->classMapAuthoritative) {
            // Force scanPsr0Packages when classmap is authoritative
            $scanPsr0Packages = true;
        }
        $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, array(), array('optimize' => (bool) $scanPsr0Packages));
        $filesystem = new Filesystem();
        $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
        $basePath = $filesystem->normalizePath(realpath(getcwd()));
        $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
        $useGlobalIncludePath = (bool) $config->get('use-include-path');
        $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
        $targetDir = $vendorPath . '/' . $targetDir;
        $filesystem->ensureDirectoryExists($targetDir);
        $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
        $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
        $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
        $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
        $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
        $namespacesFile = <<<EOF
<?php

// autoload_namespaces.php @generated by Composer

\$vendorDir = {$vendorPathCode52};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        $psr4File = <<<EOF
<?php

// autoload_psr4.php @generated by Composer

\$vendorDir = {$vendorPathCode52};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        // Collect information from all packages.
        $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages());
        $autoloads = $this->parseAutoloads($packageMap, $mainPackage);
        // Process the 'psr-0' base directories.
        foreach ($autoloads['psr-0'] as $namespace => $paths) {
            $exportedPaths = array();
            foreach ($paths as $path) {
                $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
            }
            $exportedPrefix = var_export($namespace, true);
            $namespacesFile .= "    {$exportedPrefix} => ";
            $namespacesFile .= "array(" . implode(', ', $exportedPaths) . "),\n";
        }
        $namespacesFile .= ");\n";
        // Process the 'psr-4' base directories.
        foreach ($autoloads['psr-4'] as $namespace => $paths) {
            $exportedPaths = array();
            foreach ($paths as $path) {
                $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
            }
            $exportedPrefix = var_export($namespace, true);
            $psr4File .= "    {$exportedPrefix} => ";
            $psr4File .= "array(" . implode(', ', $exportedPaths) . "),\n";
        }
        $psr4File .= ");\n";
        $classmapFile = <<<EOF
<?php

// autoload_classmap.php @generated by Composer

\$vendorDir = {$vendorPathCode52};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        // add custom psr-0 autoloading if the root package has a target dir
        $targetDirLoader = null;
        $mainAutoload = $mainPackage->getAutoload();
        if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
            $levels = count(explode('/', $filesystem->normalizePath($mainPackage->getTargetDir())));
            $prefixes = implode(', ', array_map(function ($prefix) {
                return var_export($prefix, true);
            }, array_keys($mainAutoload['psr-0'])));
            $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
            $targetDirLoader = <<<EOF

    public static function autoload(\$class)
    {
        \$dir = {$baseDirFromTargetDirCode} . '/';
        \$prefixes = array({$prefixes});
        foreach (\$prefixes as \$prefix) {
            if (0 !== strpos(\$class, \$prefix)) {
                continue;
            }
            \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), {$levels})).'.php';
            if (!\$path = stream_resolve_include_path(\$path)) {
                return false;
            }
            require \$path;

            return true;
        }
    }

EOF;
        }
        $blacklist = null;
        if (!empty($autoloads['exclude-from-classmap'])) {
            $blacklist = '{(' . implode('|', $autoloads['exclude-from-classmap']) . ')}';
        }
        // flatten array
        $classMap = array();
        if ($scanPsr0Packages) {
            $namespacesToScan = array();
            // Scan the PSR-0/4 directories for class files, and add them to the class map
            foreach (array('psr-0', 'psr-4') as $psrType) {
                foreach ($autoloads[$psrType] as $namespace => $paths) {
                    $namespacesToScan[$namespace][] = array('paths' => $paths, 'type' => $psrType);
                }
            }
            krsort($namespacesToScan);
            foreach ($namespacesToScan as $namespace => $groups) {
                foreach ($groups as $group) {
                    $psrType = $group['type'];
                    foreach ($group['paths'] as $dir) {
                        $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath . '/' . $dir);
                        if (!is_dir($dir)) {
                            continue;
                        }
                        //                        $whitelist = sprintf(
                        //                            '{%s/%s.+$}',
                        //                            preg_quote($dir),
                        //                            ($psrType === 'psr-0' && strpos($namespace, '_') === false) ? preg_quote(strtr($namespace, '\\', '/')) : ''
                        //                        );
                        $namespaceFilter = $namespace === '' ? null : $namespace;
                        $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, $namespaceFilter, $classMap);
                    }
                }
            }
        }
        foreach ($autoloads['classmap'] as $dir) {
            $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, null, $classMap);
        }
        ksort($classMap);
        foreach ($classMap as $class => $code) {
            $classmapFile .= '    ' . var_export($class, true) . ' => ' . $code;
        }
        $classmapFile .= ");\n";
        if (!$suffix) {
            if (!$config->get('autoloader-suffix') && is_readable($vendorPath . '/autoload.php')) {
                $content = file_get_contents($vendorPath . '/autoload.php');
                if (preg_match('{ComposerAutoloaderInit([^:\\s]+)::}', $content, $match)) {
                    $suffix = $match[1];
                }
            }
            if (!$suffix) {
                $suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
            }
        }
        file_put_contents($targetDir . '/autoload_namespaces.php', $namespacesFile);
        file_put_contents($targetDir . '/autoload_psr4.php', $psr4File);
        file_put_contents($targetDir . '/autoload_classmap.php', $classmapFile);
        $includePathFilePath = $targetDir . '/include_paths.php';
        if ($includePathFileContents = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
            file_put_contents($includePathFilePath, $includePathFileContents);
        } elseif (file_exists($includePathFilePath)) {
            unlink($includePathFilePath);
        }
        $includeFilesFilePath = $targetDir . '/autoload_files.php';
        if ($includeFilesFileContents = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
            file_put_contents($includeFilesFilePath, $includeFilesFileContents);
        } elseif (file_exists($includeFilesFilePath)) {
            unlink($includeFilesFilePath);
        }
        file_put_contents($vendorPath . '/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
        file_put_contents($targetDir . '/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFileContents, $targetDirLoader, (bool) $includeFilesFileContents, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader));
        $this->safeCopy(__DIR__ . '/ClassLoader.php', $targetDir . '/ClassLoader.php');
        $this->safeCopy(__DIR__ . '/../../../LICENSE', $targetDir . '/LICENSE');
        $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, array(), array('optimize' => (bool) $scanPsr0Packages));
    }
Beispiel #6
0
    public function dump(RepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir)
    {
        $autoloadFile = <<<'EOF'
<?php

// autoload.php generated by Composer
if (!class_exists('Composer\\Autoload\\ClassLoader', false)) {
    require __DIR__.'/ClassLoader.php';
}

$__composer_autoload_init = function() {
    $loader = new \Composer\Autoload\ClassLoader();

    $map = require __DIR__.'/autoload_namespaces.php';

    foreach ($map as $namespace => $path) {
        $loader->add($namespace, $path);
    }

    $loader->register();

    return $loader;
};

return $__composer_autoload_init();
EOF;
        $filesystem = new Filesystem();
        $vendorPath = strtr(realpath($installationManager->getVendorPath()), '\\', '/');
        $relVendorPath = $filesystem->findShortestPath(getcwd(), $vendorPath);
        $vendorDirCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
        $namespacesFile = <<<EOF
<?php

// autoload_namespace.php generated by Composer

\$vendorDir = {$vendorDirCode};

return array(

EOF;
        $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getPackages());
        $autoloads = $this->parseAutoloads($packageMap);
        $appBaseDir = $filesystem->findShortestPathCode($vendorPath, getcwd(), true);
        $appBaseDir = str_replace('__DIR__', '$vendorDir', $appBaseDir);
        if (isset($autoloads['psr-0'])) {
            foreach ($autoloads['psr-0'] as $namespace => $paths) {
                $exportedPaths = array();
                foreach ($paths as $path) {
                    $path = strtr($path, '\\', '/');
                    $baseDir = '';
                    if (!$filesystem->isAbsolutePath($path)) {
                        // vendor dir == working dir
                        if (preg_match('{^(\\./?)?$}', $relVendorPath)) {
                            $path = '/' . $path;
                            $baseDir = '$vendorDir . ';
                        } elseif (strpos($path, $relVendorPath) === 0) {
                            // path starts with vendor dir
                            $path = substr($path, strlen($relVendorPath));
                            $baseDir = '$vendorDir . ';
                        } else {
                            $path = '/' . $path;
                            $baseDir = $appBaseDir . ' . ';
                        }
                    } elseif (strpos($path, $vendorPath) === 0) {
                        $path = substr($path, strlen($vendorPath));
                        $baseDir = '$vendorDir . ';
                    }
                    $exportedPaths[] = $baseDir . var_export($path, true);
                }
                $exportedPrefix = var_export($namespace, true);
                $namespacesFile .= "    {$exportedPrefix} => ";
                if (count($exportedPaths) > 1) {
                    $namespacesFile .= "array(" . implode(', ', $exportedPaths) . "),\n";
                } else {
                    $namespacesFile .= $exportedPaths[0] . ",\n";
                }
            }
        }
        $namespacesFile .= ");\n";
        file_put_contents($targetDir . '/autoload.php', $autoloadFile);
        file_put_contents($targetDir . '/autoload_namespaces.php', $namespacesFile);
        copy(__DIR__ . '/ClassLoader.php', $targetDir . '/ClassLoader.php');
    }
    protected function getStaticFile($suffix, $targetDir, $vendorPath, $basePath, &$staticPhpVersion)
    {
        $staticPhpVersion = 50600;
        $file = <<<HEADER
<?php

// autoload_static.php @generated by Composer

namespace Composer\\Autoload;

class ComposerStaticInit{$suffix}
{

HEADER;
        $loader = new ClassLoader();
        $map = (require $targetDir . '/autoload_namespaces.php');
        foreach ($map as $namespace => $path) {
            $loader->set($namespace, $path);
        }
        $map = (require $targetDir . '/autoload_psr4.php');
        foreach ($map as $namespace => $path) {
            $loader->setPsr4($namespace, $path);
        }
        $classMap = (require $targetDir . '/autoload_classmap.php');
        if ($classMap) {
            $loader->addClassMap($classMap);
        }
        $filesystem = new Filesystem();
        $vendorPathCode = ' ' . $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true, true) . " . '/";
        $appBaseDirCode = ' ' . $filesystem->findShortestPathCode(realpath($targetDir), $basePath, true, true) . " . '/";
        $absoluteVendorPathCode = ' ' . substr(var_export(rtrim($vendorDir, '\\/') . '/', true), 0, -1);
        $absoluteAppBaseDirCode = ' ' . substr(var_export(rtrim($baseDir, '\\/') . '/', true), 0, -1);
        $initializer = '';
        $prefix = "Composer\\Autoload\\ClassLoader";
        $prefixLen = strlen($prefix);
        if (file_exists($targetDir . '/autoload_files.php')) {
            $maps = array('files' => require $targetDir . '/autoload_files.php');
        } else {
            $maps = array();
        }
        foreach ((array) $loader as $prop => $value) {
            if ($value && 0 === strpos($prop, $prefix)) {
                $maps[substr($prop, $prefixLen)] = $value;
            }
        }
        foreach ($maps as $prop => $value) {
            if (count($value) > 32767) {
                // Static arrays are limited to 32767 values on PHP 5.6
                // See https://bugs.php.net/68057
                $staticPhpVersion = 70000;
            }
            $value = var_export($value, true);
            $value = str_replace($absoluteVendorPathCode, $vendorPathCode, $value);
            $value = str_replace($absoluteAppBaseDirCode, $appBaseDirCode, $value);
            $value = ltrim(preg_replace('/^ */m', '    $0$0', $value));
            $file .= sprintf("    public static \$%s = %s;\n\n", $prop, $value);
            if ('files' !== $prop) {
                $initializer .= "            \$loader->{$prop} = ComposerStaticInit{$suffix}::\${$prop};\n";
            }
        }
        return $file . <<<INITIALIZER
    public static function getInitializer(ClassLoader \$loader)
    {
        return \\Closure::bind(function () use (\$loader) {
{$initializer}
        }, null, ClassLoader::class);
    }
}

INITIALIZER;
    }
 /**
  * @return string
  * @throws \InvalidArgumentException
  */
 public function getContent()
 {
     $includeFileFolder = dirname(dirname(__DIR__)) . '/res/php';
     return $this->filesystem->findShortestPathCode($includeFileFolder, $this->typo3PluginConfig->getBaseDir(), true);
 }
Beispiel #9
0
    public function dump(RepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $bcLinks = false)
    {
        $filesystem = new Filesystem();
        $filesystem->ensureDirectoryExists($installationManager->getVendorPath());
        $filesystem->ensureDirectoryExists($targetDir);
        $vendorPath = strtr(realpath($installationManager->getVendorPath()), '\\', '/');
        $relVendorPath = $filesystem->findShortestPath(getcwd(), $vendorPath, true);
        $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
        $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
        $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, getcwd(), true);
        $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
        $namespacesFile = <<<EOF
<?php

// autoload_namespace.php generated by Composer

\$vendorDir = {$vendorPathCode};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getPackages());
        $autoloads = $this->parseAutoloads($packageMap);
        foreach ($autoloads['psr-0'] as $namespace => $paths) {
            $exportedPaths = array();
            foreach ($paths as $path) {
                $exportedPaths[] = $this->getPathCode($filesystem, $relVendorPath, $vendorPath, $path);
            }
            $exportedPrefix = var_export($namespace, true);
            $namespacesFile .= "    {$exportedPrefix} => ";
            if (count($exportedPaths) > 1) {
                $namespacesFile .= "array(" . implode(', ', $exportedPaths) . "),\n";
            } else {
                $namespacesFile .= $exportedPaths[0] . ",\n";
            }
        }
        $namespacesFile .= ");\n";
        $classmapFile = <<<EOF
<?php

// autoload_classmap.php generated by Composer

\$vendorDir = {$vendorPathCode};
\$baseDir = {$appBaseDirCode};

return array(

EOF;
        // add custom psr-0 autoloading if the root package has a target dir
        $targetDirLoader = null;
        $mainAutoload = $mainPackage->getAutoload();
        if ($mainPackage->getTargetDir() && $mainAutoload['psr-0']) {
            $levels = count(explode('/', trim(strtr($mainPackage->getTargetDir(), '\\', '/'), '/')));
            $prefixes = implode(', ', array_map(function ($prefix) {
                return var_export($prefix, true);
            }, array_keys($mainAutoload['psr-0'])));
            $baseDirFromVendorDirCode = $filesystem->findShortestPathCode($vendorPath, getcwd(), true);
            $targetDirLoader = <<<EOF
    spl_autoload_register(function(\$class) {
        \$dir = {$baseDirFromVendorDirCode} . '/';
        \$prefixes = array({$prefixes});
        foreach (\$prefixes as \$prefix) {
            if (0 !== strpos(\$class, \$prefix)) {
                continue;
            }
            \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), {$levels})).'.php';
            if (!stream_resolve_include_path(\$path)) {
                return false;
            }
            require_once \$path;

            return true;
        }
    });


EOF;
        }
        // flatten array
        $autoloads['classmap'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['classmap']));
        foreach ($autoloads['classmap'] as $dir) {
            foreach (ClassMapGenerator::createMap($dir) as $class => $path) {
                $path = '/' . $filesystem->findShortestPath(getcwd(), $path, true);
                $classmapFile .= '    ' . var_export($class, true) . ' => $baseDir . ' . var_export($path, true) . ",\n";
            }
        }
        $classmapFile .= ");\n";
        file_put_contents($targetDir . '/autoload_namespaces.php', $namespacesFile);
        file_put_contents($targetDir . '/autoload_classmap.php', $classmapFile);
        if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $relVendorPath, $vendorPath, $vendorPathCode, $appBaseDirCode)) {
            file_put_contents($targetDir . '/include_paths.php', $includePathFile);
        }
        file_put_contents($vendorPath . '/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, true, true, (bool) $includePathFile, $targetDirLoader));
        copy(__DIR__ . '/ClassLoader.php', $targetDir . '/ClassLoader.php');
        // TODO BC feature, remove after June 15th
        if ($bcLinks) {
            $filesystem->ensureDirectoryExists($vendorPath . '/.composer');
            $deprecated = "// Deprecated file, use the one in root of vendor dir\n" . "trigger_error(__FILE__.' is deprecated, please use vendor/autoload.php or vendor/composer/autoload_* instead'.PHP_EOL.'See https://groups.google.com/forum/#!msg/composer-dev/fWIs3KocwoA/nU3aLko9LhQJ for details', E_USER_DEPRECATED);\n";
            file_put_contents($vendorPath . '/.composer/autoload_namespaces.php', "<?php\n{$deprecated}\nreturn include dirname(__DIR__).'/composer/autoload_namespaces.php';\n");
            file_put_contents($vendorPath . '/.composer/autoload_classmap.php', "<?php\n{$deprecated}\nreturn include dirname(__DIR__).'/composer/autoload_classmap.php';\n");
            file_put_contents($vendorPath . '/.composer/autoload.php', "<?php\n{$deprecated}\nreturn include dirname(__DIR__).'/autoload.php';\n");
            file_put_contents($vendorPath . '/.composer/ClassLoader.php', "<?php\n{$deprecated}\nreturn include dirname(__DIR__).'/composer/ClassLoader.php';\n");
            if ($includePathFile) {
                file_put_contents($vendorPath . '/.composer/include_paths.php', "<?php\n{$deprecated}\nreturn include dirname(__DIR__).'/composer/include_paths.php';\n");
            }
        }
    }
Beispiel #10
0
    public function dump(RepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir)
    {
        $filesystem = new Filesystem();
        $filesystem->ensureDirectoryExists($installationManager->getVendorPath());
        $filesystem->ensureDirectoryExists($targetDir);
        $vendorPath = strtr(realpath($installationManager->getVendorPath()), '\\', '/');
        $relVendorPath = $filesystem->findShortestPath(getcwd(), $vendorPath, true);
        $vendorDirCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
        $appBaseDir = $filesystem->findShortestPathCode($vendorPath, getcwd(), true);
        $appBaseDir = str_replace('__DIR__', '$vendorDir', $appBaseDir);
        $namespacesFile = <<<EOF
<?php

// autoload_namespace.php generated by Composer

\$vendorDir = {$vendorDirCode};
\$baseDir = {$appBaseDir};

return array(

EOF;
        $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getPackages());
        $autoloads = $this->parseAutoloads($packageMap);
        foreach ($autoloads['psr-0'] as $namespace => $paths) {
            $exportedPaths = array();
            foreach ($paths as $path) {
                $path = strtr($path, '\\', '/');
                $baseDir = '';
                if (!$filesystem->isAbsolutePath($path)) {
                    if (strpos($path, $relVendorPath) === 0) {
                        // path starts with vendor dir
                        $path = substr($path, strlen($relVendorPath));
                        $baseDir = '$vendorDir . ';
                    } else {
                        $path = '/' . $path;
                        $baseDir = '$baseDir . ';
                    }
                } elseif (strpos($path, $vendorPath) === 0) {
                    $path = substr($path, strlen($vendorPath));
                    $baseDir = '$vendorDir . ';
                }
                $exportedPaths[] = $baseDir . var_export($path, true);
            }
            $exportedPrefix = var_export($namespace, true);
            $namespacesFile .= "    {$exportedPrefix} => ";
            if (count($exportedPaths) > 1) {
                $namespacesFile .= "array(" . implode(', ', $exportedPaths) . "),\n";
            } else {
                $namespacesFile .= $exportedPaths[0] . ",\n";
            }
        }
        $namespacesFile .= ");\n";
        $classmapFile = <<<EOF
<?php

// autoload_classmap.php generated by Composer

\$vendorDir = {$vendorDirCode};
\$baseDir = {$appBaseDir};

return array(

EOF;
        // flatten array
        $autoloads['classmap'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['classmap']));
        foreach ($autoloads['classmap'] as $dir) {
            foreach (ClassMapGenerator::createMap($dir) as $class => $path) {
                $path = '/' . $filesystem->findShortestPath(getcwd(), $path, true);
                $classmapFile .= '    ' . var_export($class, true) . ' => $baseDir . ' . var_export($path, true) . ",\n";
            }
        }
        $classmapFile .= ");\n";
        file_put_contents($targetDir . '/autoload_namespaces.php', $namespacesFile);
        file_put_contents($targetDir . '/autoload_classmap.php', $classmapFile);
        if ($includePathFile = $this->getIncludePathsFile($packageMap)) {
            file_put_contents($targetDir . '/include_paths.php', $includePathFile);
        }
        file_put_contents($targetDir . '/autoload.php', $this->getAutoloadFile(true, true, (bool) $includePathFile));
        copy(__DIR__ . '/ClassLoader.php', $targetDir . '/ClassLoader.php');
    }
Beispiel #11
0
    public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
    {
        if ($this->classMapAuthoritative) {
            // Force scanPsr0Packages when classmap is authoritative
            $scanPsr0Packages = true;
        }
        $filesystem = new Filesystem();
        $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
        $cwd = getcwd();
        $basePath = $filesystem->normalizePath($cwd);
        $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
        $targetDir = $vendorPath . '/' . $targetDir;
        $filesystem->ensureDirectoryExists($targetDir);
        $useGlobalIncludePath = (bool) $config->get('use-include-path');
        $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
        $classMapAuthoritative = $config->get('classmap-authoritative');
        $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
        $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
        $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
        $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
        // add 5.2 compat
        $vendorPathCode = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
        $vendorPathToTargetDirCode = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathToTargetDirCode);
        $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages());
        $autoloads = $this->parseAutoloads($packageMap, $mainPackage);
        // add custom psr-0 autoloading if the root package has a target dir
        $targetDirLoader = null;
        $mainAutoload = $mainPackage->getAutoload();
        if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
            $levels = count(explode('/', $filesystem->normalizePath($mainPackage->getTargetDir())));
            $prefixes = implode(', ', array_map(function ($prefix) {
                return var_export($prefix, true);
            }, array_keys($mainAutoload['psr-0'])));
            $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
            $targetDirLoader = <<<EOF

\tpublic static function autoload(\$class) {
\t\t\$dir      = {$baseDirFromTargetDirCode}.'/';
\t\t\$prefixes = array({$prefixes});

\t\tforeach (\$prefixes as \$prefix) {
\t\t\tif (0 !== strpos(\$class, \$prefix)) {
\t\t\t\tcontinue;
\t\t\t}

\t\t\t\$path = explode(DIRECTORY_SEPARATOR, self::getClassPath(\$class));
\t\t\t\$path = \$dir.implode('/', array_slice(\$path, {$levels}));

\t\t\tif (!\$path = self::resolveIncludePath(\$path)) {
\t\t\t\treturn false;
\t\t\t}

\t\t\trequire \$path;
\t\t\treturn true;
\t\t}
\t}

EOF;
        }
        $filesCode = "";
        $autoloads['files'] = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($autoloads['files']));
        foreach ($autoloads['files'] as $functionFile) {
            // don't include file if it is using PHP 5.3+ syntax
            // https://bitbucket.org/xrstf/composer-php52/issue/4
            if ($this->isPHP53($functionFile)) {
                $filesCode .= '//		require ' . $this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile) . "; // disabled because of PHP 5.3 syntax\n";
            } else {
                $filesCode .= '		require ' . $this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile) . ";\n";
            }
        }
        if (!$suffix) {
            $suffix = md5(uniqid('', true));
        }
        $includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode);
        file_put_contents($vendorPath . '/autoload_52.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
        file_put_contents($targetDir . '/autoload_real_52.php', $this->getAutoloadRealFile(true, (bool) $includePathFile, $targetDirLoader, $filesCode, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader));
        // use stream_copy_to_stream instead of copy
        // to work around https://bugs.php.net/bug.php?id=64634
        $sourceLoader = fopen(__DIR__ . '/ClassLoader.php', 'r');
        $targetLoader = fopen($targetDir . '/ClassLoader52.php', 'w+');
        stream_copy_to_stream($sourceLoader, $targetLoader);
        fclose($sourceLoader);
        fclose($targetLoader);
        unset($sourceLoader, $targetLoader);
    }
Beispiel #12
0
 /**
  * Constructs the include file content
  *
  * @param string $includeFile The path to the file that will be included by composer in autoload.php
  * @return array
  * @throws \RuntimeException
  * @throws \InvalidArgumentException
  */
 protected function getIncludeFileContent($includeFile)
 {
     $filesystem = new Filesystem();
     $includeFileTemplate = dirname(__DIR__) . self::INCLUDE_FILE_TEMPLATE;
     $envDir = $this->config->get('env-dir');
     $pathToEnvFileCode = $filesystem->findShortestPathCode(dirname($includeFile), $envDir, true);
     $cacheDir = $this->config->get('cache-dir');
     $allowOverridesCode = $this->config->get('allow-overrides') ? 'true' : 'false';
     if ($cacheDir === null) {
         $pathToCacheDirCode = 'null';
     } else {
         $cache = new Cache($cacheDir, $envDir);
         $cache->cleanCache();
         $pathToCacheDirCode = $filesystem->findShortestPathCode(dirname($includeFile), $cacheDir, true);
     }
     $includeFileContent = file_get_contents($includeFileTemplate);
     $includeFileContent = $this->replaceToken('env-dir', $pathToEnvFileCode, $includeFileContent);
     $includeFileContent = $this->replaceToken('allow-overrides', $allowOverridesCode, $includeFileContent);
     $includeFileContent = $this->replaceToken('cache-dir', $pathToCacheDirCode, $includeFileContent);
     return $includeFileContent;
 }