/**
  * Dispatches the vcs repositories event.
  *
  * @param array $vcsRepos
  */
 protected function dispatchAddVcsEvent(array $vcsRepos)
 {
     if (null !== $this->dispatcher) {
         $event = new VcsRepositoryEvent(AssetEvents::ADD_VCS_REPOSITORIES, $vcsRepos);
         $this->dispatcher->dispatch($event->getName(), $event);
     }
 }
Ejemplo n.º 2
0
 /**
  * @dataProvider getDevModes
  * @param bool $devMode
  */
 public function testDispatcherPassDevModeToAutoloadGeneratorForScriptEvents($devMode)
 {
     $composer = $this->createComposerInstance();
     $generator = $this->getGeneratorMockForDevModePassingTest();
     $generator->expects($this->atLeastOnce())->method('setDevMode')->with($devMode);
     $composer->setAutoloadGenerator($generator);
     $package = $this->getMock('Composer\\Package\\RootPackageInterface');
     $package->method('getScripts')->will($this->returnValue(array('scriptName' => array('scriptName'))));
     $composer->setPackage($package);
     $composer->setRepositoryManager($this->getRepositoryManagerMockForDevModePassingTest());
     $composer->setInstallationManager($this->getMock('Composer\\Installer\\InstallationManager'));
     $dispatcher = new EventDispatcher($composer, $this->getMock('Composer\\IO\\IOInterface'), $this->getMock('Composer\\Util\\ProcessExecutor'));
     $event = $this->getMockBuilder('Composer\\Script\\Event')->disableOriginalConstructor()->getMock();
     $event->method('getName')->will($this->returnValue('scriptName'));
     $event->expects($this->atLeastOnce())->method('isDevMode')->will($this->returnValue($devMode));
     $dispatcher->hasEventListeners($event);
 }
 public function testPreAndPostEventsAreDispatchedDuringAutoloadDump()
 {
     $this->eventDispatcher->expects($this->at(0))->method('dispatchScript')->with(ScriptEvents::PRE_AUTOLOAD_DUMP, false);
     $this->eventDispatcher->expects($this->at(1))->method('dispatchScript')->with(ScriptEvents::POST_AUTOLOAD_DUMP, false);
     $package = new Package('a', '1.0', '1.0');
     $package->setAutoload(array('psr-0' => array('foo/bar/non/existing/')));
     $this->repository->expects($this->once())->method('getCanonicalPackages')->will($this->returnValue(array()));
     $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_8');
 }
Ejemplo n.º 4
0
    public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
    {
        $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode);
        $filesystem = new Filesystem();
        $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
        $basePath = $filesystem->normalizePath(realpath(getcwd()));
        $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
        $useGlobalIncludePath = (bool) $config->get('use-include-path');
        $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
        $targetDir = $vendorPath . '/' . $targetDir;
        $filesystem->ensureDirectoryExists($targetDir);
        $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
        $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
        $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
        $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
        $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
        $namespacesFile = <<<EOF
<?php

// autoload_namespaces.php @generated by Composer

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

