Esempio n. 1
0
 public function loadRepository(RepositoryInterface $repo)
 {
     foreach ($repo->getPackages() as $package) {
         if ($package instanceof AliasPackage) {
             continue;
         }
         if ('composer-plugin' === $package->getType()) {
             $requiresComposer = null;
             foreach ($package->getRequires() as $link) {
                 if ($link->getTarget() == 'composer-plugin-api') {
                     $requiresComposer = $link->getConstraint();
                 }
             }
             if (!$requiresComposer) {
                 throw new \RuntimeException("Plugin " . $package->getName() . " is missing a require statement for a version of the composer-plugin-api package.");
             }
             if (!$requiresComposer->matches(new VersionConstraint('==', $this->versionParser->normalize(PluginInterface::PLUGIN_API_VERSION)))) {
                 $this->io->writeError("<warning>The plugin " . $package->getName() . " requires a version of composer-plugin-api that does not match your composer installation. You may need to run composer update with the '--no-plugins' option.</warning>");
             }
             $this->registerPackage($package);
         }
         if ('composer-installer' === $package->getType()) {
             $this->registerPackage($package);
         }
     }
 }
Esempio n. 2
0
 /**
  * @param string $name
  * @param ConstraintInterface $constraint
  * @return \Composer\Package\PackageInterface
  */
 private function getPackage($name, ConstraintInterface $constraint)
 {
     $package = $this->repository->findPackage($name, $constraint);
     if ($package === NULL) {
         return new ComposerPackage($name, '0.0.0.1', '--no-dev');
     }
     return $package;
 }
Esempio n. 3
0
 private function processPackages()
 {
     foreach ($this->repos->getPackages() as $package) {
         if ($package instanceof CompletePackageInterface) {
             $this->processPackageDependencies($package);
         }
     }
 }
Esempio n. 4
0
 /**
  * Update a project
  *
  * @param \Packagist\WebBundle\Entity\Package $package
  * @param RepositoryInterface $repository the repository instance used to update from
  * @param int $flags a few of the constants of this class
  * @param \DateTime $start
  */
 public function update(Package $package, RepositoryInterface $repository, $flags = 0, \DateTime $start = null)
 {
     $blacklist = '{^symfony/symfony (2.0.[456]|dev-charset|dev-console)}i';
     if (null === $start) {
         $start = new \DateTime();
     }
     $pruneDate = clone $start;
     $pruneDate->modify('-8days');
     $versions = $repository->getPackages();
     $em = $this->doctrine->getManager();
     if ($repository->hadInvalidBranches()) {
         throw new InvalidRepositoryException('Some branches contained invalid data and were discarded, it is advised to review the log and fix any issues present in branches');
     }
     usort($versions, function ($a, $b) {
         $aVersion = $a->getVersion();
         $bVersion = $b->getVersion();
         if ($aVersion === '9999999-dev' || 'dev-' === substr($aVersion, 0, 4)) {
             $aVersion = 'dev';
         }
         if ($bVersion === '9999999-dev' || 'dev-' === substr($bVersion, 0, 4)) {
             $bVersion = 'dev';
         }
         if ($aVersion === $bVersion) {
             return $a->getReleaseDate() > $b->getReleaseDate() ? 1 : -1;
         }
         return version_compare($a->getVersion(), $b->getVersion());
     });
     $versionRepository = $this->doctrine->getRepository('PackagistWebBundle:Version');
     if ($flags & self::DELETE_BEFORE) {
         foreach ($package->getVersions() as $version) {
             $versionRepository->remove($version);
         }
         $em->flush();
         $em->refresh($package);
     }
     foreach ($versions as $version) {
         if ($version instanceof AliasPackage) {
             continue;
         }
         if (preg_match($blacklist, $version->getName() . ' ' . $version->getPrettyVersion())) {
             continue;
         }
         $this->updateInformation($package, $version, $flags);
         $em->flush();
     }
     // remove outdated versions
     foreach ($package->getVersions() as $version) {
         if ($version->getUpdatedAt() < $pruneDate) {
             $versionRepository->remove($version);
         }
     }
     $package->setUpdatedAt(new \DateTime());
     $package->setCrawledAt(new \DateTime());
     $em->flush();
 }
