private function addPackage(PackageInterface $package) { $class_map = ClassMapGenerator::createMap($this->resolver->getSourcePath($package)); $entity_content = new PackageContent($class_map, PackageContent::ENTITY); $repo_content = new PackageContent($class_map, PackageContent::REPOSITORY); $this->tree_nodes[$package->getName()] = new EntityPackage($package, $entity_content, $repo_content); }
/** * Returns class loading information for a single package * * @param PackageInterface $package The package to generate the class loading info for * @param bool $useRelativePaths If set to TRUE, make the path relative to the current TYPO3 instance (PATH_site) * @return array */ public static function buildClassLoadingInformationForPackage(PackageInterface $package, $useRelativePaths = FALSE) { $classMap = array(); $psr4 = array(); $packagePath = $package->getPackagePath(); try { $manifest = self::getPackageManager()->getComposerManifest($package->getPackagePath()); if (!empty($manifest->autoload->{'psr-4'})) { $psr4manifest = json_decode(json_encode($manifest->autoload->{'psr-4'}), TRUE); if (is_array($psr4manifest)) { foreach ($psr4manifest as $namespacePrefix => $path) { $namespacePath = $packagePath . $path; if ($useRelativePaths) { $psr4[$namespacePrefix] = self::makePathRelative($namespacePath, realpath($namespacePath)); } else { $psr4[$namespacePrefix] = $namespacePath; } } } } } catch (MissingPackageManifestException $e) { // Ignore missing composer manifest } foreach (ClassMapGenerator::createMap($packagePath) as $class => $path) { if ($useRelativePaths) { $classMap[$class] = self::makePathRelative($packagePath, $path); } else { $classMap[$class] = $path; } } return array('classMap' => $classMap, 'psr-4' => $psr4); }
public function testCreateMapFinderSupport() { if (!class_exists('Symfony\\Component\\Finder\\Finder')) { $this->markTestSkipped('Finder component is not available'); } $finder = new \Symfony\Component\Finder\Finder(); $finder->files()->in(__DIR__ . '/Fixtures/beta/NamespaceCollision'); $this->assertEqualsNormalized(array('NamespaceCollision\\A\\B\\Bar' => realpath(__DIR__) . '/Fixtures/beta/NamespaceCollision/A/B/Bar.php', 'NamespaceCollision\\A\\B\\Foo' => realpath(__DIR__) . '/Fixtures/beta/NamespaceCollision/A/B/Foo.php'), ClassMapGenerator::createMap($finder)); }
public function onPostAutoloadDump(Event $event) { $vendorDir = dirname(dirname(dirname(__DIR__))); $composerDir = $vendorDir . '/composer'; $generator = new AutoloadGenerator(); $classmap = (require $composerDir . '/autoload_classmap.php'); $files = (require $composerDir . '/autoload_files.php'); foreach ($files as $file) { $classmap = array_merge($classmap, ClassMapGenerator::createMap($file, NULL, $this->m_io)); } foreach ($classmap as $class => $path) { $generator->register($class, $path); } $psr4 = (require $composerDir . '/autoload_psr4.php'); foreach ($psr4 as $namespace => $paths) { foreach ($paths as $path) { $generator->register($namespace, $path); } } file_put_contents(dirname(__DIR__) . '/autoload.php', (string) $generator); return true; }
/** * 初期化 */ public static function initialize($args = array()) { $args = wp_parse_args($args, array('directories' => array('classes/PostType', 'classes/ShortCode', 'classes/Taxonomy', 'classes/Widgets', 'classes/MenuPage'))); $class_maps = array(); $base_dir = get_template_directory(); foreach ($args['directories'] as $dir) { if (is_dir($dir_path = "{$base_dir}/{$dir}")) { $class_maps[] = ClassMapGenerator::createMap($dir_path); } } if (is_child_theme()) { $base_dir = get_stylesheet_directory(); foreach ($args['directories'] as $dir) { if (is_dir($dir_path = "{$base_dir}/{$dir}")) { $class_maps[] = ClassMapGenerator::createMap($dir_path); } } } $class_map = call_user_func_array('array_merge', $class_maps); foreach ($class_map as $class => $path) { require_once $path; if (class_exists($class)) { $base = null; foreach (self::$based_classes as $based_class) { if (self::parentOf($class, $based_class, self::$name_space)) { $base = $based_class; break; } } if ($base) { self::set_object($based_class, $class, $class); } } } self::add_hooks(); }
public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '') { $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'; $classMapAuthoritative = $config->get('classmap-authoritative'); $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) { $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; foreach (ClassMapGenerator::createMap($dir, $whitelist, $this->io, $namespaceFilter) as $class => $path) { $pathCode = $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n"; if (!isset($classMap[$class])) { $classMap[$class] = $pathCode; } elseif ($this->io && $classMap[$class] !== $pathCode && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($classMap[$class] . ' ' . $path, '\\', '/'))) { $this->io->writeError('<warning>Warning: Ambiguous class resolution, "' . $class . '"' . ' was found in both "' . str_replace(array('$vendorDir . \'', "',\n"), array($vendorPath, ''), $classMap[$class]) . '" and "' . $path . '", the first will be used.</warning>'); } } } } } } foreach ($autoloads['classmap'] as $dir) { foreach (ClassMapGenerator::createMap($dir, null, $this->io) as $class => $path) { $pathCode = $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n"; if (!isset($classMap[$class])) { $classMap[$class] = $pathCode; } elseif ($this->io && $classMap[$class] !== $pathCode && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($classMap[$class] . ' ' . $path, '\\', '/'))) { $this->io->writeError('<warning>Warning: Ambiguous class resolution, "' . $class . '"' . ' was found in both "' . str_replace(array('$vendorDir . \'', "',\n"), array($vendorPath, ''), $classMap[$class]) . '" and "' . $path . '", the first will be used.</warning>'); } } } 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); 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, $classMapAuthoritative)); $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)); }
/** * @expectedException \RuntimeException * @expectedExceptionMessage Could not scan for classes inside */ public function testCreateMapThrowsWhenDirectoryDoesNotExist() { ClassMapGenerator::createMap(__DIR__ . '/no-file.no-foler'); }
<?php /* @var $loader \Composer\Autoload\ClassLoader */ $loader = (require __DIR__ . '/../vendor/autoload.php'); $classMap1 = \Composer\Autoload\ClassMapGenerator::createMap(__DIR__); $loader->addClassMap($classMap1); error_reporting(E_ALL); $configApiFilePath = dirname(__DIR__) . '/SEOstats/Config/ApiKeys.php'; $configApi = file_get_contents($configApiFilePath); $configApi = preg_replace("#(\\s+const MOZSCAPE_ACCESS_ID\\s+=) \\'\\';#", "\$1 'MOZSCAPE_ACCESS_ID';", $configApi); $configApi = preg_replace("#(\\s+const MOZSCAPE_SECRET_KEY\\s+=) \\'\\';#", "\$1 'MOZSCAPE_SECRET_KEY';", $configApi); $configApi = preg_replace("#(\\s+const GOOGLE_SIMPLE_API_ACCESS_KEY\\s+=) \\'\\';#", "\$1 'GOOGLE_SIMPLE_API_ACCESS_KEY';", $configApi); file_put_contents($configApiFilePath, $configApi);
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'); }
/** * Run script * */ public function run() { $mapDirs = array(BP . '/app/code/local', BP . '/app/code/community', BP . '/app/code/core', BP . '/lib'); ClassMapGenerator::dump($mapDirs, BP . '/includes/optimized_map.php'); }
public static function postAutoloadDump(Event $event) { $root = static::getContaoRoot($event->getComposer()->getPackage()); $localconfig = $root . '/system/config/localconfig.php'; $lines = file($localconfig); $remove = false; foreach ($lines as $index => $line) { $tline = trim($line); if ($tline == '### COMPOSER CLASSES START ###') { $remove = true; unset($lines[$index]); } else { if ($tline == '### COMPOSER CLASSES STOP ###') { $remove = true; unset($lines[$index]); } else { if ($remove || $tline == '?>') { unset($lines[$index]); } } } } $file = implode('', $lines); $file = rtrim($file); if (version_compare(VERSION, '3', '<')) { $classmapGenerator = new ClassMapGenerator(); $classmapClasses = array(); $installationManager = $event->getComposer()->getInstallationManager(); $localRepository = $event->getComposer()->getRepositoryManager()->getLocalRepository(); /** @var PackageInterface $package */ foreach ($localRepository->getPackages() as $package) { if ($package->getType() == self::MODULE_TYPE || $package->getType() == self::LEGACY_MODULE_TYPE) { $installPath = $installationManager->getInstallPath($package); $autoload = $package->getAutoload(); if (array_key_exists('psr-0', $autoload)) { foreach ($autoload['psr-0'] as $source) { if (file_exists($installPath . DIRECTORY_SEPARATOR . $source)) { $classmapClasses = array_merge($classmapClasses, $classmapGenerator->createMap($installPath . DIRECTORY_SEPARATOR . $source)); } } } if (array_key_exists('classmap', $autoload)) { foreach ($autoload['classmap'] as $source) { if ($installPath . DIRECTORY_SEPARATOR . $source) { $classmapClasses = array_merge($classmapClasses, $classmapGenerator->createMap($installPath . DIRECTORY_SEPARATOR . $source)); } } } } } $classmapClasses = array_keys($classmapClasses); $classmapClasses = array_map(function ($className) { return var_export($className, true); }, $classmapClasses); $classmapClasses = implode(",\n\t\t", $classmapClasses); $file .= <<<EOF ### COMPOSER CLASSES START ### if (version_compare(VERSION, '3', '<') && class_exists('FileCache')) { \t\$classes = array( \t\t{$classmapClasses} \t); \t\$cache = FileCache::getInstance('classes'); \tforeach (\$classes as \$class) { \t\tif (!\$cache->\$class) { \t\t\t\$cache->\$class = true; \t\t} \t} } ### COMPOSER CLASSES STOP ### EOF; } else { $file .= "\n"; } file_put_contents($root . '/system/config/localconfig.php', $file); }
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'); }
/** * Creates a class map for a given (absolute) path * * @param string $classesPath * @param bool $useRelativePaths * @param bool $ignorePotentialTestClasses * @param string $namespace * @return array */ protected function createClassMap($classesPath, $useRelativePaths = false, $ignorePotentialTestClasses = false, $namespace = null) { $classMap = array(); foreach (ClassMapGenerator::createMap($classesPath, null, null, $namespace) as $class => $path) { if ($ignorePotentialTestClasses) { if ($this->isIgnoredPath($classesPath, $path)) { continue; } if ($this->isIgnoredClassName($class)) { continue; } } if ($useRelativePaths) { $classMap[$class] = $this->makePathRelative($classesPath, $path); } else { $classMap[$class] = $path; } } return $classMap; }
protected function deployLibraries() { $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getPackages(); $autoloadDirectories = array(); $libraryPath = $this->config->getLibraryPath(); if ($libraryPath === null) { if ($this->io->isDebug()) { $this->io->write('jump over deployLibraries as no Magento libraryPath is set'); } return; } $vendorDir = rtrim($this->composer->getConfig()->get('vendor-dir'), '/'); $filesystem = $this->filesystem; $filesystem->removeDirectory($libraryPath); $filesystem->ensureDirectoryExists($libraryPath); foreach ($packages as $package) { /** @var PackageInterface $package */ $packageConfig = $this->config->getLibraryConfigByPackagename($package->getName()); if ($packageConfig === null) { continue; } if (!isset($packageConfig['autoload'])) { $packageConfig['autoload'] = array('/'); } foreach ($packageConfig['autoload'] as $path) { $autoloadDirectories[] = $libraryPath . '/' . $package->getName() . "/" . $path; } if ($this->io->isDebug()) { $this->io->write('Magento deployLibraries executed for ' . $package->getName()); } $libraryTargetPath = $libraryPath . '/' . $package->getName(); $filesystem->removeDirectory($libraryTargetPath); $filesystem->ensureDirectoryExists($libraryTargetPath); $this->copyRecursive($vendorDir . '/' . $package->getPrettyName(), $libraryTargetPath); } $autoloadGenerator = new AutoloadGenerator(new EventDispatcher($this->composer, $this->io)); $classmap = ClassMapGenerator::createMap($libraryPath); $executable = $this->composer->getConfig()->get('bin-dir') . '/phpab'; if (!file_exists($executable)) { $executable = $this->composer->getConfig()->get('vendor-dir') . '/theseer/autoload/composer/bin/phpab'; } if (file_exists($executable)) { if ($this->io->isDebug()) { $this->io->write('Magento deployLibraries executes autoload generator'); } $process = new Process($executable . " -o {$libraryPath}/autoload.php " . implode(' ', $autoloadDirectories)); $process->run(); } else { if ($this->io->isDebug()) { $this->io->write('Magento deployLibraries autoload generator not availabel, you should require "theseer/autoload"'); var_dump($executable, getcwd()); } } }
public function getClassmap() : \Traversable { foreach (ClassMapGenerator::createMap($this->directory) as $class => $path) { (yield $class => $this->normalize($path)); } }
private function generateClassMap($dir, $blacklist = null, $namespaceFilter = null, $showAmbiguousWarning = true) { return ClassMapGenerator::createMap($dir, $blacklist, $showAmbiguousWarning ? $this->io : null, $namespaceFilter); }
/** * Creates a class map for a given (absolute) path * * @param string $classesPath * @param bool $useRelativePaths * @param bool $ignorePotentialTestClasses * @param string $namespace * @return array */ protected function createClassMap($classesPath, $useRelativePaths = false, $ignorePotentialTestClasses = false, $namespace = null) { $classMap = array(); $blacklistExpression = null; if ($ignorePotentialTestClasses) { $blacklistPathPrefix = realpath($classesPath); $blacklistPathPrefix = strtr($blacklistPathPrefix, '\\', '/'); $blacklistExpression = "{({$blacklistPathPrefix}/tests/|{$blacklistPathPrefix}/Tests/|{$blacklistPathPrefix}/Resources/|{$blacklistPathPrefix}/res/|{$blacklistPathPrefix}/class.ext_update.php)}"; } foreach (ClassMapGenerator::createMap($classesPath, $blacklistExpression, null, $namespace) as $class => $path) { if ($useRelativePaths) { $classMap[$class] = $this->makePathRelative($classesPath, $path); } else { $classMap[$class] = $path; } } return $classMap; }
private function generateClassMap($dir, $blacklist = null, $namespaceFilter = null) { return ClassMapGenerator::createMap($dir, $blacklist, $this->io, $namespaceFilter); }
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"); } } }
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); }
public function testDump() { $tempDir = self::getUniqueTmpDirectory(); $resultFile = $tempDir . '/result.txt'; $fileInDirectory = $tempDir . DIRECTORY_SEPARATOR . 'TestClass.php'; file_put_contents($fileInDirectory, "<?php class TestClass {} ?>"); ClassMapGenerator::dump(array($tempDir), $resultFile); $fileInDirectory = str_replace('\\', '\\\\', $fileInDirectory); $this->assertEquals("<?php return array (\n 'TestClass' => '{$fileInDirectory}',\n);", file_get_contents($resultFile)); $fs = new Filesystem(); $fs->removeDirectory($tempDir); }