return array(

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

// autoload_psr4.php @generated by Composer

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

return array(

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

// autoload_classmap.php @generated by Composer

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

return array(

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

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

            return true;
        }
    }

EOF;
        }
        // flatten array
        $classMap = array();
        if ($scanPsr0Packages) {
            // Scan the PSR-0/4 directories for class files, and add them to the class map
            foreach (array('psr-0', 'psr-4') as $psrType) {
                foreach ($autoloads[$psrType] as $namespace => $paths) {
                    foreach ($paths as $dir) {
                        $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath . '/' . $dir);
                        if (!is_dir($dir)) {
                            continue;
                        }
                        $whitelist = sprintf('{%s/%s.+(?<!(?<!/)Test\\.php)$}', preg_quote($dir), $psrType === 'psr-0' && strpos($namespace, '_') === false ? preg_quote(strtr($namespace, '\\', '/')) : '');
                        $namespaceFilter = $namespace === '' ? null : $namespace;
                        foreach (ClassMapGenerator::createMap($dir, $whitelist, $this->io, $namespaceFilter) as $class => $path) {
                            if (!isset($classMap[$class])) {
                                $path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
                                $classMap[$class] = $path . ",\n";
                            }
                        }
                    }
                }
            }
        }
        foreach ($autoloads['classmap'] as $dir) {
            foreach (ClassMapGenerator::createMap($dir, null, $this->io) as $class => $path) {
                $path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
                $classMap[$class] = $path . ",\n";
            }
        }
        ksort($classMap);
        foreach ($classMap as $class => $code) {
            $classmapFile .= '    ' . var_export($class, true) . ' => ' . $code;
        }
        $classmapFile .= ");\n";
        if (!$suffix) {
            $suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
        }
        file_put_contents($targetDir . '/autoload_namespaces.php', $namespacesFile);
        file_put_contents($targetDir . '/autoload_psr4.php', $psr4File);
        file_put_contents($targetDir . '/autoload_classmap.php', $classmapFile);
        if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
            file_put_contents($targetDir . '/include_paths.php', $includePathFile);
        }
        if ($includeFilesFile = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
            file_put_contents($targetDir . '/autoload_files.php', $includeFilesFile);
        }
        file_put_contents($vendorPath . '/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
        file_put_contents($targetDir . '/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFile, $targetDirLoader, (bool) $includeFilesFile, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader));
        // use stream_copy_to_stream instead of copy
        // to work around https://bugs.php.net/bug.php?id=64634
        $sourceLoader = fopen(__DIR__ . '/ClassLoader.php', 'r');
        $targetLoader = fopen($targetDir . '/ClassLoader.php', 'w+');
        stream_copy_to_stream($sourceLoader, $targetLoader);
        fclose($sourceLoader);
        fclose($targetLoader);
        unset($sourceLoader, $targetLoader);
        $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode);
    }
