private function registerAutoloader($package)
 {
     $generator = new AutoloadGenerator(new EventDispatcher($this->composer, $this->io));
     $map = $generator->parseAutoloads(array(array($package, $this->getInstallPath($package))), new Package('dummy', '1.0.0.0', '1.0.0'));
     $classLoader = $generator->createLoader($map);
     $classLoader->register();
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('<info>Generating autoload files</info>');
     $composer = $this->getComposer();
     $installationManager = $composer->getInstallationManager();
     $localRepos = new CompositeRepository($composer->getRepositoryManager()->getLocalRepositories());
     $package = $composer->getPackage();
     $config = $composer->getConfig();
     $generator = new AutoloadGenerator();
     $generator->dump($config, $localRepos, $package, $installationManager, 'composer', $input->getOption('optimize'));
 }
Exemple #3
0
 /**
  * @param string $baseDir Root directory of composer package.
  */
 public function __construct($baseDir)
 {
     $this->baseDir = $baseDir;
     $io = new NullIO();
     $this->composer = (new Factory())->createComposer($io, $baseDir . '/composer.json', true, $baseDir, false);
     $generator = new AutoloadGenerator($this->composer->getEventDispatcher(), $io);
     $generator->setDevMode(true);
     $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getPackages();
     $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $this->composer->getPackage(), $packages);
     $packageMap[0][1] = $baseDir;
     // To make root package paths absolute too.
     $autoloads = $generator->parseAutoloads($packageMap, $this->composer->getPackage());
     $this->classLoader = $generator->createLoader($autoloads);
 }
 public function testExcludeFromClassmap()
 {
     $package = new Package('a', '1.0', '1.0');
     $package->setAutoload(array('psr-0' => array('Main' => 'src/', 'Lala' => array('src/', 'lib/')), 'psr-4' => array('Acme\\Fruit\\' => 'src-fruit/', 'Acme\\Cake\\' => array('src-cake/', 'lib-cake/')), 'classmap' => array('composersrc/'), 'exclude-from-classmap' => array('/composersrc/excludedTests/', '/composersrc/ClassToExclude.php', '/composersrc/*/excluded/excsubpath', '**/excsubpath')));
     $this->repository->expects($this->once())->method('getCanonicalPackages')->will($this->returnValue(array()));
     $this->fs->ensureDirectoryExists($this->workingDir . '/composer');
     $this->fs->ensureDirectoryExists($this->workingDir . '/src/Lala/Test');
     $this->fs->ensureDirectoryExists($this->workingDir . '/lib');
     file_put_contents($this->workingDir . '/src/Lala/ClassMapMain.php', '<?php namespace Lala; class ClassMapMain {}');
     file_put_contents($this->workingDir . '/src/Lala/Test/ClassMapMainTest.php', '<?php namespace Lala\\Test; class ClassMapMainTest {}');
     $this->fs->ensureDirectoryExists($this->workingDir . '/src-fruit');
     $this->fs->ensureDirectoryExists($this->workingDir . '/src-cake');
     $this->fs->ensureDirectoryExists($this->workingDir . '/lib-cake');
     file_put_contents($this->workingDir . '/src-cake/ClassMapBar.php', '<?php namespace Acme\\Cake; class ClassMapBar {}');
     $this->fs->ensureDirectoryExists($this->workingDir . '/composersrc');
     $this->fs->ensureDirectoryExists($this->workingDir . '/composersrc/tests');
     file_put_contents($this->workingDir . '/composersrc/foo.php', '<?php class ClassMapFoo {}');
     // this classes should not be found in the classmap
     $this->fs->ensureDirectoryExists($this->workingDir . '/composersrc/excludedTests');
     file_put_contents($this->workingDir . '/composersrc/excludedTests/bar.php', '<?php class ClassExcludeMapFoo {}');
     file_put_contents($this->workingDir . '/composersrc/ClassToExclude.php', '<?php class ClassClassToExclude {}');
     $this->fs->ensureDirectoryExists($this->workingDir . '/composersrc/long/excluded/excsubpath');
     file_put_contents($this->workingDir . '/composersrc/long/excluded/excsubpath/foo.php', '<?php class ClassExcludeMapFoo2 {}');
     file_put_contents($this->workingDir . '/composersrc/long/excluded/excsubpath/bar.php', '<?php class ClassExcludeMapBar {}');
     $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_1');
     // Assert that autoload_classmap.php was correctly generated.
     $this->assertAutoloadFiles('classmap', $this->vendorDir . '/composer', 'classmap');
 }