Esempio n. 5
0
 /**
  * Adds a repository and its packages to this package pool
  *
  * @param RepositoryInterface $repo A package repository
  */
 public function addRepository(RepositoryInterface $repo)
 {
     $this->repositories[] = $repo;
     foreach ($repo->getPackages() as $package) {
         $package->setId(count($this->packages) + 1);
         $this->packages[] = $package;
         foreach ($package->getNames() as $name) {
             $this->packageByName[$name][] = $package;
         }
     }
 }
Esempio n. 6
0
 private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array())
 {
     $requires = array_keys($package->getRequires());
     $packageListNames = array_keys($bucket);
     $packages = array_filter($repo->getPackages(), function ($package) use($requires, $packageListNames) {
         return in_array($package->getName(), $requires) && !in_array($package->getName(), $packageListNames);
     });
     $bucket = $this->appendPackages($packages, $bucket);
     foreach ($packages as $package) {
         $bucket = $this->filterRequiredPackages($repo, $package, $bucket);
     }
     return $bucket;
 }
 public function setUp()
 {
     $this->composerMock = $this->getMockBuilder(Composer::class)->disableOriginalConstructor()->getMock();
     $this->lockerMock = $this->getMockBuilder(Locker::class)->disableOriginalConstructor()->getMock();
     $this->lockerRepositoryMock = $this->getMockForAbstractClass(\Composer\Repository\RepositoryInterface::class);
     $this->packageMock = $this->getMockForAbstractClass(\Composer\Package\CompletePackageInterface::class);
     $this->lockerMock->method('getLockedRepository')->willReturn($this->lockerRepositoryMock);
     $this->packageMock->method('getType')->willReturn('metapackage');
     $this->packageMock->method('getPrettyName')->willReturn('magento/product-test-package-name');
     $this->packageMock->method('getName')->willReturn('magento/product-test-package-name');
     $this->packageMock->method('getPrettyVersion')->willReturn('123.456.789');
     $this->lockerRepositoryMock->method('getPackages')->willReturn([$this->packageMock]);
     $objectManager = new ObjectManager($this);
     $this->composerInformation = $objectManager->getObject(\Magento\Framework\Composer\ComposerInformation::class, ['composer' => $this->composerMock, 'locker' => $this->lockerMock]);
 }
Esempio n. 8
0
 protected function setupInstalledMap()
 {
     $this->installedMap = array();
     foreach ($this->installed->getPackages() as $package) {
         $this->installedMap[$package->id] = $package;
     }
 }