Ejemplo n.º 5
0
 protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $withDevReqs)
 {
     // init vars
     $lockedRepository = null;
     $repositories = null;
     // initialize locker to create aliased packages
     $installFromLock = false;
     if (!$this->update && $this->locker->isLocked()) {
         $installFromLock = true;
         try {
             $lockedRepository = $this->locker->getLockedRepository($withDevReqs);
         } catch (\RuntimeException $e) {
             // if there are dev requires, then we really can not install
             if ($this->package->getDevRequires()) {
                 throw $e;
             }
             // no require-dev in composer.json and the lock file was created with no dev info, so skip them
             $lockedRepository = $this->locker->getLockedRepository();
         }
     }
     $this->whitelistUpdateDependencies($localRepo, $withDevReqs, $this->package->getRequires(), $this->package->getDevRequires());
     $this->io->writeError('<info>Loading composer repositories with package information</info>');
     // creating repository pool
     $policy = $this->createPolicy();
     $pool = $this->createPool($withDevReqs, $lockedRepository);
     $pool->addRepository($installedRepo, $aliases);
     if ($installFromLock) {
         $pool->addRepository($lockedRepository, $aliases);
     }
     if (!$installFromLock) {
         $repositories = $this->repositoryManager->getRepositories();
         foreach ($repositories as $repository) {
             $pool->addRepository($repository, $aliases);
         }
     }
     // creating requirements request
     $request = $this->createRequest($pool, $this->package, $platformRepo);
     if (!$installFromLock) {
         // remove unstable packages from the localRepo if they don't match the current stability settings
         $removedUnstablePackages = array();
         foreach ($localRepo->getPackages() as $package) {
             if (!$pool->isPackageAcceptable($package->getNames(), $package->getStability()) && $this->installationManager->isPackageInstalled($localRepo, $package)) {
                 $removedUnstablePackages[$package->getName()] = true;
                 $request->remove($package->getName(), new VersionConstraint('=', $package->getVersion()));
             }
         }
     }
     if ($this->update) {
         $this->io->writeError('<info>Updating dependencies' . ($withDevReqs ? ' (including require-dev)' : '') . '</info>');
         $request->updateAll();
         if ($withDevReqs) {
             $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
         } else {
             $links = $this->package->getRequires();
         }
         foreach ($links as $link) {
             $request->install($link->getTarget(), $link->getConstraint());
         }
         // if the updateWhitelist is enabled, packages not in it are also fixed
         // to the version specified in the lock, or their currently installed version
         if ($this->updateWhitelist) {
             if ($this->locker->isLocked()) {
                 try {
                     $currentPackages = $this->locker->getLockedRepository($withDevReqs)->getPackages();
                 } catch (\RuntimeException $e) {
                     // fetch only non-dev packages from lock if doing a dev update fails due to a previously incomplete lock file
                     $currentPackages = $this->locker->getLockedRepository()->getPackages();
                 }
             } else {
                 $currentPackages = $installedRepo->getPackages();
             }
             // collect packages to fixate from root requirements as well as installed packages
             $candidates = array();
             foreach ($links as $link) {
                 $candidates[$link->getTarget()] = true;
             }
             foreach ($localRepo->getPackages() as $package) {
                 $candidates[$package->getName()] = true;
             }
             // fix them to the version in lock (or currently installed) if they are not updateable
             foreach ($candidates as $candidate => $dummy) {
                 foreach ($currentPackages as $curPackage) {
                     if ($curPackage->getName() === $candidate) {
                         if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) {
                             $constraint = new VersionConstraint('=', $curPackage->getVersion());
                             $request->install($curPackage->getName(), $constraint);
                         }
                         break;
                     }
                 }
             }
         }
     } elseif ($installFromLock) {
         $this->io->writeError('<info>Installing dependencies' . ($withDevReqs ? ' (including require-dev)' : '') . ' from lock file</info>');
         if (!$this->locker->isFresh()) {
             $this->io->writeError('<warning>Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.</warning>');
         }
         foreach ($lockedRepository->getPackages() as $package) {
             $version = $package->getVersion();
             if (isset($aliases[$package->getName()][$version])) {
                 $version = $aliases[$package->getName()][$version]['alias_normalized'];
             }
             $constraint = new VersionConstraint('=', $version);
             $constraint->setPrettyString($package->getPrettyVersion());
             $request->install($package->getName(), $constraint);
         }
         foreach ($this->locker->getPlatformRequirements($withDevReqs) as $link) {
             $request->install($link->getTarget(), $link->getConstraint());
         }
     } else {
         $this->io->writeError('<info>Installing dependencies' . ($withDevReqs ? ' (including require-dev)' : '') . '</info>');
         if ($withDevReqs) {
             $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
         } else {
             $links = $this->package->getRequires();
         }
         foreach ($links as $link) {
             $request->install($link->getTarget(), $link->getConstraint());
         }
     }
     // force dev packages to have the latest links if we update or install from a (potentially new) lock
     $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-links');
     // solve dependencies
     $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request);
     $solver = new Solver($policy, $pool, $installedRepo);
     try {
         $operations = $solver->solve($request, $this->ignorePlatformReqs);
         $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request, $operations);
     } catch (SolverProblemsException $e) {
         $this->io->writeError('<error>Your requirements could not be resolved to an installable set of packages.</error>');
         $this->io->writeError($e->getMessage());
         return max(1, $e->getCode());
     }
     // force dev packages to be updated if we update or install from a (potentially new) lock
     $operations = $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-updates', $operations);
     // execute operations
     if (!$operations) {
         $this->io->writeError('Nothing to install or update');
     }
     $operations = $this->movePluginsToFront($operations);
     $operations = $this->moveUninstallsToFront($operations);
     foreach ($operations as $operation) {
         // collect suggestions
         if ('install' === $operation->getJobType()) {
             foreach ($operation->getPackage()->getSuggests() as $target => $reason) {
                 $this->suggestedPackages[] = array('source' => $operation->getPackage()->getPrettyName(), 'target' => $target, 'reason' => $reason);
             }
         }
         // not installing from lock, force dev packages' references if they're in root package refs
         if (!$installFromLock) {
             $package = null;
             if ('update' === $operation->getJobType()) {
                 $package = $operation->getTargetPackage();
             } elseif ('install' === $operation->getJobType()) {
                 $package = $operation->getPackage();
             }
             if ($package && $package->isDev()) {
                 $references = $this->package->getReferences();
                 if (isset($references[$package->getName()])) {
                     $package->setSourceReference($references[$package->getName()]);
                     $package->setDistReference($references[$package->getName()]);
                 }
             }
             if ('update' === $operation->getJobType() && $operation->getTargetPackage()->isDev() && $operation->getTargetPackage()->getVersion() === $operation->getInitialPackage()->getVersion() && $operation->getTargetPackage()->getSourceReference() === $operation->getInitialPackage()->getSourceReference()) {
                 if ($this->io->isDebug()) {
                     $this->io->writeError('  - Skipping update of ' . $operation->getTargetPackage()->getPrettyName() . ' to the same reference-locked version');
                     $this->io->writeError('');
                 }
                 continue;
             }
         }
         $event = 'Composer\\Installer\\PackageEvents::PRE_PACKAGE_' . strtoupper($operation->getJobType());
         if (defined($event) && $this->runScripts) {
             $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
         }
         // output non-alias ops in dry run, output alias ops in debug verbosity
         if ($this->dryRun && false === strpos($operation->getJobType(), 'Alias')) {
             $this->io->writeError('  - ' . $operation);
             $this->io->writeError('');
         } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
             $this->io->writeError('  - ' . $operation);
             $this->io->writeError('');
         }
         $this->installationManager->execute($localRepo, $operation);
         // output reasons why the operation was ran, only for install/update operations
         if ($this->verbose && $this->io->isVeryVerbose() && in_array($operation->getJobType(), array('install', 'update'))) {
             $reason = $operation->getReason();
             if ($reason instanceof Rule) {
                 switch ($reason->getReason()) {
                     case Rule::RULE_JOB_INSTALL:
                         $this->io->writeError('    REASON: Required by root: ' . $reason->getPrettyString($pool));
                         $this->io->writeError('');
                         break;
                     case Rule::RULE_PACKAGE_REQUIRES:
                         $this->io->writeError('    REASON: ' . $reason->getPrettyString($pool));
                         $this->io->writeError('');
                         break;
                 }
             }
         }
         $event = 'Composer\\Installer\\PackageEvents::POST_PACKAGE_' . strtoupper($operation->getJobType());
         if (defined($event) && $this->runScripts) {
             $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
         }
         if (!$this->dryRun) {
             $localRepo->write();
         }
     }
     return 0;
 }