Exemple #5
0
 /**
  * Run installation (or update)
  */
 public function run()
 {
     if ($this->dryRun) {
         $this->verbose = true;
         $this->runScripts = false;
         $this->installationManager->addInstaller(new NoopInstaller());
     }
     if ($this->preferSource) {
         $this->downloadManager->setPreferSource(true);
     }
     // create installed repo, this contains all local packages + platform packages (php & extensions)
     $installedRootPackage = clone $this->package;
     $installedRootPackage->setRequires(array());
     $installedRootPackage->setDevRequires(array());
     $repos = array_merge($this->repositoryManager->getLocalRepositories(), array(new InstalledArrayRepository(array($installedRootPackage)), new PlatformRepository()));
     $installedRepo = new CompositeRepository($repos);
     if ($this->additionalInstalledRepository) {
         $installedRepo->addRepository($this->additionalInstalledRepository);
     }
     $aliases = $this->aliasPackages();
     if ($this->runScripts) {
         // dispatch pre event
         $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
         $this->eventDispatcher->dispatchCommandEvent($eventName);
     }
     $this->suggestedPackages = array();
     if (!$this->doInstall($this->repositoryManager->getLocalRepository(), $installedRepo, $aliases)) {
         return false;
     }
     if ($this->devMode) {
         if (!$this->doInstall($this->repositoryManager->getLocalDevRepository(), $installedRepo, $aliases, true)) {
             return false;
         }
     }
     // output suggestions
     foreach ($this->suggestedPackages as $suggestion) {
         if (!$installedRepo->findPackages($suggestion['target'])) {
             $this->io->write($suggestion['source'] . ' suggests installing ' . $suggestion['target'] . ' (' . $suggestion['reason'] . ')');
         }
     }
     if (!$this->dryRun) {
         // write lock
         if ($this->update || !$this->locker->isLocked()) {
             $updatedLock = $this->locker->setLockData($this->repositoryManager->getLocalRepository()->getPackages(), $this->devMode ? $this->repositoryManager->getLocalDevRepository()->getPackages() : null, $aliases, $this->package->getMinimumStability(), $this->package->getStabilityFlags());
             if ($updatedLock) {
                 $this->io->write('<info>Writing lock file</info>');
             }
         }
         // write autoloader
         $this->io->write('<info>Generating autoload files</info>');
         $localRepos = new CompositeRepository($this->repositoryManager->getLocalRepositories());
         $this->autoloadGenerator->dump($localRepos, $this->package, $this->installationManager, $this->installationManager->getVendorPath() . '/composer', true);
         if ($this->runScripts) {
             // dispatch post event
             $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
             $this->eventDispatcher->dispatchCommandEvent($eventName);
         }
     }
     return true;
 }
 public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
 {
     $packageMap = parent::buildPackageMap($installationManager, $mainPackage, $packages);
     $packageMap[0][1] = $mainPackage->getName();
     // hack the install path
     return $packageMap;
 }
 /**
  * @param \Composer\Package\PackageInterface $package
  * @param \Composer\Composer $composer
  */
 public function __construct(PackageInterface $package, Composer $composer)
 {
     parent::__construct($composer->getEventDispatcher());
     $this->_composer = $composer;
     $this->_autoloader = AssetsAutoloadGenerator::getInstance();
     $this->_autoloader->setGenerator(array($this, 'generate'));
     $this->_package = $package;
 }
 private function registerInstaller(PackageInterface $package)
 {
     $downloadPath = $this->getInstallPath($package);
     $extra = $package->getExtra();
     $class = $extra['class'];
     $generator = new AutoloadGenerator();
     $map = $generator->parseAutoloads(array(array($package, $downloadPath)));
     $classLoader = $generator->createLoader($map);
     $classLoader->register();
     if (class_exists($class, false)) {
         $code = file_get_contents($classLoader->findFile($class));
         $code = preg_replace('{^class\\s+(\\S+)}mi', 'class $1_composer_tmp' . self::$classCounter, $code);
         eval('?>' . $code);
         $class .= '_composer_tmp' . self::$classCounter;
         self::$classCounter++;
     }
     $extra = $package->getExtra();
     $installer = new $class($this->vendorDir, $this->binDir, $this->downloadManager, $this->io);
     $this->installationManager->addInstaller($installer);
 }
 /**
  * Set hoa\core require in last position.
  *
  * @param array $packageMap packageMap
  */
 protected function sortPackageMap(array $packageMap)
 {
     $packageMap = parent::sortPackageMap($packageMap);
     foreach ($packageMap as $k => $item) {
         if ($item[0]->getName() === 'hoa/core') {
             unset($packageMap[$k]);
             $packageMap[] = $item;
             break;
         }
     }
     return $packageMap;
 }