Esempio n. 9
0
 /**
  * Adds a repository and its packages to this package pool
  *
  * @param RepositoryInterface $repo        A package repository
  * @param array               $rootAliases
  */
 public function addRepository(RepositoryInterface $repo, $rootAliases = array())
 {
     if ($repo instanceof CompositeRepository) {
         $repos = $repo->getRepositories();
     } else {
         $repos = array($repo);
     }
     foreach ($repos as $repo) {
         $this->repositories[] = $repo;
         $exempt = $repo instanceof PlatformRepository || $repo instanceof InstalledRepositoryInterface;
         if ($repo instanceof ComposerRepository && $repo->hasProviders()) {
             $this->providerRepos[] = $repo;
             $repo->setRootAliases($rootAliases);
             $repo->resetPackageIds();
         } else {
             foreach ($repo->getPackages() as $package) {
                 $names = $package->getNames();
                 $stability = $package->getStability();
                 if ($exempt || $this->isPackageAcceptable($names, $stability)) {
                     $package->setId($this->id++);
                     $this->packages[] = $package;
                     $this->packageByExactName[$package->getName()][$package->id] = $package;
                     foreach ($names as $provided) {
                         $this->packageByName[$provided][] = $package;
                     }
                     // handle root package aliases
                     $name = $package->getName();
                     if (isset($rootAliases[$name][$package->getVersion()])) {
                         $alias = $rootAliases[$name][$package->getVersion()];
                         if ($package instanceof AliasPackage) {
                             $package = $package->getAliasOf();
                         }
                         $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
                         $aliasPackage->setRootPackageAlias(true);
                         $aliasPackage->setId($this->id++);
                         $package->getRepository()->addPackage($aliasPackage);
                         $this->packages[] = $aliasPackage;
                         $this->packageByExactName[$aliasPackage->getName()][$aliasPackage->id] = $aliasPackage;
                         foreach ($aliasPackage->getNames() as $name) {
                             $this->packageByName[$name][] = $aliasPackage;
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * Output suggested packages.
  * Do not list the ones already installed if installed repository provided.
  *
  * @param  RepositoryInterface       $installedRepo Installed packages
  * @return SuggestedPackagesReporter
  */
 public function output(RepositoryInterface $installedRepo = null)
 {
     $suggestedPackages = $this->getPackages();
     $installedPackages = array();
     if (null !== $installedRepo && !empty($suggestedPackages)) {
         foreach ($installedRepo->getPackages() as $package) {
             $installedPackages = array_merge($installedPackages, $package->getNames());
         }
     }
     foreach ($suggestedPackages as $suggestion) {
         if (in_array($suggestion['target'], $installedPackages)) {
             continue;
         }
         $this->io->writeError(sprintf('%s suggests installing %s (%s)', $suggestion['source'], $suggestion['target'], $suggestion['reason']));
     }
     return $this;
 }
Esempio n. 11
0
 public function addRepository(RepositoryInterface $repository)
 {
     if ($repository instanceof self) {
         foreach ($repository->getRepositories() as $repo) {
             $this->addRepository($repo);
         }
     } else {
         $this->repositories[] = $repository;
     }
 }
Esempio n. 12
0
 /**
  * Decorate a package.
  *
  * @param string $packageName The name of the package to decorate.
  *
  * @return VersionedPackage
  *
  * @throws \InvalidArgumentException When the package could not be found.
  */
 protected function decorate($packageName)
 {
     $results = $this->repository->findPackages($packageName);
     if (!count($results)) {
         throw new \InvalidArgumentException('Could not find package with specified name ' . $packageName);
     }
     $latest = array_slice($results, 0, 1)[0];
     $versions = array_slice($results, 1);
     $package = new VersionedPackage($latest, $versions);
     return $this->decorateWithPackagistStats($package);
 }
Esempio n. 13
0
 public function collectData(RepositoryInterface $repo)
 {
     $puzzleData = [];
     foreach ($repo->getPackages() as $package) {
         /** @var Package $package */
         $extra = $package->getExtra();
         if (!empty($extra["downsider-puzzle-di"]) && is_array($extra["downsider-puzzle-di"])) {
             foreach ($extra["downsider-puzzle-di"] as $key => $config) {
                 if ($key == (string) (int) $key) {
                     continue;
                 }
                 if (!array_key_exists($key, $puzzleData)) {
                     $puzzleData[$key] = array();
                 }
                 $puzzleConfig = ["name" => $package->getName(), "path" => $this->installationManager->getInstallPath($package) . "/" . $config["path"]];
                 if (!empty($config["alias"])) {
                     $puzzleConfig["alias"] = $config["alias"];
                 }
                 $puzzleData[$key][] = $puzzleConfig;
             }
         }
     }
     return $puzzleData;
 }
Esempio n. 14
0
 /**
  * Adds a repository and its packages to this package pool
  *
  * @param RepositoryInterface $repo A package repository
  */
 public function addRepository(RepositoryInterface $repo)
 {
     if ($repo instanceof CompositeRepository) {
         $repos = $repo->getRepositories();
     } else {
         $repos = array($repo);
     }
     $id = count($this->packages) + 1;
     foreach ($repos as $repo) {
         $this->repositories[] = $repo;
         $exempt = $repo instanceof PlatformRepository || $repo instanceof InstalledRepositoryInterface;
         foreach ($repo->getPackages() as $package) {
             $name = $package->getName();
             $stability = $package->getStability();
             if ($exempt || !isset($this->stabilityFlags[$name]) && isset($this->acceptableStabilities[$stability]) || isset($this->stabilityFlags[$name]) && BasePackage::$stabilities[$stability] <= $this->stabilityFlags[$name]) {
                 $package->setId($id++);
                 $this->packages[] = $package;
                 foreach ($package->getNames() as $name) {
                     $this->packageByName[$name][] = $package;
                 }
             }
         }
     }
 }
Esempio n. 15
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');
    }
Esempio n. 16
0
 private function createRequest(Pool $pool, RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
 {
     $request = new Request($pool);
     $constraint = new VersionConstraint('=', $rootPackage->getVersion());
     $constraint->setPrettyString($rootPackage->getPrettyVersion());
     $request->install($rootPackage->getName(), $constraint);
     $fixedPackages = $platformRepo->getPackages();
     if ($this->additionalInstalledRepository) {
         $additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
         $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
     }
     // fix the version of all platform packages + additionally installed packages
     // to prevent the solver trying to remove or update those
     $provided = $rootPackage->getProvides();
     foreach ($fixedPackages as $package) {
         $constraint = new VersionConstraint('=', $package->getVersion());
         $constraint->setPrettyString($package->getPrettyVersion());
         // skip platform packages that are provided by the root package
         if ($package->getRepository() !== $platformRepo || !isset($provided[$package->getName()]) || !$provided[$package->getName()]->getConstraint()->matches($constraint)) {
             $request->fix($package->getName(), $constraint);
         }
     }
     return $request;
 }
Esempio n. 17
0
 /**
  * Executes markAlias operation.
  *
  * @param RepositoryInterface           $repo      repository in which to check
  * @param MarkAliasUninstalledOperation $operation operation instance
  */
 public function markAliasUninstalled(RepositoryInterface $repo, MarkAliasUninstalledOperation $operation)
 {
     $package = $operation->getPackage();
     $repo->removePackage($package);
 }
Esempio n. 18
0
 /**
  * prints all available versions of this package and highlights the installed one if any
  */
 protected function printVersions(InputInterface $input, OutputInterface $output, PackageInterface $package, RepositoryInterface $installedRepo, RepositoryInterface $repos)
 {
     if ($input->getArgument('version')) {
         $output->writeln('<info>version</info>  : ' . $package->getPrettyVersion());
         return;
     }
     $versions = array();
     foreach ($repos->findPackages($package->getName()) as $version) {
         $versions[$version->getPrettyVersion()] = $version->getVersion();
     }
     uasort($versions, 'version_compare');
     $versions = implode(', ', array_keys(array_reverse($versions)));
     // highlight installed version
     if ($installedRepo->hasPackage($package)) {
         $versions = str_replace($package->getPrettyVersion(), '<info>* ' . $package->getPrettyVersion() . '</info>', $versions);
     }
     $output->writeln('<info>versions</info> : ' . $versions);
 }
Esempio n. 19
0
 protected function mapFromRepo(RepositoryInterface $repo)
 {
     $map = array();
     foreach ($repo->getPackages() as $package) {
         $map[$package->getId()] = true;
     }
     return $map;
 }
 /**
  * Build dependency graph of installed packages.
  *
  * @param RepositoryInterface $repository
  *
  * @return array
  */
 protected function calculateDependencyMap(RepositoryInterface $repository, $inverted = false)
 {
     $dependencyMap = array();
     /** @var \Composer\Package\PackageInterface $package */
     foreach ($repository->getPackages() as $package) {
         $this->fillDependencyMap($package, $dependencyMap, $inverted);
     }
     return $dependencyMap;
 }
Esempio n. 21
0
 /**
  * prints all available versions of this package and highlights the installed one if any
  */
 protected function printVersions(InputInterface $input, OutputInterface $output, CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo, RepositoryInterface $repos)
 {
     uasort($versions, 'version_compare');
     $versions = array_keys(array_reverse($versions));
     // highlight installed version
     if ($installedRepo->hasPackage($package)) {
         $installedVersion = $package->getPrettyVersion();
         $key = array_search($installedVersion, $versions);
         if (false !== $key) {
             $versions[$key] = '<info>* ' . $installedVersion . '</info>';
         }
     }
     $versions = implode(', ', $versions);
     $output->writeln('<info>versions</info> : ' . $versions);
 }
Esempio n. 22
0
 /**
  * Loads the most "current" list of packages that are installed meaning from lock ideally or from installed repo as fallback
  * @param  RepositoryInterface $installedRepo
  * @return array
  */
 private function getCurrentPackages($installedRepo)
 {
     if ($this->locker->isLocked()) {
         try {
             return $this->locker->getLockedRepository(true)->getPackages();
         } catch (\RuntimeException $e) {
             // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
             return $this->locker->getLockedRepository()->getPackages();
         }
     }
     return $installedRepo->getPackages();
 }
Esempio n. 23
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");
            }
        }
    }
 public function uninstall(RepositoryInterface $repo, UninstallOperation $operation)
 {
     $this->uninstalled[] = $operation->getPackage();
     $this->trace[] = (string) $operation;
     $repo->removePackage($operation->getPackage());
 }
Esempio n. 25
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');
    }
Esempio n. 26
0
 /**
  * Gets All or filtered Packages of a Repository.
  *
  * @param RepositoryInterface $repo a Repository
  *
  * @return PackageInterface[]
  */
 private function getPackages(RepositoryInterface $repo)
 {
     $packages = array();
     if ($this->hasFilterForPackages()) {
         // apply package filter if defined
         foreach ($this->packagesFilter as $filter) {
             $packages += $repo->findPackages($filter);
         }
     } else {
         // process other repos directly
         $packages = $repo->getPackages();
     }
     return $packages;
 }
Esempio n. 27
0
 /**
  * Convert the information of all packages in a repository to an array used by json API.
  *
  * @param RepositoryInterface      $repository   The repository holding the packages to convert.
  *
  * @param bool                     $requiredOnly If true, return only the packages added to the root package as
  *                                               require.
  *
  * @param null|RepositoryInterface $upgradeList  The packages available as upgrades.
  *
  * @return JsonArray
  */
 public function convertRepositoryToArray(RepositoryInterface $repository, $requiredOnly = false, RepositoryInterface $upgradeList = null)
 {
     $requires = $requiredOnly ? $this->rootPackage->getRequires() : false;
     $packages = new JsonArray();
     /** @var \Composer\Package\PackageInterface $package */
     foreach ($repository->getPackages() as $package) {
         $name = $package->getPrettyName();
         $esc = $packages->escape($name);
         if (false === $requires || isset($requires[$name])) {
             $upgradePkg = null;
             if ($upgradeList) {
                 $upgradePkg = $upgradeList->findPackage($name, '*');
             }
             $packages->set($esc, $this->convertPackageToArray($package, $upgradePkg)->getData());
         }
     }
     return $packages;
 }
Esempio n. 28
0
 /**
  * Load all plugins and installers from a repository
  *
  * Note that plugins in the specified repository that rely on events that
  * have fired prior to loading will be missed. This means you likely want to
  * call this method as early as possible.
  *
  * @param RepositoryInterface $repo Repository to scan for plugins to install
  *
  * @throws \RuntimeException
  */
 private function loadRepository(RepositoryInterface $repo)
 {
     foreach ($repo->getPackages() as $package) {
         /** @var PackageInterface $package */
         if ($package instanceof AliasPackage) {
             continue;
         }
         if ('composer-plugin' === $package->getType()) {
             $this->registerPackage($package);
             // Backward compatibility
         } elseif ('composer-installer' === $package->getType()) {
             $this->registerPackage($package);
         }
     }
 }
Esempio n. 29
0
 protected function getPackage(RepositoryInterface $installedRepo, RepositoryInterface $repos, $name, $version = null)
 {
     $name = strtolower($name);
     $constraint = null;
     if ($version) {
         $constraint = $this->versionParser->parseConstraints($version);
     }
     $policy = new DefaultPolicy();
     $pool = new Pool('dev');
     $pool->addRepository($repos);
     $matchedPackage = null;
     $versions = array();
     $matches = $pool->whatProvides($name, $constraint);
     foreach ($matches as $index => $package) {
         // skip providers/replacers
         if ($package->getName() !== $name) {
             unset($matches[$index]);
             continue;
         }
         // select an exact match if it is in the installed repo and no specific version was required
         if (null === $version && $installedRepo->hasPackage($package)) {
             $matchedPackage = $package;
         }
         $versions[$package->getPrettyVersion()] = $package->getVersion();
         $matches[$index] = $package->getId();
     }
     // select prefered package according to policy rules
     if (!$matchedPackage && $matches && ($prefered = $policy->selectPreferedPackages($pool, array(), $matches))) {
         $matchedPackage = $pool->literalToPackage($prefered[0]);
     }
     return array($matchedPackage, $versions);
 }
Esempio n. 30
0
 /**
  * Adds a repository and its packages to this package pool
  *
  * @param RepositoryInterface $repo        A package repository
  * @param array               $rootAliases
  */
 public function addRepository(RepositoryInterface $repo, $rootAliases = array())
 {
     if ($repo instanceof CompositeRepository) {
         $repos = $repo->getRepositories();
     } else {
         $repos = array($repo);
     }
     foreach ($repos as $repo) {
         $this->repositories[] = $repo;
         $exempt = $repo instanceof PlatformRepository || $repo instanceof InstalledRepositoryInterface;
         if ($repo instanceof ComposerRepository && $repo->hasProviders()) {
             $this->providerRepos[] = $repo;
             $repo->setRootAliases($rootAliases);
             $repo->resetPackageIds();
         } elseif ($repo instanceof StreamableRepositoryInterface) {
             foreach ($repo->getMinimalPackages() as $package) {
                 $name = $package['name'];
                 $version = $package['version'];
                 $stability = VersionParser::parseStability($version);
                 // collect names
                 $names = array($name => true);
                 if (isset($package['provide'])) {
                     foreach ($package['provide'] as $target => $constraint) {
                         $names[$target] = true;
                     }
                 }
                 if (isset($package['replace'])) {
                     foreach ($package['replace'] as $target => $constraint) {
                         $names[$target] = true;
                     }
                 }
                 $names = array_keys($names);
                 if ($exempt || $this->isPackageAcceptable($names, $stability)) {
                     $package['id'] = $this->id++;
                     $this->packages[] = $package;
                     foreach ($names as $provided) {
                         $this->packageByName[$provided][$package['id']] = $this->packages[$this->id - 2];
                     }
                     // handle root package aliases
                     unset($rootAliasData);
                     if (isset($rootAliases[$name][$version])) {
                         $rootAliasData = $rootAliases[$name][$version];
                     } elseif (isset($package['alias_normalized']) && isset($rootAliases[$name][$package['alias_normalized']])) {
                         $rootAliasData = $rootAliases[$name][$package['alias_normalized']];
                     }
                     if (isset($rootAliasData)) {
                         $alias = $package;
                         unset($alias['raw']);
                         $alias['version'] = $rootAliasData['alias_normalized'];
                         $alias['alias'] = $rootAliasData['alias'];
                         $alias['alias_of'] = $package['id'];
                         $alias['id'] = $this->id++;
                         $alias['root_alias'] = true;
                         $this->packages[] = $alias;
                         foreach ($names as $provided) {
                             $this->packageByName[$provided][$alias['id']] = $this->packages[$this->id - 2];
                         }
                     }
                     // handle normal package aliases
                     if (isset($package['alias'])) {
                         $alias = $package;
                         unset($alias['raw']);
                         $alias['version'] = $package['alias_normalized'];
                         $alias['alias'] = $package['alias'];
                         $alias['alias_of'] = $package['id'];
                         $alias['id'] = $this->id++;
                         $this->packages[] = $alias;
                         foreach ($names as $provided) {
                             $this->packageByName[$provided][$alias['id']] = $this->packages[$this->id - 2];
                         }
                     }
                 }
             }
         } else {
             foreach ($repo->getPackages() as $package) {
                 $names = $package->getNames();
                 $stability = $package->getStability();
                 if ($exempt || $this->isPackageAcceptable($names, $stability)) {
                     $package->setId($this->id++);
                     $this->packages[] = $package;
                     foreach ($names as $provided) {
                         $this->packageByName[$provided][] = $package;
                     }
                     // handle root package aliases
                     $name = $package->getName();
                     if (isset($rootAliases[$name][$package->getVersion()])) {
                         $alias = $rootAliases[$name][$package->getVersion()];
                         if ($package instanceof AliasPackage) {
                             $package = $package->getAliasOf();
                         }
                         $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
                         $aliasPackage->setRootPackageAlias(true);
                         $aliasPackage->setId($this->id++);
                         $package->getRepository()->addPackage($aliasPackage);
                         $this->packages[] = $aliasPackage;
                         foreach ($aliasPackage->getNames() as $name) {
                             $this->packageByName[$name][] = $aliasPackage;
                         }
                     }
                 }
             }
         }
     }
 }