Ejemplo n.º 6
0
    public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
    {
        if ($this->classMapAuthoritative) {
            // Force scanPsr0Packages when classmap is authoritative
            $scanPsr0Packages = true;
        }
        $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, array(), array('optimize' => (bool) $scanPsr0Packages));
        $filesystem = new Filesystem();
        $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
        $basePath = $filesystem->normalizePath(realpath(getcwd()));
        $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
        $useGlobalIncludePath = (bool) $config->get('use-include-path');
        $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
        $targetDir = $vendorPath . '/' . $targetDir;
        $filesystem->ensureDirectoryExists($targetDir);
        $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
        $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
        $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
        $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
        $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
        $namespacesFile = <<<EOF
<?php

// autoload_namespaces.php @generated by Composer

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

return array(

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

// autoload_psr4.php @generated by Composer

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

return array(

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

// autoload_classmap.php @generated by Composer

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

return array(

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

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

            return true;
        }
    }

EOF;
        }
        $blacklist = null;
        if (!empty($autoloads['exclude-from-classmap'])) {
            $blacklist = '{(' . implode('|', $autoloads['exclude-from-classmap']) . ')}';
        }
        // flatten array
        $classMap = array();
        if ($scanPsr0Packages) {
            $namespacesToScan = array();
            // Scan the PSR-0/4 directories for class files, and add them to the class map
            foreach (array('psr-0', 'psr-4') as $psrType) {
                foreach ($autoloads[$psrType] as $namespace => $paths) {
                    $namespacesToScan[$namespace][] = array('paths' => $paths, 'type' => $psrType);
                }
            }
            krsort($namespacesToScan);
            foreach ($namespacesToScan as $namespace => $groups) {
                foreach ($groups as $group) {
                    $psrType = $group['type'];
                    foreach ($group['paths'] as $dir) {
                        $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath . '/' . $dir);
                        if (!is_dir($dir)) {
                            continue;
                        }
                        //                        $whitelist = sprintf(
                        //                            '{%s/%s.+$}',
                        //                            preg_quote($dir),
                        //                            ($psrType === 'psr-0' && strpos($namespace, '_') === false) ? preg_quote(strtr($namespace, '\\', '/')) : ''
                        //                        );
                        $namespaceFilter = $namespace === '' ? null : $namespace;
                        $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, $namespaceFilter, $classMap);
                    }
                }
            }
        }
        foreach ($autoloads['classmap'] as $dir) {
            $classMap = $this->addClassMapCode($filesystem, $basePath, $vendorPath, $dir, $blacklist, null, $classMap);
        }
        ksort($classMap);
        foreach ($classMap as $class => $code) {
            $classmapFile .= '    ' . var_export($class, true) . ' => ' . $code;
        }
        $classmapFile .= ");\n";
        if (!$suffix) {
            if (!$config->get('autoloader-suffix') && is_readable($vendorPath . '/autoload.php')) {
                $content = file_get_contents($vendorPath . '/autoload.php');
                if (preg_match('{ComposerAutoloaderInit([^:\\s]+)::}', $content, $match)) {
                    $suffix = $match[1];
                }
            }
            if (!$suffix) {
                $suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
            }
        }
        file_put_contents($targetDir . '/autoload_namespaces.php', $namespacesFile);
        file_put_contents($targetDir . '/autoload_psr4.php', $psr4File);
        file_put_contents($targetDir . '/autoload_classmap.php', $classmapFile);
        $includePathFilePath = $targetDir . '/include_paths.php';
        if ($includePathFileContents = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
            file_put_contents($includePathFilePath, $includePathFileContents);
        } elseif (file_exists($includePathFilePath)) {
            unlink($includePathFilePath);
        }
        $includeFilesFilePath = $targetDir . '/autoload_files.php';
        if ($includeFilesFileContents = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
            file_put_contents($includeFilesFilePath, $includeFilesFileContents);
        } elseif (file_exists($includeFilesFilePath)) {
            unlink($includeFilesFilePath);
        }
        file_put_contents($vendorPath . '/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
        file_put_contents($targetDir . '/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFileContents, $targetDirLoader, (bool) $includeFilesFileContents, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader));
        $this->safeCopy(__DIR__ . '/ClassLoader.php', $targetDir . '/ClassLoader.php');
        $this->safeCopy(__DIR__ . '/../../../LICENSE', $targetDir . '/LICENSE');
        $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, array(), array('optimize' => (bool) $scanPsr0Packages));
    }