Exemple #10
0
    protected function getAutoloadRealFile($useClassMap, $useIncludePath, $targetDirLoader, $useIncludeFiles, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $classMapAuthoritative)
    {
        $file = parent::getAutoloadRealFile($useClassMap, $useIncludePath, $targetDirLoader, false, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $classMapAuthoritative);
        if (!$useIncludeFiles) {
            return $file;
        }
        return $file .= <<<INCLUDE_FILES

\$includeFiles = require __DIR__ . '/autoload_files.php';
foreach (\$includeFiles as \$file) {
    composerRequireOnce{$suffix}(\$file);
}

function composerRequireOnce{$suffix}(\$file)
{
    require_once \$file;
}

INCLUDE_FILES;
    }
    public function testVendorSubstringPath()
    {
        $package = new Package('a', '1.0', '1.0');
        $package->setAutoload(array('psr-0' => array('Foo' => 'composer-test-autoload-src/src'), 'psr-4' => array('Acme\\Foo\\' => 'composer-test-autoload-src/src-psr4')));
        $this->repository->expects($this->once())->method('getCanonicalPackages')->will($this->returnValue(array()));
        $this->fs->ensureDirectoryExists($this->vendorDir . '/a');
        $expectedNamespace = <<<'EOF'
<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Foo' => array($baseDir . '/composer-test-autoload-src/src'),
);

EOF;
        $expectedPsr4 = <<<'EOF'
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Acme\\Foo\\' => array($baseDir . '/composer-test-autoload-src/src-psr4'),
);

EOF;
        $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, 'VendorSubstring');
        $this->assertEquals($expectedNamespace, file_get_contents($this->vendorDir . '/composer/autoload_namespaces.php'));
        $this->assertEquals($expectedPsr4, file_get_contents($this->vendorDir . '/composer/autoload_psr4.php'));
    }
Exemple #12
0
 /**
  * Run installation (or update)
  *
  * @return int 0 on success or a positive error code on failure
  *
  * @throws \Exception
  */
 public function run()
 {
     gc_collect_cycles();
     gc_disable();
     if ($this->dryRun) {
         $this->verbose = true;
         $this->runScripts = false;
         $this->installationManager->addInstaller(new NoopInstaller());
         $this->mockLocalRepositories($this->repositoryManager);
     }
     // TODO remove this BC feature at some point
     // purge old require-dev packages to avoid conflicts with the new way of handling dev requirements
     $devRepo = new InstalledFilesystemRepository(new JsonFile($this->config->get('vendor-dir') . '/composer/installed_dev.json'));
     if ($devRepo->getPackages()) {
         $this->io->writeError('<warning>BC Notice: Removing old dev packages to migrate to the new require-dev handling.</warning>');
         foreach ($devRepo->getPackages() as $package) {
             if ($this->installationManager->isPackageInstalled($devRepo, $package)) {
                 $this->installationManager->uninstall($devRepo, new UninstallOperation($package));
             }
         }
         unlink($this->config->get('vendor-dir') . '/composer/installed_dev.json');
     }
     unset($devRepo, $package);
     // end BC
     if ($this->runScripts) {
         // dispatch pre event
         $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
         $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
     }
     $this->downloadManager->setPreferSource($this->preferSource);
     $this->downloadManager->setPreferDist($this->preferDist);
     // clone root package to have one in the installed repo that does not require anything
     // we don't want it to be uninstallable, but its requirements should not conflict
     // with the lock file for example
     $installedRootPackage = clone $this->package;
     $installedRootPackage->setRequires(array());
     $installedRootPackage->setDevRequires(array());
     // create installed repo, this contains all local packages + platform packages (php & extensions)
     $localRepo = $this->repositoryManager->getLocalRepository();
     $platformRepo = new PlatformRepository();
     $repos = array($localRepo, new InstalledArrayRepository(array($installedRootPackage)), $platformRepo);
     $installedRepo = new CompositeRepository($repos);
     if ($this->additionalInstalledRepository) {
         $installedRepo->addRepository($this->additionalInstalledRepository);
     }
     $aliases = $this->getRootAliases();
     $this->aliasPlatformPackages($platformRepo, $aliases);
     try {
         $this->suggestedPackages = array();
         $res = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode);
         if ($res !== 0) {
             return $res;
         }
     } catch (\Exception $e) {
         $this->installationManager->notifyInstalls();
         throw $e;
     }
     $this->installationManager->notifyInstalls();
     // output suggestions if we're in dev mode
     if ($this->devMode) {
         foreach ($this->suggestedPackages as $suggestion) {
             $target = $suggestion['target'];
             foreach ($installedRepo->getPackages() as $package) {
                 if (in_array($target, $package->getNames())) {
                     continue 2;
                 }
             }
             $this->io->writeError($suggestion['source'] . ' suggests installing ' . $suggestion['target'] . ' (' . $suggestion['reason'] . ')');
         }
     }
     # Find abandoned packages and warn user
     foreach ($localRepo->getPackages() as $package) {
         if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
             continue;
         }
         $replacement = is_string($package->getReplacementPackage()) ? 'Use ' . $package->getReplacementPackage() . ' instead' : 'No replacement was suggested';
         $this->io->writeError(sprintf("<error>Package %s is abandoned, you should avoid using it. %s.</error>", $package->getPrettyName(), $replacement));
     }
     if (!$this->dryRun) {
         // write lock
         if ($this->update || !$this->locker->isLocked()) {
             $localRepo->reload();
             // if this is not run in dev mode and the root has dev requires, the lock must
             // contain null to prevent dev installs from a non-dev lock
             $devPackages = $this->devMode || !$this->package->getDevRequires() ? array() : null;
             // split dev and non-dev requirements by checking what would be removed if we update without the dev requirements
             if ($this->devMode && $this->package->getDevRequires()) {
                 $policy = $this->createPolicy();
                 $pool = $this->createPool(true);
                 $pool->addRepository($installedRepo, $aliases);
                 // creating requirements request
                 $request = $this->createRequest($pool, $this->package, $platformRepo);
                 $request->updateAll();
                 foreach ($this->package->getRequires() as $link) {
                     $request->install($link->getTarget(), $link->getConstraint());
                 }
                 $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request);
                 $solver = new Solver($policy, $pool, $installedRepo);
                 $ops = $solver->solve($request, $this->ignorePlatformReqs);
                 $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request, $ops);
                 foreach ($ops as $op) {
                     if ($op->getJobType() === 'uninstall') {
                         $devPackages[] = $op->getPackage();
                     }
                 }
             }
             $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
             $platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();
             $updatedLock = $this->locker->setLockData(array_diff($localRepo->getCanonicalPackages(), (array) $devPackages), $devPackages, $platformReqs, $platformDevReqs, $aliases, $this->package->getMinimumStability(), $this->package->getStabilityFlags(), $this->preferStable || $this->package->getPreferStable(), $this->preferLowest);
             if ($updatedLock) {
                 $this->io->writeError('<info>Writing lock file</info>');
             }
         }
         if ($this->dumpAutoloader) {
             // write autoloader
             if ($this->optimizeAutoloader) {
                 $this->io->writeError('<info>Generating optimized autoload files</info>');
             } else {
                 $this->io->writeError('<info>Generating autoload files</info>');
             }
             $this->autoloadGenerator->setDevMode($this->devMode);
             $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
         }
         if ($this->runScripts) {
             // dispatch post event
             $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
             $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
         }
         $vendorDir = $this->config->get('vendor-dir');
         if (is_dir($vendorDir)) {
             touch($vendorDir);
         }
     }
     return 0;
 }
