/** * @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); } }
private function normalize(string $path) : string { if (!$this->filesystem->isAbsolutePath($path)) { $path = $this->basePath . '/' . $path; } return $this->filesystem->normalizePath($path); }
/** * Constructs the include file content * * @return string * @throws \RuntimeException * @throws \InvalidArgumentException */ protected function getIncludeFileContent() { $includeFileTemplate = $this->filesystem->normalizePath(__DIR__ . '/../' . self::RESOURCES_PATH . '/' . self::INCLUDE_FILE_TEMPLATE); $includeFileContent = file_get_contents($includeFileTemplate); foreach ($this->tokens as $token) { $includeFileContent = self::replaceToken($token->getName(), $token->getContent(), $includeFileContent); } return $includeFileContent; }
public function onPostInstallCommand(ScriptEvent $event) { $config = $event->getComposer()->getConfig(); $filesystem = new Filesystem(); $vendor_path = $filesystem->normalizePath(realpath($config->get('vendor-dir'))); $cake_dir = $filesystem->normalizePath($vendor_path . '/cakephp/cakephp'); $root_dir = $filesystem->normalizePath(realpath("")); $app_dir = $filesystem->normalizePath($root_dir . '/app'); if (!is_dir($app_dir)) { $this->copyRecursive($filesystem->normalizePath($cake_dir . '/app'), $app_dir); $index_path = $filesystem->normalizePath($app_dir . '/webroot/index.php'); $index = str_replace('define(\'CAKE_CORE_INCLUDE_PATH\', ROOT);', 'define(\'CAKE_CORE_INCLUDE_PATH\', ROOT . \'vendor\' . DS . \'cakephp\' . DS . \'cakephp\');', file_get_contents($index_path)); file_put_contents($index_path, $index); $loader_of_old_php_path = $filesystem->normalizePath($vendor_path . '/atomita/loader-of-less-than-php5.3-plugin'); if (file_exists($loader_of_old_php_path)) { $loader = <<<EOD // @generated by atomita/cakephp1-setup-plugin include(ROOT . DS . '{$config->get('vendor-dir')}' . DS . 'autoload.php'); // @end generated EOD; $config_path = $filesystem->normalizePath($app_dir . '/config/core.php'); $config = file_get_contents($config_path); if (false === strpos($config, $loader)) { file_put_contents($config_path, $config . PHP_EOL . PHP_EOL . $loader); } } } }
/** * {@inheritdoc} */ public function archive($sources, $target, $format, array $excludes = array()) { $fs = new Filesystem(); $sources = $fs->normalizePath($sources); $zip = new ZipArchive(); $res = $zip->open($target, ZipArchive::CREATE); if ($res === true) { $files = new ArchivableFilesFinder($sources, $excludes); foreach ($files as $file) { /** @var $file \SplFileInfo */ $filepath = strtr($file->getPath() . "/" . $file->getFilename(), '\\', '/'); $localname = str_replace($sources . '/', '', $filepath); if ($file->isDir()) { $zip->addEmptyDir($localname); } else { $zip->addFile($filepath, $localname); } } if ($zip->close()) { return $target; } } $message = sprintf("Could not create archive '%s' from '%s': %s", $target, $sources, $zip->getStatusString()); throw new \RuntimeException($message); }
/** * Clean a package, based on its rules. * * @param BasePackage $package The package to clean * @return bool True if cleaned */ protected function cleanPackage(BasePackage $package) { // Only clean 'dist' packages if ($package->getInstallationSource() !== 'dist') { return false; } $vendorDir = $this->config->get('vendor-dir'); $targetDir = $package->getTargetDir(); $packageName = $package->getPrettyName(); $packageDir = $targetDir ? $packageName . '/' . $targetDir : $packageName; $rules = isset($this->rules[$packageName]) ? $this->rules[$packageName] : null; if (!$rules) { return; } $dir = $this->filesystem->normalizePath(realpath($vendorDir . '/' . $packageDir)); if (!is_dir($dir)) { return false; } foreach ((array) $rules as $part) { // Split patterns for single globs (should be max 260 chars) $patterns = explode(' ', trim($part)); foreach ($patterns as $pattern) { try { foreach (glob($dir . '/' . $pattern) as $file) { $this->filesystem->remove($file); } } catch (\Exception $e) { $this->io->write("Could not parse {$packageDir} ({$pattern}): " . $e->getMessage()); } } } return true; }
/** * Clean a package, based on its rules. * * @param BasePackage $package The package to clean * @return bool True if cleaned * * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function cleanPackage(BasePackage $package) { $vendorDir = $this->config->get('vendor-dir'); $targetDir = $package->getTargetDir(); $packageName = $package->getPrettyName(); $packageDir = $targetDir ? $packageName . '/' . $targetDir : $packageName; $rules = isset($this->rules[$packageName]) ? $this->rules[$packageName] : null; if (!$rules) { $this->io->writeError('Rules not found: ' . $packageName); return false; } $dir = $this->filesystem->normalizePath(realpath($vendorDir . '/' . $packageDir)); if (!is_dir($dir)) { $this->io->writeError('Vendor dir not found: ' . $vendorDir . '/' . $packageDir); return false; } //$this->io->write('Rules: ' . print_r($rules, true)); foreach ((array) $rules as $part) { // Split patterns for single globs (should be max 260 chars) $patterns = (array) $part; foreach ($patterns as $pattern) { try { foreach (glob($dir . '/' . $pattern) as $file) { $this->filesystem->remove($file); //$this->io->write('File removed: ' . $file); } } catch (\Exception $e) { $this->io->write("Could not parse {$packageDir} ({$pattern}): " . $e->getMessage()); } } } return true; }
/** * Initializes the internal Symfony Finder with appropriate filters * * @param string $sources Path to source files to be archived * @param array $excludes Composer's own exclude rules from composer.json */ public function __construct($sources, array $excludes) { $fs = new Filesystem(); $sources = $fs->normalizePath($sources); $filters = array(new HgExcludeFilter($sources), new GitExcludeFilter($sources), new ComposerExcludeFilter($sources, $excludes)); $this->finder = new Finder\Finder(); $this->finder->in($sources)->filter(function (\SplFileInfo $file) use($sources, $filters, $fs) { $relativePath = preg_replace('#^' . preg_quote($sources, '#') . '#', '', $fs->normalizePath($file->getRealPath())); $exclude = false; foreach ($filters as $filter) { $exclude = $filter->filter($relativePath, $exclude); } return !$exclude; })->ignoreVCS(true)->ignoreDotFiles(false); parent::__construct($this->finder->getIterator()); }
public function getClassmap() : \Traversable { $filesystem = new Filesystem(); $vendorPath = $filesystem->normalizePath(realpath($this->config->get('vendor-dir'))); $classmapPath = $vendorPath . '/composer/autoload_classmap.php'; if (!is_file($classmapPath)) { throw new \RuntimeException('Th dumped classmap does not exists. Try to run `composer dump-autoload --optimize` first.'); } yield from (include $vendorPath . '/composer/autoload_classmap.php'); }
protected function setUp() { $fs = new Filesystem(); $this->fs = $fs; $this->sources = $fs->normalizePath(realpath(sys_get_temp_dir()) . '/composer_archiver_test' . uniqid(mt_rand(), true)); $fileTree = array('A/prefixA.foo', 'A/prefixB.foo', 'A/prefixC.foo', 'A/prefixD.foo', 'A/prefixE.foo', 'A/prefixF.foo', 'B/sub/prefixA.foo', 'B/sub/prefixB.foo', 'B/sub/prefixC.foo', 'B/sub/prefixD.foo', 'B/sub/prefixE.foo', 'B/sub/prefixF.foo', 'toplevelA.foo', 'toplevelB.foo', 'prefixA.foo', 'prefixB.foo', 'prefixC.foo', 'prefixD.foo', 'prefixE.foo', 'prefixF.foo'); foreach ($fileTree as $relativePath) { $path = $this->sources . '/' . $relativePath; $fs->ensureDirectoryExists(dirname($path)); file_put_contents($path, ''); } }
protected function setUp() { $fs = new Filesystem(); $this->fs = $fs; $this->sources = $fs->normalizePath(realpath(sys_get_temp_dir()) . '/composer_archiver_test' . uniqid(mt_rand(), true)); $fileTree = array('A/prefixA.foo', 'A/prefixB.foo', 'A/prefixC.foo', 'A/prefixD.foo', 'A/prefixE.foo', 'A/prefixF.foo', 'B/sub/prefixA.foo', 'B/sub/prefixB.foo', 'B/sub/prefixC.foo', 'B/sub/prefixD.foo', 'B/sub/prefixE.foo', 'B/sub/prefixF.foo', 'C/prefixA.foo', 'C/prefixB.foo', 'C/prefixC.foo', 'C/prefixD.foo', 'C/prefixE.foo', 'C/prefixF.foo', 'D/prefixA', 'D/prefixB', 'D/prefixC', 'D/prefixD', 'D/prefixE', 'D/prefixF', 'E/subtestA.foo', 'F/subtestA.foo', 'G/subtestA.foo', 'H/subtestA.foo', 'I/J/subtestA.foo', 'K/dirJ/subtestA.foo', 'toplevelA.foo', 'toplevelB.foo', 'prefixA.foo', 'prefixB.foo', 'prefixC.foo', 'prefixD.foo', 'prefixE.foo', 'prefixF.foo', 'parameters.yml', 'parameters.yml.dist', '!important!.txt', '!important_too!.txt'); foreach ($fileTree as $relativePath) { $path = $this->sources . '/' . $relativePath; $fs->ensureDirectoryExists(dirname($path)); file_put_contents($path, ''); } }
protected function setUp() { $fs = new Filesystem(); $this->fs = $fs; $this->sources = $fs->normalizePath($this->getUniqueTmpDirectory()); $fileTree = array('A/prefixA.foo', 'A/prefixB.foo', 'A/prefixC.foo', 'A/prefixD.foo', 'A/prefixE.foo', 'A/prefixF.foo', 'B/sub/prefixA.foo', 'B/sub/prefixB.foo', 'B/sub/prefixC.foo', 'B/sub/prefixD.foo', 'B/sub/prefixE.foo', 'B/sub/prefixF.foo', 'C/prefixA.foo', 'C/prefixB.foo', 'C/prefixC.foo', 'C/prefixD.foo', 'C/prefixE.foo', 'C/prefixF.foo', 'D/prefixA', 'D/prefixB', 'D/prefixC', 'D/prefixD', 'D/prefixE', 'D/prefixF', 'E/subtestA.foo', 'F/subtestA.foo', 'G/subtestA.foo', 'H/subtestA.foo', 'I/J/subtestA.foo', 'K/dirJ/subtestA.foo', 'toplevelA.foo', 'toplevelB.foo', 'prefixA.foo', 'prefixB.foo', 'prefixC.foo', 'prefixD.foo', 'prefixE.foo', 'prefixF.foo', 'parameters.yml', 'parameters.yml.dist', '!important!.txt', '!important_too!.txt', '#weirdfile'); foreach ($fileTree as $relativePath) { $path = $this->sources . '/' . $relativePath; $fs->ensureDirectoryExists(dirname($path)); file_put_contents($path, ''); } }
public function __construct($sources, array $excludes) { $fs = new Filesystem(); $sources = $fs->normalizePath($sources); $filters = array(new HgExcludeFilter($sources), new GitExcludeFilter($sources), new ComposerExcludeFilter($sources, $excludes)); $this->finder = new Finder\Finder(); $filter = function (\SplFileInfo $file) use($sources, $filters, $fs) { if ($file->isLink() && strpos($file->getLinkTarget(), $sources) !== 0) { return false; } $relativePath = preg_replace('#^' . preg_quote($sources, '#') . '#', '', $fs->normalizePath($file->getRealPath())); $exclude = false; foreach ($filters as $filter) { $exclude = $filter->filter($relativePath, $exclude); } return !$exclude; }; if (method_exists($filter, 'bindTo')) { $filter = $filter->bindTo(null); } $this->finder->in($sources)->filter($filter)->ignoreVCS(true)->ignoreDotFiles(false); parent::__construct($this->finder->getIterator()); }
/** * 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 $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 * * @throws \RuntimeException When the path is neither an existing file nor directory * @return array A class map array */ public static function createMap($path, $blacklist = null, IOInterface $io = null, $namespace = null) { if (is_string($path)) { if (is_file($path)) { $path = array(new \SplFileInfo($path)); } elseif (is_dir($path)) { $path = Finder::create()->files()->followLinks()->name('/\\.(php|inc|hh)$/')->in($path); } else { throw new \RuntimeException('Could not scan for classes inside "' . $path . '" which does not appear to be a file nor a folder'); } } $map = array(); $filesystem = new Filesystem(); $cwd = getcwd(); foreach ($path as $file) { $filePath = $file->getPathname(); if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) { continue; } if (!$filesystem->isAbsolutePath($filePath)) { $filePath = $cwd . '/' . $filePath; $filePath = $filesystem->normalizePath($filePath); } else { $filePath = preg_replace('{[\\\\/]{2,}}', '/', $filePath); } if ($blacklist && preg_match($blacklist, strtr($filePath, '\\', '/'))) { continue; } $classes = self::findClasses($filePath); foreach ($classes as $class) { // skip classes not within the given namespace prefix if (null !== $namespace && 0 !== strpos($class, $namespace)) { continue; } if (!isset($map[$class])) { $map[$class] = $filePath; } elseif ($io && $map[$class] !== $filePath && !preg_match('{/(test|fixture|example|stub)s?/}i', strtr($map[$class] . ' ' . $filePath, '\\', '/'))) { $io->writeError('<warning>Warning: Ambiguous class resolution, "' . $class . '"' . ' was found in both "' . $map[$class] . '" and "' . $filePath . '", the first will be used.</warning>'); } } } return $map; }
public function onPostAutoloadDump(ScriptEvent $event) { $banner = 'by atomita/loader-of-less-than-php5.3-plugin'; $config = $event->getComposer()->getConfig(); $filesystem = new Filesystem(); $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir'))); $targetDir = $vendorPath . DIRECTORY_SEPARATOR . 'composer' . DIRECTORY_SEPARATOR; $file = $vendorPath . DIRECTORY_SEPARATOR . 'autoload.php'; if (file_exists($file)) { $content = explode('<?php', file_get_contents($file), 2); $content = str_replace('__DIR__', 'dirname(__FILE__)', end($content)); $append = <<<EOD <?php // @appended {$banner} require dirname(__FILE__) . implode(DIRECTORY_SEPARATOR, explode('/', '/atomita/loader-of-less-than-php5.3-plugin/src/autoload-wrapper.php')); EOD; file_put_contents($file, $append . $content); foreach (glob($targetDir . '*.php') as $path) { $content = file_get_contents($path); switch (true) { case $this->endsWith(DIRECTORY_SEPARATOR . 'ClassLoader.php', $path): $content = str_replace('namespace Composer\\Autoload;', '// namespace Composer\\Autoload;', $content); $content = str_replace('\\InvalidArgumentException', 'InvalidArgumentException;', $content); $content = str_replace('spl_autoload_register(array($this, \'loadClass\'), true, $prepend);', 'spl_autoload_register(array($this, \'loadClass\'));', $content); break; case $this->endsWith(DIRECTORY_SEPARATOR . 'autoload_real.php', $path): $content = str_replace('\'Composer\\Autoload\\ClassLoader\'', '\'ClassLoader\'', $content); $content = str_replace('\\Composer\\Autoload\\ClassLoader', 'ClassLoader', $content); $content = preg_replace('/spl_autoload_register\\(array\\(\'([^\']*?)\', \'loadClassLoader\'\\), true, true\\);/', 'spl_autoload_register(array(\'${1}\', \'loadClassLoader\'));', $content); default: $content = str_replace('__DIR__', 'dirname(__FILE__)', $content); break; } file_put_contents($path, $content); } } }
/** * @param \Composer\Script\Event $event * @param bool $calledByPlugin * @return bool * @throws \Exception */ public static function generateAliasMap(\Composer\Script\Event $event, $calledByPlugin = false) { if (!$calledByPlugin) { $event->getIO()->write(' <warning>Please remove the section "post-autoload-dump": "Helhum\\ClassAliasLoader\\Composer\\ClassAliasGenerator::generateAliasMap" from your composer.json! It is obsolete.</warning> '); return false; } $event->getIO()->write('<info>Generating class alias map files</info>'); $composer = $event->getComposer(); $config = $composer->getConfig(); $filesystem = new Filesystem(); $filesystem->ensureDirectoryExists($config->get('vendor-dir')); $basePath = $filesystem->normalizePath(realpath(getcwd())); $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir'))); $targetDir = $vendorPath . '/composer'; $filesystem->ensureDirectoryExists($targetDir); $mainPackage = $composer->getPackage(); $autoLoadGenerator = $composer->getAutoloadGenerator(); $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $packageMap = $autoLoadGenerator->buildPackageMap($composer->getInstallationManager(), $mainPackage, $localRepo->getCanonicalPackages()); $caseSensitiveClassLoading = self::caseSensitiveClassLoading($mainPackage, $targetDir) ? 'true' : 'false'; $aliasToClassNameMapping = array(); $classNameToAliasMapping = array(); $mappingFound = false; foreach ($packageMap as $item) { list($package, $installPath) = $item; $extra = $package->getExtra(); if (!empty($extra['class-alias-maps'])) { if (!is_array($extra['class-alias-maps'])) { throw new \Exception('"class-alias-maps" must be an array'); } foreach ($extra['class-alias-maps'] as $mapFile) { $mapFilePath = ($installPath ?: $basePath) . '/' . $filesystem->normalizePath($mapFile); if (is_file($mapFilePath)) { $packageAliasMap = (require $mapFilePath); if (!is_array($packageAliasMap)) { throw new \Exception('"class alias maps" must return an array', 1422625075); } if (!empty($packageAliasMap)) { $mappingFound = true; } foreach ($packageAliasMap as $aliasClassName => $className) { $lowerCasedAliasClassName = strtolower($aliasClassName); $aliasToClassNameMapping[$lowerCasedAliasClassName] = $className; $classNameToAliasMapping[$className][$lowerCasedAliasClassName] = $lowerCasedAliasClassName; } } } } } if (!$mappingFound) { return false; } $exportArray = array('aliasToClassNameMapping' => $aliasToClassNameMapping, 'classNameToAliasMapping' => $classNameToAliasMapping); $fileContent = '<?php' . chr(10) . 'return '; $fileContent .= var_export($exportArray, true); $fileContent .= ';'; file_put_contents($targetDir . '/autoload_classaliasmap.php', $fileContent); $originalAutoloadFileContent = file_get_contents($vendorPath . '/autoload.php'); preg_match('/return ComposerAutoloaderInit[^;]*;/', $originalAutoloadFileContent, $matches); $originalAutoloadFileContent = str_replace($matches[0], '', $originalAutoloadFileContent); $composerClassLoaderInit = str_replace(array('return ', ';'), '', $matches[0]); $autoloadFileContent = <<<EOF {$originalAutoloadFileContent} // autoload.php @generated by Helhum/ClassAliasLoader return call_user_func(function() { \t\$composerClassLoader = {$composerClassLoaderInit}; \t\$aliasClassLoader = new Helhum\\ClassAliasLoader\\Composer\\ClassAliasLoader(\$composerClassLoader); \t\$classAliasMap = require __DIR__ . '/composer/autoload_classaliasmap.php'; \t\$aliasClassLoader->setAliasMap(\$classAliasMap); \t\$aliasClassLoader->setCaseSensitiveClassLoading({$caseSensitiveClassLoading}); \tspl_autoload_register(array(\$aliasClassLoader, 'loadClassWithAlias'), true, true); \treturn \$aliasClassLoader; }); EOF; file_put_contents($vendorPath . '/autoload.php', $autoloadFileContent); return true; }
protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $path) { if (!$filesystem->isAbsolutePath($path)) { $path = $basePath . '/' . $path; } $path = $filesystem->normalizePath($path); $baseDir = ''; if (strpos($path . '/', $vendorPath . '/') === 0) { $path = substr($path, strlen($vendorPath)); $baseDir = '$vendorDir'; if ($path !== false) { $baseDir .= " . "; } } else { $path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true)); if (!$filesystem->isAbsolutePath($path)) { $baseDir = '$baseDir . '; $path = '/' . $path; } } if (preg_match('/\\.phar$/', $path)) { $baseDir = "'phar://' . " . $baseDir; } return $baseDir . ($path !== false ? var_export($path, true) : ""); }
protected function generateDefaultAlias(PackageInterface $package) { $fs = new Filesystem(); $vendorDir = $fs->normalizePath($this->vendorDir); $autoload = $package->getAutoload(); $aliases = []; if (!empty($autoload['psr-0'])) { foreach ($autoload['psr-0'] as $name => $path) { $name = str_replace('\\', '/', trim($name, '\\')); if (!$fs->isAbsolutePath($path)) { $path = $this->vendorDir . '/' . $package->getPrettyName() . '/' . $path; } $path = $fs->normalizePath($path); if (strpos($path . '/', $vendorDir . '/') === 0) { $aliases["@{$name}"] = '<vendor-dir>' . substr($path, strlen($vendorDir)) . '/' . $name; } else { $aliases["@{$name}"] = $path . '/' . $name; } } } if (!empty($autoload['psr-4'])) { foreach ($autoload['psr-4'] as $name => $path) { $name = str_replace('\\', '/', trim($name, '\\')); if (!$fs->isAbsolutePath($path)) { $path = $this->vendorDir . '/' . $package->getPrettyName() . '/' . $path; } $path = $fs->normalizePath($path); if (strpos($path . '/', $vendorDir . '/') === 0) { $aliases["@{$name}"] = '<vendor-dir>' . substr($path, strlen($vendorDir)); } else { $aliases["@{$name}"] = $path; } } } return $aliases; }
public function apply(CommandEvent $event) { $composer = $event->getComposer(); $fs = new Filesystem(); $this->baseDir = $fs->normalizePath(realpath(getcwd())); $this->vendorDir = rtrim($composer->getConfig()->get('vendor-dir'), '/'); $rootPackage = $composer->getPackage(); $this->setRootPackage($rootPackage, $event); if ($event->getName() === ScriptEvents::POST_INSTALL_CMD) { $extra = $rootPackage->getExtra(); if (isset($extra[self::EXTRA_PERMISSION])) { static::setPermission($extra[self::EXTRA_PERMISSION]); } if (isset($extra[self::EXTRA_SYMLINK])) { static::generateSymlink($extra[self::EXTRA_SYMLINK]); } } $extensions = $this->loadExtensions(); $packages = $composer->getRepositoryManager()->getLocalRepository()->findPackages('deesoft/yii2-composer'); if (!empty($packages)) { /* @var $package PackageInterface */ $package = reset($packages); $extensions[$package->getName()] = ['name' => $package->getName(), 'version' => $package->getVersion(), 'alias' => ['@dee/composer' => '<vendor-dir>/deesoft/yii2-composer'], 'bootstrap' => 'dee\\composer\\Bootstrap']; } else { unset($extensions['deesoft/yii2-composer']); } $this->saveExtensions($extensions); }
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); }
protected function getAutoloadPath() { $filesystem = new Filesystem(); $config = $this->composer->getConfig(); $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir'))); return $vendorPath . '/autoload.php'; }
/** * @dataProvider provideNormalizedPaths */ public function testNormalizePath($expected, $actual) { $fs = new Filesystem(); $this->assertEquals($expected, $fs->normalizePath($actual)); }
function setup() { $allModulesDir = $this->parameters->getAllModulesDirs(); $allPluginsDir = $this->parameters->getAllPluginsDirs(); $allModules = $this->parameters->getAllSingleModuleDirs(); if (!count($allModulesDir) && !count($allModules) && !count($allPluginsDir)) { // nothing to setup return; } $appDir = $this->parameters->getAppDir(); if (!$appDir) { throw new \Exception("No application directory is set in JelixParameters"); } $configDir = $this->parameters->getVarConfigDir(); $vendorDir = $this->parameters->getVendorDir(); $fs = new Filesystem(); // open the localconfig.ini.php file $localinifile = $configDir . 'localconfig.ini.php'; if (!file_exists($localinifile)) { if (!file_exists($configDir)) { throw new \Exception('Configuration directory "' . $configDir . '" for the app does not exist'); } file_put_contents($localinifile, "<" . "?php\n;die(''); ?" . ">\n\n"); } $ini = new IniModifier($localinifile); if (count($allModulesDir)) { $modulesPath = ''; foreach ($allModulesDir as $path) { $path = $fs->findShortestPath($appDir, $vendorDir . $path, true); if ($fs->isAbsolutePath($path)) { $modulesPath .= ',' . $path; } else { $modulesPath .= ',app:' . $path; } } $modulesPath = trim($modulesPath, ','); $ini->setValue('modulesPath', $modulesPath); } if (count($allPluginsDir)) { $pluginsPath = ''; foreach ($allPluginsDir as $path) { $path = $fs->findShortestPath($appDir, $vendorDir . $path, true); if ($fs->isAbsolutePath($path)) { $pluginsPath .= ',' . $path; } else { $pluginsPath .= ',app:' . $path; } } $pluginsPath = trim($pluginsPath, ','); $ini->setValue('pluginsPath', $pluginsPath); } if (count($allModules)) { // erase first all "<module>.path" keys foreach ($ini->getValues('modules') as $key => $val) { if (preg_match("/\\.path\$/", $key)) { $ini->removeValue($key, "modules"); } } foreach ($allModules as $path) { $path = $fs->normalizePath($path); $moduleName = basename($path); $path = $fs->findShortestPath($appDir, $vendorDir . $path, true); if (!$fs->isAbsolutePath($path)) { $path = 'app:' . $path; } $ini->setValue($moduleName . '.path', $path, 'modules'); } } $ini->save(); }
/** * @return bool * @throws \Exception */ public function generateAliasMap() { $config = $this->composer->getConfig(); $filesystem = new Filesystem(); $filesystem->ensureDirectoryExists($config->get('vendor-dir')); $basePath = $this->extractBasePath($config); $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir'))); $targetDir = $vendorPath . '/composer'; $filesystem->ensureDirectoryExists($targetDir); $mainPackage = $this->composer->getPackage(); $autoLoadGenerator = $this->composer->getAutoloadGenerator(); $localRepo = $this->composer->getRepositoryManager()->getLocalRepository(); $packageMap = $autoLoadGenerator->buildPackageMap($this->composer->getInstallationManager(), $mainPackage, $localRepo->getCanonicalPackages()); $aliasToClassNameMapping = array(); $classNameToAliasMapping = array(); $classAliasMappingFound = false; foreach ($packageMap as $item) { /** @var PackageInterface $package */ list($package, $installPath) = $item; $aliasLoaderConfig = new \TYPO3\ClassAliasLoader\Config($package, $this->IO); if ($aliasLoaderConfig->get('class-alias-maps') !== null) { if (!is_array($aliasLoaderConfig->get('class-alias-maps'))) { throw new \Exception('Configuration option "class-alias-maps" must be an array'); } foreach ($aliasLoaderConfig->get('class-alias-maps') as $mapFile) { $mapFilePath = ($installPath ?: $basePath) . '/' . $filesystem->normalizePath($mapFile); if (!is_file($mapFilePath)) { $this->IO->writeError(sprintf('The class alias map file "%s" configured in package "%s" was not found!', $mapFile, $package->getName())); } else { $packageAliasMap = (require $mapFilePath); if (!is_array($packageAliasMap)) { throw new \Exception('Class alias map files must return an array', 1422625075); } if (!empty($packageAliasMap)) { $classAliasMappingFound = true; } foreach ($packageAliasMap as $aliasClassName => $className) { $lowerCasedAliasClassName = strtolower($aliasClassName); $aliasToClassNameMapping[$lowerCasedAliasClassName] = $className; $classNameToAliasMapping[$className][$lowerCasedAliasClassName] = $lowerCasedAliasClassName; } } } } } $mainPackageAliasLoaderConfig = new \TYPO3\ClassAliasLoader\Config($mainPackage); $alwaysAddAliasLoader = $mainPackageAliasLoaderConfig->get('always-add-alias-loader'); $caseSensitiveClassLoading = $mainPackageAliasLoaderConfig->get('autoload-case-sensitivity'); if (!$alwaysAddAliasLoader && !$classAliasMappingFound && $caseSensitiveClassLoading) { // No mapping found in any package and no insensitive class loading active. We return early and skip rewriting // Unless user configured alias loader to be always added return false; } $caseSensitiveClassLoadingString = $caseSensitiveClassLoading ? 'true' : 'false'; $this->IO->write('<info>Generating ' . ($classAliasMappingFound ? ' ' : 'empty ') . 'class alias map file</info>'); $this->generateAliasMapFile($aliasToClassNameMapping, $classNameToAliasMapping, $targetDir); $suffix = null; 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)); } $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true'; $aliasLoaderInitClassContent = <<<EOF <?php // autoload_alias_loader_real.php @generated by typo3/class-alias-loader class ClassAliasLoaderInit{$suffix} { private static \$loader; public static function initializeClassAliasLoader(\$composerClassLoader) { if (null !== self::\$loader) { return self::\$loader; } self::\$loader = \$composerClassLoader; \$classAliasMap = require __DIR__ . '/autoload_classaliasmap.php'; \$classAliasLoader = new TYPO3\\ClassAliasLoader\\ClassAliasLoader(\$composerClassLoader); \$classAliasLoader->setAliasMap(\$classAliasMap); \$classAliasLoader->setCaseSensitiveClassLoading({$caseSensitiveClassLoadingString}); \$classAliasLoader->register({$prependAutoloader}); TYPO3\\ClassAliasLoader\\ClassAliasMap::setClassAliasLoader(\$classAliasLoader); return self::\$loader; } } EOF; file_put_contents($targetDir . '/autoload_alias_loader_real.php', $aliasLoaderInitClassContent); if (!$caseSensitiveClassLoading) { $this->IO->write('<info>Re-writing class map to support case insensitive class loading</info>'); if (!$this->optimizeAutoloadFiles) { $this->IO->write('<warning>Case insensitive class loading only works reliably if you use the optimize class loading feature of composer</warning>'); } $this->rewriteClassMapWithLowerCaseClassNames($targetDir); } $this->IO->write('<info>Inserting class alias loader into main autoload.php file</info>'); $this->modifyMainAutoloadFile($vendorPath . '/autoload.php', $suffix); return true; }
protected function generateDefaultAlias(PackageInterface $package) { $fs = new Filesystem(); $vendorDir = $fs->normalizePath($this->vendorDir); $autoload = $package->getAutoload(); $aliases = []; if (!empty($autoload['psr-0'])) { foreach ($autoload['psr-0'] as $name => $path) { $name = str_replace('\\', '/', trim($name, '\\')); if (!$fs->isAbsolutePath($path)) { $path = $this->vendorDir . '/' . $package->getPrettyName() . '/' . $path; } $path = $fs->normalizePath($path); if (strpos($path . '/', $vendorDir . '/') === 0) { $aliases["@{$name}"] = '<vendor-dir>' . substr($path, strlen($vendorDir)) . '/' . $name; } else { $aliases["@{$name}"] = $path . '/' . $name; } } } if (!empty($autoload['psr-4'])) { foreach ($autoload['psr-4'] as $name => $path) { if (is_array($path)) { // ignore psr-4 autoload specifications with multiple search paths // we can not convert them into aliases as they are ambiguous continue; } $name = str_replace('\\', '/', trim($name, '\\')); if (!$fs->isAbsolutePath($path)) { $path = $this->vendorDir . '/' . $package->getPrettyName() . '/' . $path; } $path = $fs->normalizePath($path); if (strpos($path . '/', $vendorDir . '/') === 0) { $aliases["@{$name}"] = '<vendor-dir>' . substr($path, strlen($vendorDir)); } else { $aliases["@{$name}"] = $path; } } } return $aliases; }
/** * Initialize the extension dir based on configuration */ protected function initializeExtensionDir() { $configDir = $this->filesystem->normalizePath($this->pluginConfig->get('config-dir')); $this->extensionDir = $configDir . DIRECTORY_SEPARATOR . self::TYPO3_EXT_DIR; }
/** * Get a file path from a project-root-relative file name. * * @since 0.1.0 * * @param string $fileName Project-root-relative file name to get the path of. * * @return string Complete path to the requested file. * @throws RuntimeException If the file could not be matched. */ public static function getFile($fileName) { $filesystem = new Filesystem(); $file = $filesystem->normalizePath(__DIR__ . '/../' . $fileName); if (!file_exists($file)) { throw new RuntimeException(sprintf('Could not find a matching file for file name "%1$s".', $fileName)); } return $file; }
/** * Get the path to the 'vendor' directory. * * @return string */ public function getVendorPath() { $config = $this->composer->getConfig(); $filesystem = new Filesystem(); $filesystem->ensureDirectoryExists($config->get('vendor-dir')); $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir'))); return $vendorPath; }
public function onPostInstallCommand(ScriptEvent $event) { $composer = $event->getComposer(); $config = $composer->getConfig(); $filesystem = new Filesystem(); if ($composer->getPackage()) { $extra = $composer->getPackage()->getExtra(); if (isset($extra['webroot-dir'])) { $wp_dir = $extra['webroot-dir']; $wp_config_dir = "{$wp_dir}/wp-environment-config"; $wp_config = $filesystem->normalizePath($wp_dir . '/wp-config.php'); $wp_config_sample = $filesystem->normalizePath($wp_dir . '/wp-config-sample.php'); if (!file_exists($wp_config) or false === strpos(file_get_contents($wp_config), $this->banner)) { file_put_contents($wp_config, <<<EOD <?php {$this->servername_switch} ?> <?php // {$this->banner} {$this->call_environment} // @end generated EOD ); } // generate wp-environment-config.php file_put_contents($filesystem->normalizePath($wp_dir . '/wp-environment-config.php'), <<<EOD <?php // {$this->banner} {$this->process_environment} // @end generated EOD ); // copy wp-config-sample.php $filesystem->ensureDirectoryExists($wp_config_dir); foreach (array('production', 'staging', 'development', 'local') as $env) { if (!file_exists($filesystem->normalizePath($path = "{$wp_config_dir}/{$env}/wp-config-sample.php"))) { $filesystem->ensureDirectoryExists("{$wp_config_dir}/{$env}"); copy($wp_config_sample, $path); } } } } }