Ejemplo n.º 7
0
 /**
  * Extracts the dev packages out of the localRepo
  *
  * This works by faking the operations so we can see what the dev packages
  * would be at the end of the operation execution. This lets us then remove
  * the dev packages from the list of operations accordingly if we are in a
  * --no-dev install or update.
  *
  * @return array
  */
 private function extractDevPackages(array $operations, RepositoryInterface $localRepo, PlatformRepository $platformRepo, array $aliases)
 {
     if (!$this->package->getDevRequires()) {
         return array();
     }
     // fake-apply all operations to this clone of the local repo so we see the complete set of package we would end up with
     $tempLocalRepo = clone $localRepo;
     foreach ($operations as $operation) {
         switch ($operation->getJobType()) {
             case 'install':
             case 'markAliasInstalled':
                 if (!$tempLocalRepo->hasPackage($operation->getPackage())) {
                     $tempLocalRepo->addPackage(clone $operation->getPackage());
                 }
                 break;
             case 'uninstall':
             case 'markAliasUninstalled':
                 $tempLocalRepo->removePackage($operation->getPackage());
                 break;
             case 'update':
                 $tempLocalRepo->removePackage($operation->getInitialPackage());
                 if (!$tempLocalRepo->hasPackage($operation->getTargetPackage())) {
                     $tempLocalRepo->addPackage(clone $operation->getTargetPackage());
                 }
                 break;
             default:
                 throw new \LogicException('Unknown type: ' . $operation->getJobType());
         }
     }
     // we have to reload the local repo to handle aliases properly
     // but as it is not persisted on disk we use a loader/dumper
     // to reload it in memory
     $localRepo = new InstalledArrayRepository(array());
     $loader = new ArrayLoader(null, true);
     $dumper = new ArrayDumper();
     foreach ($tempLocalRepo->getCanonicalPackages() as $pkg) {
         $localRepo->addPackage($loader->load($dumper->dump($pkg)));
     }
     unset($tempLocalRepo, $loader, $dumper);
     $policy = $this->createPolicy();
     $pool = $this->createPool();
     $installedRepo = $this->createInstalledRepo($localRepo, $platformRepo);
     $pool->addRepository($installedRepo, $aliases);
     // creating requirements request without dev requirements
     $request = $this->createRequest($this->package, $platformRepo);
     $request->updateAll();
     foreach ($this->package->getRequires() as $link) {
         $request->install($link->getTarget(), $link->getConstraint());
     }
     // solve deps to see which get removed
     $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request);
     $solver = new Solver($policy, $pool, $installedRepo, $this->io);
     $ops = $solver->solve($request, $this->ignorePlatformReqs);
     $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request, $ops);
     $devPackages = array();
     foreach ($ops as $op) {
         if ($op->getJobType() === 'uninstall') {
             $devPackages[] = $op->getPackage();
         }
     }
     return $devPackages;
 }