Exemple #13
0
 /**
  * @param Event $event Event object
  * @return array Listeners
  */
 protected function getListeners(Event $event)
 {
     $package = $this->composer->getPackage();
     $scripts = $package->getScripts();
     if (empty($scripts[$event->getName()])) {
         return array();
     }
     if ($this->loader) {
         $this->loader->unregister();
     }
     $generator = new AutoloadGenerator();
     $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getPackages();
     $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages);
     $map = $generator->parseAutoloads($packageMap);
     $this->loader = $generator->createLoader($map);
     $this->loader->register();
     return $scripts[$event->getName()];
 }
Exemple #14
0
 /**
  * Run installation (or update)
  */
 public function run()
 {
     if ($this->dryRun) {
         $this->verbose = true;
         $this->runScripts = false;
         $this->installationManager->addInstaller(new NoopInstaller());
         $this->mockLocalRepositories($this->repositoryManager);
     }
     // TODO remove this BC feature at some point
     // purge old require-dev packages to avoid conflicts with the new way of handling dev requirements
     $devRepo = new InstalledFilesystemRepository(new JsonFile($this->config->get('vendor-dir') . '/composer/installed_dev.json'));
     if ($devRepo->getPackages()) {
         $this->io->write('<warning>BC Notice: Removing old dev packages to migrate to the new require-dev handling.</warning>');
         foreach ($devRepo->getPackages() as $package) {
             if ($this->installationManager->isPackageInstalled($devRepo, $package)) {
                 $this->installationManager->uninstall($devRepo, new UninstallOperation($package));
             }
         }
         unlink($this->config->get('vendor-dir') . '/composer/installed_dev.json');
     }
     unset($devRepo, $package);
     // end BC
     if ($this->preferSource) {
         $this->downloadManager->setPreferSource(true);
     }
     if ($this->preferDist) {
         $this->downloadManager->setPreferDist(true);
     }
     // create installed repo, this contains all local packages + platform packages (php & extensions)
     $installedRootPackage = clone $this->package;
     $installedRootPackage->setRequires(array());
     $installedRootPackage->setDevRequires(array());
     $localRepo = $this->repositoryManager->getLocalRepository();
     $platformRepo = new PlatformRepository();
     $repos = array($localRepo, new InstalledArrayRepository(array($installedRootPackage)), $platformRepo);
     $installedRepo = new CompositeRepository($repos);
     if ($this->additionalInstalledRepository) {
         $installedRepo->addRepository($this->additionalInstalledRepository);
     }
     $aliases = $this->getRootAliases();
     $this->aliasPlatformPackages($platformRepo, $aliases);
     if ($this->runScripts) {
         // dispatch pre event
         $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
         $this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
     }
     try {
         $this->suggestedPackages = array();
         if (!$this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode)) {
             return false;
         }
     } catch (\Exception $e) {
         $this->installationManager->notifyInstalls();
         throw $e;
     }
     $this->installationManager->notifyInstalls();
     // output suggestions
     foreach ($this->suggestedPackages as $suggestion) {
         $target = $suggestion['target'];
         foreach ($installedRepo->getPackages() as $package) {
             if (in_array($target, $package->getNames())) {
                 continue 2;
             }
         }
         $this->io->write($suggestion['source'] . ' suggests installing ' . $suggestion['target'] . ' (' . $suggestion['reason'] . ')');
     }
     if (!$this->dryRun) {
         // write lock
         if ($this->update || !$this->locker->isLocked()) {
             $localRepo->reload();
             // if this is not run in dev mode and the root has dev requires, the lock must
             // contain null to prevent dev installs from a non-dev lock
             $devPackages = $this->devMode || !$this->package->getDevRequires() ? array() : null;
             // split dev and non-dev requirements by checking what would be removed if we update without the dev requirements
             if ($this->devMode && $this->package->getDevRequires()) {
                 $policy = $this->createPolicy();
                 $pool = $this->createPool();
                 $pool->addRepository($installedRepo, $aliases);
                 // creating requirements request
                 $request = $this->createRequest($pool, $this->package, $platformRepo);
                 $request->updateAll();
                 foreach ($this->package->getRequires() as $link) {
                     $request->install($link->getTarget(), $link->getConstraint());
                 }
                 $solver = new Solver($policy, $pool, $installedRepo);
                 $ops = $solver->solve($request);
                 foreach ($ops as $op) {
                     if ($op->getJobType() === 'uninstall') {
                         $devPackages[] = $op->getPackage();
                     }
                 }
             }
             $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
             $platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();
             $updatedLock = $this->locker->setLockData(array_diff($localRepo->getPackages(), (array) $devPackages), $devPackages, $platformReqs, $platformDevReqs, $aliases, $this->package->getMinimumStability(), $this->package->getStabilityFlags());
             if ($updatedLock) {
                 $this->io->write('<info>Writing lock file</info>');
             }
         }
         // write autoloader
         $this->io->write('<info>Generating autoload files</info>');
         $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
         if ($this->runScripts) {
             // dispatch post event
             $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
             $this->eventDispatcher->dispatchCommandEvent($eventName, $this->devMode);
         }
     }
     return true;
 }