Ejemplo n.º 8
0
 /**
  * Downloads drupal scaffold files for the current process.
  */
 public function downloadScaffold()
 {
     $drupalCorePackage = $this->getDrupalCorePackage();
     $webroot = realpath($this->getWebRoot());
     // Collect options, excludes and settings files.
     $options = $this->getOptions();
     $files = array_diff($this->getIncludes(), $this->getExcludes());
     // Call any pre-scaffold scripts that may be defined.
     $dispatcher = new EventDispatcher($this->composer, $this->io);
     $dispatcher->dispatch(self::PRE_DRUPAL_SCAFFOLD_CMD);
     $version = $this->getDrupalCoreVersion($drupalCorePackage);
     $remoteFs = new RemoteFilesystem($this->io);
     $fetcher = new FileFetcher($remoteFs, $options['source'], $files);
     $fetcher->fetch($version, $webroot);
     $initialFileFetcher = new InitialFileFetcher($remoteFs, $options['source'], $this->getInitial());
     $initialFileFetcher->fetch($version, $webroot);
     // Call post-scaffold scripts.
     $dispatcher->dispatch(self::POST_DRUPAL_SCAFFOLD_CMD);
 }
Ejemplo n.º 9
0
 /**
  * Downloads drupal scaffold files for the current process.
  */
 public function downloadScaffold()
 {
     $drupalCorePackage = $this->getDrupalCorePackage();
     $webroot = $this->getWebRoot();
     // Collect options, excludes and settings files.
     $options = $this->getOptions();
     $excludes = $this->getExcludes();
     $includes = $this->getIncludes();
     // Call any pre-scaffold scripts that may be defined.
     $dispatcher = new EventDispatcher($this->composer, $this->io);
     $dispatcher->dispatch(self::PRE_DRUPAL_SCAFFOLD_CMD);
     // Run Robo
     $robo = new RoboRunner();
     $robo->execute(['robo', 'drupal_scaffold:download', $drupalCorePackage->getPrettyVersion(), '--source', $options['source'], '--webroot', realpath($webroot), '--excludes', static::array_to_csv($excludes), '--includes', static::array_to_csv($includes)]);
     // Call post-scaffold scripts.
     $dispatcher->dispatch(self::POST_DRUPAL_SCAFFOLD_CMD);
 }