Exemple #15
0
 /**
  * Run installation (or update)
  *
  * @throws \Exception
  * @return int        0 on success or a positive error code on failure
  */
 public function run()
 {
     // Disable GC to save CPU cycles, as the dependency solver can create hundreds of thousands
     // of PHP objects, the GC can spend quite some time walking the tree of references looking
     // for stuff to collect while there is nothing to collect. This slows things down dramatically
     // and turning it off results in much better performance. Do not try this at home however.
     gc_collect_cycles();
     gc_disable();
     // Force update if there is no lock file present
     if (!$this->update && !$this->locker->isLocked()) {
         $this->update = true;
     }
     if ($this->dryRun) {
         $this->verbose = true;
         $this->runScripts = false;
         $this->installationManager->addInstaller(new NoopInstaller());
         $this->mockLocalRepositories($this->repositoryManager);
     }
     if ($this->runScripts) {
         // dispatch pre event
         $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
         $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
     }
     $this->downloadManager->setPreferSource($this->preferSource);
     $this->downloadManager->setPreferDist($this->preferDist);
     // create installed repo, this contains all local packages + platform packages (php & extensions)
     $localRepo = $this->repositoryManager->getLocalRepository();
     if ($this->update) {
         $platformOverrides = $this->config->get('platform') ?: array();
     } else {
         $platformOverrides = $this->locker->getPlatformOverrides();
     }
     $platformRepo = new PlatformRepository(array(), $platformOverrides);
     $installedRepo = $this->createInstalledRepo($localRepo, $platformRepo);
     $aliases = $this->getRootAliases();
     $this->aliasPlatformPackages($platformRepo, $aliases);
     if (!$this->suggestedPackagesReporter) {
         $this->suggestedPackagesReporter = new SuggestedPackagesReporter($this->io);
     }
     try {
         list($res, $devPackages) = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases);
         if ($res !== 0) {
             return $res;
         }
     } catch (\Exception $e) {
         if (!$this->dryRun) {
             $this->installationManager->notifyInstalls($this->io);
         }
         throw $e;
     }
     if (!$this->dryRun) {
         $this->installationManager->notifyInstalls($this->io);
     }
     // output suggestions if we're in dev mode
     if ($this->devMode && !$this->skipSuggest) {
         $this->suggestedPackagesReporter->output($installedRepo);
     }
     # Find abandoned packages and warn user
     foreach ($localRepo->getPackages() as $package) {
         if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
             continue;
         }
         $replacement = is_string($package->getReplacementPackage()) ? 'Use ' . $package->getReplacementPackage() . ' instead' : 'No replacement was suggested';
         $this->io->writeError(sprintf("<warning>Package %s is abandoned, you should avoid using it. %s.</warning>", $package->getPrettyName(), $replacement));
     }
     if (!$this->dryRun) {
         // write lock
         if ($this->update) {
             $localRepo->reload();
             $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
             $platformDevReqs = $this->extractPlatformRequirements($this->package->getDevRequires());
             $updatedLock = $this->locker->setLockData(array_diff($localRepo->getCanonicalPackages(), $devPackages), $devPackages, $platformReqs, $platformDevReqs, $aliases, $this->package->getMinimumStability(), $this->package->getStabilityFlags(), $this->preferStable || $this->package->getPreferStable(), $this->preferLowest, $this->config->get('platform') ?: array());
             if ($updatedLock) {
                 $this->io->writeError('<info>Writing lock file</info>');
             }
         }
         if ($this->dumpAutoloader) {
             // write autoloader
             if ($this->optimizeAutoloader) {
                 $this->io->writeError('<info>Generating optimized autoload files</info>');
             } else {
                 $this->io->writeError('<info>Generating autoload files</info>');
             }
             $this->autoloadGenerator->setDevMode($this->devMode);
             $this->autoloadGenerator->setClassMapAuthoritative($this->classMapAuthoritative);
             $this->autoloadGenerator->setRunScripts($this->runScripts);
             $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
         }
         if ($this->runScripts) {
             $devMode = (int) $this->devMode;
             putenv("COMPOSER_DEV_MODE={$devMode}");
             // dispatch post event
             $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
             $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
         }
         // force binaries re-generation in case they are missing
         foreach ($localRepo->getPackages() as $package) {
             $this->installationManager->ensureBinariesPresence($package);
         }
         $vendorDir = $this->config->get('vendor-dir');
         if (is_dir($vendorDir)) {
             // suppress errors as this fails sometimes on OSX for no apparent reason
             // see https://github.com/composer/composer/issues/4070#issuecomment-129792748
             @touch($vendorDir);
         }
     }
     // re-enable GC except on HHVM which triggers a warning here
     if (!defined('HHVM_VERSION')) {
         gc_enable();
     }
     return 0;
 }
 /**
  * Run installation (or update)
  *
  * @throws \Exception
  * @return int        0 on success or a positive error code on failure
  */
 public function run()
 {
     // Disable GC to save CPU cycles, as the dependency solver can create hundreds of thousands
     // of PHP objects, the GC can spend quite some time walking the tree of references looking
     // for stuff to collect while there is nothing to collect. This slows things down dramatically
     // and turning it off results in much better performance. Do not try this at home however.
     gc_collect_cycles();
     gc_disable();
     if ($this->dryRun) {
         $this->verbose = true;
         $this->runScripts = false;
         $this->installationManager->addInstaller(new NoopInstaller());
         $this->mockLocalRepositories($this->repositoryManager);
     }
     if ($this->runScripts) {
         // dispatch pre event
         $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
         $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
     }
     $this->downloadManager->setPreferSource($this->preferSource);
     $this->downloadManager->setPreferDist($this->preferDist);
     // clone root package to have one in the installed repo that does not require anything
     // we don't want it to be uninstallable, but its requirements should not conflict
     // with the lock file for example
     $installedRootPackage = clone $this->package;
     $installedRootPackage->setRequires(array());
     $installedRootPackage->setDevRequires(array());
     // create installed repo, this contains all local packages + platform packages (php & extensions)
     $localRepo = $this->repositoryManager->getLocalRepository();
     if (!$this->update && $this->locker->isLocked()) {
         $platformOverrides = $this->locker->getPlatformOverrides();
     } else {
         $platformOverrides = $this->config->get('platform') ?: array();
     }
     $platformRepo = new PlatformRepository(array(), $platformOverrides);
     $repos = array($localRepo, new InstalledArrayRepository(array($installedRootPackage)), $platformRepo);
     $installedRepo = new CompositeRepository($repos);
     if ($this->additionalInstalledRepository) {
         $installedRepo->addRepository($this->additionalInstalledRepository);
     }
     $aliases = $this->getRootAliases();
     $this->aliasPlatformPackages($platformRepo, $aliases);
     try {
         $this->suggestedPackages = array();
         $res = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode);
         if ($res !== 0) {
             return $res;
         }
     } catch (\Exception $e) {
         if (!$this->dryRun) {
             $this->installationManager->notifyInstalls($this->io);
         }
         throw $e;
     }
     if (!$this->dryRun) {
         $this->installationManager->notifyInstalls($this->io);
     }
     // output suggestions if we're in dev mode
     if ($this->devMode) {
         foreach ($this->suggestedPackages as $suggestion) {
             $target = $suggestion['target'];
             foreach ($installedRepo->getPackages() as $package) {
                 if (in_array($target, $package->getNames())) {
                     continue 2;
                 }
             }
             $this->io->writeError($suggestion['source'] . ' suggests installing ' . $suggestion['target'] . ' (' . $suggestion['reason'] . ')');
         }
     }
     # Find abandoned packages and warn user
     foreach ($localRepo->getPackages() as $package) {
         if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
             continue;
         }
         $replacement = is_string($package->getReplacementPackage()) ? 'Use ' . $package->getReplacementPackage() . ' instead' : 'No replacement was suggested';
         $this->io->writeError(sprintf("<warning>Package %s is abandoned, you should avoid using it. %s.</warning>", $package->getPrettyName(), $replacement));
     }
     if (!$this->dryRun) {
         // write lock
         if ($this->update || !$this->locker->isLocked()) {
             $localRepo->reload();
             // if this is not run in dev mode and the root has dev requires, the lock must
             // contain null to prevent dev installs from a non-dev lock
             $devPackages = $this->devMode || !$this->package->getDevRequires() ? array() : null;
             // split dev and non-dev requirements by checking what would be removed if we update without the dev requirements
             if ($this->devMode && $this->package->getDevRequires()) {
                 $policy = $this->createPolicy();
                 $pool = $this->createPool(true);
                 $pool->addRepository($installedRepo, $aliases);
                 // creating requirements request
                 $request = $this->createRequest($this->package, $platformRepo);
                 $request->updateAll();
                 foreach ($this->package->getRequires() as $link) {
                     $request->install($link->getTarget(), $link->getConstraint());
                 }
                 $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request);
                 $solver = new Solver($policy, $pool, $installedRepo);
                 $ops = $solver->solve($request, $this->ignorePlatformReqs);
                 $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request, $ops);
                 foreach ($ops as $op) {
                     if ($op->getJobType() === 'uninstall') {
                         $devPackages[] = $op->getPackage();
                     }
                 }
             }
             $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
             $platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();
             $updatedLock = $this->locker->setLockData(array_diff($localRepo->getCanonicalPackages(), (array) $devPackages), $devPackages, $platformReqs, $platformDevReqs, $aliases, $this->package->getMinimumStability(), $this->package->getStabilityFlags(), $this->preferStable || $this->package->getPreferStable(), $this->preferLowest, $this->config->get('platform') ?: array());
             if ($updatedLock) {
                 $this->io->writeError('<info>Writing lock file</info>');
             }
         }
         if ($this->dumpAutoloader) {
             // write autoloader
             if ($this->optimizeAutoloader) {
                 $this->io->writeError('<info>Generating optimized autoload files</info>');
             } else {
                 $this->io->writeError('<info>Generating autoload files</info>');
             }
             $this->autoloadGenerator->setDevMode($this->devMode);
             $this->autoloadGenerator->setClassMapAuthoritative($this->classMapAuthoritative);
             $this->autoloadGenerator->setRunScripts($this->runScripts);
             $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
         }
         if ($this->runScripts) {
             // dispatch post event
             $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
             $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
         }
         $vendorDir = $this->config->get('vendor-dir');
         if (is_dir($vendorDir)) {
             // suppress errors as this fails sometimes on OSX for no apparent reason
             // see https://github.com/composer/composer/issues/4070#issuecomment-129792748
             @touch($vendorDir);
         }
     }
     // re-enable GC except on HHVM which triggers a warning here
     if (!defined('HHVM_VERSION')) {
         gc_enable();
     }
     return 0;
 }
Exemple #17
0
 /**
  * @throws \Jarves\Exceptions\FileNotWritableException
  */
 protected function updateAutoloader()
 {
     if (!is_writeable($composerDir = $this->getComposerVendorDir() . 'composer/')) {
         throw new FileNotWritableException(sprintf('Directory `%s` is not writable.', $composerDir));
     }
     if (!is_writeable($autoload = $this->getComposerVendorDir() . 'autoload.php')) {
         throw new FileNotWritableException(sprintf('File `%s` is not writable.', $autoload));
     }
     $composer = $this->getComposer();
     $eventDispatcher = new EventDispatcher($composer, $this->composerIO);
     $autoloadGenerator = new AutoloadGenerator($eventDispatcher);
     $localRepo = $composer->getRepositoryManager()->getLocalRepository();
     $autoloadGenerator->dump($composer->getConfig(), $localRepo, $composer->getPackage(), $composer->getInstallationManager(), 'composer', true);
 }
 public static function sort_package_map(AutoloadGenerator $generator, $packageMap)
 {
     return $generator->sortPackageMap($packageMap);
 }
Exemple #19
0
 public function install(IOInterface $io, Composer $composer, EventDispatcher $eventDispatcher, $preferSource = false, $dryRun = false, $verbose = false, $noInstallRecommends = false, $installSuggests = false, $update = false, RepositoryInterface $additionalInstalledRepository = null)
 {
     if ($dryRun) {
         $verbose = true;
     }
     if ($preferSource) {
         $composer->getDownloadManager()->setPreferSource(true);
     }
     // create local repo, this contains all packages that are installed in the local project
     $localRepo = $composer->getRepositoryManager()->getLocalRepository();
     // create installed repo, this contains all local packages + platform packages (php & extensions)
     $installedRepo = new CompositeRepository(array($localRepo, new PlatformRepository()));
     if ($additionalInstalledRepository) {
         $installedRepo->addRepository($additionalInstalledRepository);
     }
     // creating repository pool
     $pool = new Pool();
     $pool->addRepository($installedRepo);
     foreach ($composer->getRepositoryManager()->getRepositories() as $repository) {
         $pool->addRepository($repository);
     }
     // dispatch pre event
     if (!$dryRun) {
         $eventName = $update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
         $eventDispatcher->dispatchCommandEvent($eventName);
     }
     // creating requirements request
     $installFromLock = false;
     $request = new Request($pool);
     if ($update) {
         $io->write('<info>Updating dependencies</info>');
         $installedPackages = $installedRepo->getPackages();
         $links = $this->collectLinks($composer->getPackage(), $noInstallRecommends, $installSuggests);
         $request->updateAll();
         foreach ($links as $link) {
             $request->install($link->getTarget(), $link->getConstraint());
         }
     } elseif ($composer->getLocker()->isLocked()) {
         $installFromLock = true;
         $io->write('<info>Installing from lock file</info>');
         if (!$composer->getLocker()->isFresh()) {
             $io->write('<warning>Your lock file is out of sync with your composer.json, run "composer.phar update" to update dependencies</warning>');
         }
         foreach ($composer->getLocker()->getLockedPackages() as $package) {
             $constraint = new VersionConstraint('=', $package->getVersion());
             $request->install($package->getName(), $constraint);
         }
     } else {
         $io->write('<info>Installing dependencies</info>');
         $links = $this->collectLinks($composer->getPackage(), $noInstallRecommends, $installSuggests);
         foreach ($links as $link) {
             $request->install($link->getTarget(), $link->getConstraint());
         }
     }
     // prepare solver
     $installationManager = $composer->getInstallationManager();
     $policy = new DependencyResolver\DefaultPolicy();
     $solver = new DependencyResolver\Solver($policy, $pool, $installedRepo);
     // solve dependencies
     $operations = $solver->solve($request);
     // execute operations
     if (!$operations) {
         $io->write('<info>Nothing to install/update</info>');
     }
     // force dev packages to be updated to latest reference on update
     if ($update) {
         foreach ($localRepo->getPackages() as $package) {
             // skip non-dev packages
             if (!$package->isDev()) {
                 continue;
             }
             // skip packages that will be updated/uninstalled
             foreach ($operations as $operation) {
                 if ('update' === $operation->getJobType() && $package === $operation->getInitialPackage() || 'uninstall' === $operation->getJobType() && $package === $operation->getPackage()) {
                     continue 2;
                 }
             }
             // force update
             $newPackage = $composer->getRepositoryManager()->findPackage($package->getName(), $package->getVersion());
             if ($newPackage && $newPackage->getSourceReference() !== $package->getSourceReference()) {
                 $operations[] = new UpdateOperation($package, $newPackage);
             }
         }
     }
     foreach ($operations as $operation) {
         if ($verbose) {
             $io->write((string) $operation);
         }
         if (!$dryRun) {
             $eventDispatcher->dispatchPackageEvent(constant('Composer\\Script\\ScriptEvents::PRE_PACKAGE_' . strtoupper($operation->getJobType())), $operation);
             // if installing from lock, restore dev packages' references to their locked state
             if ($installFromLock) {
                 $package = null;
                 if ('update' === $operation->getJobType()) {
                     $package = $operation->getTargetPackage();
                 } elseif ('install' === $operation->getJobType()) {
                     $package = $operation->getPackage();
                 }
                 if ($package && $package->isDev()) {
                     $lockData = $composer->getLocker()->getLockData();
                     foreach ($lockData['packages'] as $lockedPackage) {
                         if (!empty($lockedPackage['source-reference']) && strtolower($lockedPackage['package']) === $package->getName()) {
                             $package->setSourceReference($lockedPackage['source-reference']);
                             break;
                         }
                     }
                 }
             }
             $installationManager->execute($operation);
             $eventDispatcher->dispatchPackageEvent(constant('Composer\\Script\\ScriptEvents::POST_PACKAGE_' . strtoupper($operation->getJobType())), $operation);
         }
     }
     if (!$dryRun) {
         if ($update || !$composer->getLocker()->isLocked()) {
             $composer->getLocker()->lockPackages($localRepo->getPackages());
             $io->write('<info>Writing lock file</info>');
         }
         $localRepo->write();
         $io->write('<info>Generating autoload files</info>');
         $generator = new AutoloadGenerator();
         $generator->dump($localRepo, $composer->getPackage(), $installationManager, $installationManager->getVendorPath() . '/.composer');
         // dispatch post event
         $eventName = $update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
         $eventDispatcher->dispatchCommandEvent($eventName);
     }
 }