/** * Run 'composer remove' * * @param array $packages * @return void */ public function remove(array $packages) { $this->composerApp->resetComposer(); $this->composerApp->setAutoExit(false); $vendor = (include $this->directoryList->getPath(DirectoryList::CONFIG) . '/vendor_path.php'); $this->composerApp->run(new ArrayInput(['command' => 'remove', 'packages' => $packages, '--working-dir' => $this->directoryList->getRoot() . '/' . $vendor . '/..'])); }
/** * @see \WsdlToPhp\PackageGenerator\File\AbstractFile::writeFile() * @return int|bool */ protected function writeFile() { $composer = new Application(); $composer->setAutoExit(false); $composer->run(new ArrayInput(array('command' => 'init', '--verbose' => true, '--no-interaction' => true, '--name' => $this->getGenerator()->getOptionComposerName(), '--description' => sprintf('Package generated from %s using wsdltophp/packagegenerator', $this->getGenerator()->getWsdl()->getName()), '--require' => array('php:>=5.3.3', 'ext-soap:*', 'wsdltophp/packagebase:dev-master'), '--working-dir' => $this->getGenerator()->getOptionDestination()))); $this->addAutoloadToComposerJson(); if ($this->getRunComposerUpdate() === true) { return $composer->run(new ArrayInput(array('command' => 'update', '--verbose' => true, '--optimize-autoloader' => true, '--no-dev' => true, '--working-dir' => $this->getGenerator()->getOptionDestination()))); } return 1; }
/** * Updates composer dependencies. */ public function updateDependencies() { $container = InnomaticContainer::instance('\\Innomatic\\Core\\InnomaticContainer'); // Keep track of the current directory $previousDirectory = getcwd(); // Retrieve the Innomatic Platform root directory $platformHome = RootContainer::instance('\\Innomatic\\Core\\RootContainer')->getPlatformHome(); // Switch current directory to the Innomatic Platform root chdir($platformHome); // Call composer install command $input = new ArrayInput(array('command' => 'update')); if ($container->getInterface() == InnomaticContainer::INTERFACE_CONSOLE) { $output = new ConsoleOutput(); } else { $output = new BufferedOutput(); } $application = new ComposerApplication(); // Prevent application run method from exiting the script $application->setAutoExit(false); $application->run($input, $output); // Switch back to the previous current directory chdir($previousDirectory); // Switch back to the standard Innomatic PHP error handler set_error_handler(array($container, 'errorHandler')); }
/** * Checks dependencies to package(s), returns array of dependencies in the format of * 'package A' => [array of package names depending on package A] * If $excludeSelf is set to true, items in $packages will be excluded in all * "array of package names depending on package A" * * @param string[] $packages * @param bool $excludeSelf * @return string[] */ public function checkDependencies(array $packages, $excludeSelf = false) { $this->composerApp->setAutoExit(false); $dependencies = []; foreach ($packages as $package) { $buffer = new BufferedOutput(); $this->composerApp->resetComposer(); $this->composerApp->run(new ArrayInput(['command' => 'depends', '--working-dir' => $this->directoryList->getRoot(), 'package' => $package]), $buffer); $dependingPackages = $this->parseComposerOutput($buffer->fetch()); if ($excludeSelf === true) { $dependingPackages = array_values(array_diff($dependingPackages, $packages)); } $dependencies[$package] = $dependingPackages; } return $dependencies; }
function composer_ALL(Web $w) { echo "<pre>" . file_get_contents(ROOT_PATH . '/log/composer.log') . "</pre>"; // Collect dependencies $dependencies_array = array(); foreach ($w->modules() as $module) { $dependencies = Config::get("{$module}.dependencies"); if (!empty($dependencies)) { $dependencies_array = array_merge($dependencies, $dependencies_array); } } $json_obj = array(); $json_obj["config"] = array(); $json_obj["config"]["vendor-dir"] = 'composer/vendor'; $json_obj["config"]["cache-dir"] = 'composer/cache'; $json_obj["config"]["bin-dir"] = 'composer/bin'; $json_obj["require"] = $dependencies_array; // Need to change dir so composer can find the json file chdir(SYSTEM_PATH); // Create the JSON file file_put_contents(SYSTEM_PATH . "/composer.json", json_encode($json_obj, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_FORCE_OBJECT)); //Create the commands $input = new ArrayInput(array('command' => 'update', '--prefer-dist' => 'true')); $filestream = new StreamOutput(fopen(ROOT_PATH . '/log/composer.log', 'w')); //Create the application and run it with the commands $application = new Application(); $exitcode = $application->run($input, $filestream); // Change dir back to root chdir(ROOT_PATH); // This doesn't happen for some reason $w->msg("Composer update return exit code " . $exitcode . " (0 is OK)<br/>Check the /log/composer.log for output", "/admin"); }
/** * Standard Running the Composer Command * * @return object */ public function run() { // Run the Composer command. $application = new Application(); $application->setAutoExit(false); $application->run(); return $this->loader; }
private function checkComposer() { $this->io->writeln("Checking Composer status:", 'green'); //putenv('COMPOSER_HOME=' . $this->application()->basePath() . '/vendor/bin/composer/composer/src/'); $input = new ArrayInput(['command' => 'update', '--dry-run' => true]); $composer = new Application(); $composer->setAutoExit(false); $composer->run($input); $this->io->writeln(); }
/** * Rebuilds the root package, then calls 'composer update'. */ public static function update(Event $event) { $package_manager = self::getPackageManager(); $package_manager->rebuildRootPackage(); // Change the requested command to 'update', and rerun composer. $command_index = array_search('drupal-update', $_SERVER['argv']); $_SERVER['argv'][$command_index] = 'update'; $application = new Application(); $application->run(); }
public function update($name) { $app = new Application(); $app->setAutoExit(false); $input = new ArrayInput(['update', 'packages' => [$name]]); $input->setInteractive(false); $output = new BufferedOutput(); $app->run($input, $output); return $output->fetch(); }
private function composerInstall() { $this->io->writeln("Running Composer install:", 'green'); putenv('COMPOSER_HOME=' . $this->application()->basePath() . '/vendor/bin/composer'); $input = new ArrayInput(['command' => 'install']); $composer = new Application(); $composer->setAutoExit(false); $composer->run($input); $this->io->writeln(); }
/** * Run this composer wrapper as a command-line application. * * @param string $input command line arguments * @param object $output output object * @return integer 0 if everything went fine, or an error code * @see http://api.symfony.com/2.2/Symfony/Component/Console/Application.html#method_run */ public function run($input = '', $output = null) { $this->loadComposerPhar(false); if (!$this->application) { $this->application = new \Composer\Console\Application(); $this->application->setAutoExit(false); } $cli_args = is_string($input) && !empty($input) ? new \Symfony\Component\Console\Input\StringInput($input) : null; return $this->application->run($cli_args, $output); }
public function diagnose() { $instance = WpComposer::Instance(); $instance->recursiveExecution(function ($path, $data, $is_plugin, $is_theme) { WP_CLI::line(sprintf('Starting to process %s', end(explode('/', $path)))); $_SERVER['argv'] = array('composer', 'diagnose'); // Run the Composer command. $application = new Application(); $application->setAutoExit(false); $application->run(); WP_CLI::success('Finished processing'); }); }
/** * Run this composer wrapper as a command-line application. * * @param string $input command line arguments * @param object $output output object * @return integer 0 if everything went fine, or an error code * @see http://api.symfony.com/2.2/Symfony/Component/Console/Application.html#method_run */ public function run($input = '', $output = null) { $this->loadComposerPhar(false); if (!$this->application) { $this->application = new \Composer\Console\Application(); $this->application->setAutoExit(false); } $cli_args = is_string($input) && !empty($input) ? new \Symfony\Component\Console\Input\StringInput($input) : null; $argv0 = $_SERVER['argv'][0]; $this->fixSelfupdate($cli_args); $exitcode = $this->application->run($cli_args, $output); $_SERVER['argv'][0] = $argv0; return $exitcode; }
/** * Run composer command * * @param array $commandParams * @return bool * @throws \RuntimeException */ protected function runComposerCommand(array $commandParams) { $input = $this->consoleArrayInputFactory->create($commandParams); $this->consoleApplication->setAutoExit(false); putenv('COMPOSER_HOME=' . $this->composerConfigFileDir . '/' . self::COMPOSER_HOME_DIR); putenv('COMPOSER=' . $this->composerConfigFileDir . '/composer.json'); $exitCode = $this->consoleApplication->run($input, $this->consoleOutput); $output = $this->consoleOutput->fetch(); if ($exitCode) { $commandParamsString = json_encode($commandParams, JSON_UNESCAPED_SLASHES); throw new \RuntimeException(sprintf('Command "%s"%s failed: %s', $commandParams['command'], $commandParamsString, $output)); } return $output; }
/** * @param string $commandName * @param array|string $arguments * @param array|string $parameters **/ protected function runComposerCommand($commandName, $parameters = [], $arguments = []) { $arguments = (array) $arguments; $parameters = (array) $parameters; $input = new ArrayInput(array_merge(['command' => $commandName], $this->config['defaultParameters'], $parameters, $arguments)); // this is ugly but require doesn't seem to work otherwise if ($commandName === 'require') { exec('composer ' . $input); } else { $composer = new Application(); $composer->setAutoExit(false); $composer->run($input); } }
public function handleUpdate() { // Composer\Factory::getHomeDir() method // needs COMPOSER_HOME environment variable set putenv('COMPOSER_HOME=' . DIR_ROOT . '/vendor/bin/composer'); $input = new ArrayInput(['command' => 'update']); $output = new ConsoleOutput(); $application = new Application(); $application->setAutoExit(false); // prevent `$application->run` method from exitting the script $application->run($input, $output); $this->flashMessage("Update has been successfully done!", "success"); $this->redirect('this'); }
/** * Runs composer command * * @param array $commandParams * @param string|null $workingDir * @return bool * @throws \RuntimeException */ public function runComposerCommand(array $commandParams, $workingDir = null) { $this->consoleApplication->resetComposer(); if ($workingDir) { $commandParams[self::COMPOSER_WORKING_DIR] = $workingDir; } else { $commandParams[self::COMPOSER_WORKING_DIR] = dirname($this->composerJson); } $input = $this->consoleArrayInputFactory->create($commandParams); $exitCode = $this->consoleApplication->run($input, $this->consoleOutput); if ($exitCode) { throw new \RuntimeException(sprintf('Command "%s" failed: %s', $commandParams['command'], $this->consoleOutput->fetch())); } return $this->consoleOutput->fetch(); }
/** * @param string $format sprintf-style format string. * @param string, ... $params one or more parameters to interpolate into the format */ protected function execute() { $args = func_get_args(); $format = array_shift($args); $sanitize = function ($arg) { if (preg_match('/^-/', $arg)) { return ''; // starts with a dash: skip } if (preg_match('#[^a-zA-Z0-9\\-_:/~^\\\\.*]#', $arg)) { return ''; // contains invalid characters: skip } return escapeshellarg($arg); }; $params = array_map($sanitize, $args); $command = vsprintf($format, $params); // Try to prevent time-outs. set_time_limit(0); // Tentative fix for the issue on OSX, where the response would be this: // [Symfony\Component\Process\Exception\RuntimeException] // The process has been signaled with signal "5". // @see https://github.com/composer/composer/issues/2146#issuecomment-35478940 putenv("DYLD_LIBRARY_PATH=''"); $command .= ' -d "' . $this->basedir . '" -n --no-ansi'; $this->writeLog('command', $command); // Create an InputInterface object to pass to Composer $command = new StringInput($command); // Create the output buffer $output = new BufferedOutput(); // Execute the Composer task $responseCode = $this->composerapp->run($command, $output); if ($responseCode == 0) { $outputText = $output->fetch(); $this->writeLog('success', '', $outputText); return array_filter(explode("\n", $this->clean($outputText))); } else { $outputText = $output->fetch(); $this->writeLog('error', '', $outputText); return false; } }
public function execute(IOStream $io) { $io->writeln('Optimizing Core Framework...', 'green'); if ($this->getOptions('all') || $this->getOptions('a')) { putenv('COMPOSER_HOME=' . $this->application()->basePath() . '/vendor/bin/composer'); $input = new ArrayInput(['command' => 'clearcache']); $composer = new Application(); $composer->setAutoExit(false); $composer->run($input); $input = new ArrayInput(['command' => 'dumpautoload']); $composer = new Application(); $composer->setAutoExit(false); $composer->run($input); } $cache = $this->application()->getCache(); $config = $this->application()->getConfig(); $router = $this->application()->getRouter(); $cache->delete('framework.conf'); $cache->delete('routes'); $router->loadRoutes(); $router->cacheRoutes(); $cache->put('framework.conf', $config->all(), $config->get('app.ttl', 60)); $io->writeln('Core Framework Application Optimized successfully!', 'green'); }
public static function install($packages) { // Don't proceed if packages haven't changed. if ($packages == self::dump()) { return false; } putenv('COMPOSER_HOME=' . __DIR__ . '/../../vendor/bin/composer'); self::createComposerJson($packages); chdir(storage_dir()); // Setup composer output formatter $stream = fopen('php://temp', 'w+'); $output = new StreamOutput($stream); // Programmatically run `composer install` $application = new Application(); $application->setAutoExit(false); $code = $application->run(new ArrayInput(array('command' => 'install')), $output); // remove composer.lock if (file_exists(storage_dir() . 'composer.lock')) { unlink(storage_dir() . 'composer.lock'); } // rewind stream to read full contents rewind($stream); return stream_get_contents($stream); }
<?php require __DIR__ . '/../src/bootstrap.php'; use Composer\Console\Application; error_reporting(-1); if (function_exists('ini_set')) { @ini_set('display_errors', 1); $memoryInBytes = function ($value) { $unit = strtolower(substr($value, -1, 1)); $value = (int) $value; switch ($unit) { case 'g': $value *= 1024; case 'm': $value *= 1024; case 'k': $value *= 1024; } return $value; }; $memoryLimit = trim(ini_get('memory_limit')); // Increase memory_limit if it is lower than 512M if ($memoryLimit != -1 && $memoryInBytes($memoryLimit) < 512 * 1024 * 1024) { @ini_set('memory_limit', '512M'); } unset($memoryInBytes, $memoryLimit); } // run the command application $application = new Application(); $application->run();
/** * Fires the job. * * @param $job * @param array $data * @throws \Exception */ public function fire($job, $data) { echo 'Running: OxygenModule\\Marketplace\\Installer\\ComposerInstallJob' . "\n"; // Composer\Factory::getHomeDir() method // needs COMPOSER_HOME environment variable set putenv('COMPOSER=' . base_path() . '/composer.json'); putenv('COMPOSER_HOME=' . base_path() . '/.composer'); $log = $this->config->get('oxygen.mod-marketplace.install.log'); $progress = $this->config->get('oxygen.mod-marketplace.install.progress'); foreach ([$log, $progress] as $file) { $this->files->delete($file); if (!$this->files->exists(dirname($file))) { $this->files->makeDirectory(dirname($file)); } } $input = new ArrayInput($this->config->get('oxygen.mod-marketplace.install.command')); $this->output = new StreamOutput(fopen($log, 'a', false), OutputInterface::VERBOSITY_DEBUG); $this->progress = new FileProgress($progress, $this->output); $this->progress->section('Beginning Installation'); $this->progress->indeterminate(); $this->progress->notification('Installation Started'); $application = new Application(); $application->setAutoExit(false); $application->setCatchExceptions(false); try { $application->run($input, $this->output, $this->progress); $this->events->fire('oxygen.marketplace.postUpdate', [$this->progress, $this->output]); $this->progress->notification('Installation Complete'); $this->progress->section('Complete'); $this->progress->stopPolling(); $job->delete(); } catch (Exception $e) { $this->progress->notification($e->getMessage(), 'failed'); $this->progress->stopPolling(); throw $e; } }
/** * @dataProvider getIntegrationTests */ public function testIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectOutput, $expect) { if ($condition) { eval('$res = '.$condition.';'); if (!$res) { $this->markTestSkipped($condition); } } $output = null; $io = $this->getMock('Composer\IO\IOInterface'); $io->expects($this->any()) ->method('write') ->will($this->returnCallback(function ($text, $newline) use (&$output) { $output .= $text . ($newline ? "\n":""); })); $composer = FactoryMock::create($io, $composerConfig); $jsonMock = $this->getMockBuilder('Composer\Json\JsonFile')->disableOriginalConstructor()->getMock(); $jsonMock->expects($this->any()) ->method('read') ->will($this->returnValue($installed)); $jsonMock->expects($this->any()) ->method('exists') ->will($this->returnValue(true)); $repositoryManager = $composer->getRepositoryManager(); $repositoryManager->setLocalRepository(new InstalledFilesystemRepositoryMock($jsonMock)); $lockJsonMock = $this->getMockBuilder('Composer\Json\JsonFile')->disableOriginalConstructor()->getMock(); $lockJsonMock->expects($this->any()) ->method('read') ->will($this->returnValue($lock)); $lockJsonMock->expects($this->any()) ->method('exists') ->will($this->returnValue(true)); if ($expectLock) { $actualLock = array(); $lockJsonMock->expects($this->atLeastOnce()) ->method('write') ->will($this->returnCallback(function ($hash, $options) use (&$actualLock) { // need to do assertion outside of mock for nice phpunit output // so store value temporarily in reference for later assetion $actualLock = $hash; })); } $locker = new Locker($lockJsonMock, $repositoryManager, $composer->getInstallationManager(), md5(json_encode($composerConfig))); $composer->setLocker($locker); $eventDispatcher = $this->getMockBuilder('Composer\Script\EventDispatcher')->disableOriginalConstructor()->getMock(); $autoloadGenerator = $this->getMock('Composer\Autoload\AutoloadGenerator', array(), array($eventDispatcher)); $composer->setAutoloadGenerator($autoloadGenerator); $composer->setEventDispatcher($eventDispatcher); $installer = Installer::create( $io, $composer ); $application = new Application; $application->get('install')->setCode(function ($input, $output) use ($installer) { $installer->setDevMode($input->getOption('dev')); return $installer->run() ? 0 : 1; }); $application->get('update')->setCode(function ($input, $output) use ($installer) { $installer ->setDevMode($input->getOption('dev')) ->setUpdate(true) ->setUpdateWhitelist($input->getArgument('packages')); return $installer->run() ? 0 : 1; }); if (!preg_match('{^(install|update)\b}', $run)) { throw new \UnexpectedValueException('The run command only supports install and update'); } $application->setAutoExit(false); $appOutput = fopen('php://memory', 'w+'); $result = $application->run(new StringInput($run), new StreamOutput($appOutput)); fseek($appOutput, 0); $this->assertEquals(0, $result, $output . stream_get_contents($appOutput)); if ($expectLock) { unset($actualLock['hash']); unset($actualLock['_readme']); $this->assertEquals($expectLock, $actualLock); } $installationManager = $composer->getInstallationManager(); $this->assertSame($expect, implode("\n", $installationManager->getTrace())); if ($expectOutput) { $this->assertEquals($expectOutput, $output); } }
/** * @param string $command * @param array $params * @return string */ private function composer($command, $params = []) { if (!file_exists($this->vendorsDir)) { mkdir($this->vendorsDir, 0755, true); } putenv('COMPOSER=' . $this->vendorsDir . '/../composer.json'); putenv('COMPOSER_VENDOR_DIR=' . $this->vendorsDir); putenv('COMPOSER_HOME=' . $this->tmpDir); $arrayInput = ['command' => $command] + $params; $input = new ArrayInput($arrayInput); $output = new BufferedOutput(); $application = new Application(); $application->setAutoExit(false); $application->run($input, $output); return $output->fetch(); }
/** * @dataProvider getIntegrationTests */ public function testIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $installedDev, $run, $expect) { if ($condition) { eval('$res = ' . $condition . ';'); if (!$res) { $this->markTestSkipped($condition); } } $output = null; $io = $this->getMock('Composer\\IO\\IOInterface'); $io->expects($this->any())->method('write')->will($this->returnCallback(function ($text, $newline) use(&$output) { $output .= $text . ($newline ? "\n" : ""); })); $composer = FactoryMock::create($io, $composerConfig); $jsonMock = $this->getMockBuilder('Composer\\Json\\JsonFile')->disableOriginalConstructor()->getMock(); $jsonMock->expects($this->any())->method('read')->will($this->returnValue($installed)); $jsonMock->expects($this->any())->method('exists')->will($this->returnValue(true)); $devJsonMock = $this->getMockBuilder('Composer\\Json\\JsonFile')->disableOriginalConstructor()->getMock(); $devJsonMock->expects($this->any())->method('read')->will($this->returnValue($installedDev)); $devJsonMock->expects($this->any())->method('exists')->will($this->returnValue(true)); $repositoryManager = $composer->getRepositoryManager(); $repositoryManager->setLocalRepository(new InstalledFilesystemRepositoryMock($jsonMock)); $repositoryManager->setLocalDevRepository(new InstalledFilesystemRepositoryMock($devJsonMock)); $lockJsonMock = $this->getMockBuilder('Composer\\Json\\JsonFile')->disableOriginalConstructor()->getMock(); $lockJsonMock->expects($this->any())->method('read')->will($this->returnValue($lock)); $lockJsonMock->expects($this->any())->method('exists')->will($this->returnValue(true)); $locker = new Locker($lockJsonMock, $repositoryManager, $composer->getInstallationManager(), md5(json_encode($composerConfig))); $composer->setLocker($locker); $autoloadGenerator = $this->getMock('Composer\\Autoload\\AutoloadGenerator'); $installer = Installer::create($io, $composer, null, $autoloadGenerator); $application = new Application(); $application->get('install')->setCode(function ($input, $output) use($installer) { $installer->setDevMode($input->getOption('dev')); return $installer->run(); }); $application->get('update')->setCode(function ($input, $output) use($installer) { $installer->setDevMode($input->getOption('dev'))->setUpdate(true)->setUpdateWhitelist($input->getArgument('packages')); return $installer->run(); }); if (!preg_match('{^(install|update)\\b}', $run)) { throw new \UnexpectedValueException('The run command only supports install and update'); } $application->setAutoExit(false); $appOutput = fopen('php://memory', 'w+'); $result = $application->run(new StringInput($run), new StreamOutput($appOutput)); fseek($appOutput, 0); $this->assertEquals(0, $result, $output . stream_get_contents($appOutput)); $installationManager = $composer->getInstallationManager(); $this->assertSame($expect, implode("\n", $installationManager->getTrace())); }
/** * reserveInstall * * @param ComposerFileWriter $writer * @param int $timeLimit */ protected function reserveOperation(ComposerFileWriter $writer, $timeLimit, $callback = null) { set_time_limit($timeLimit); ignore_user_abort(true); ini_set('allow_url_fopen', '1'); $memoryInBytes = function ($value) { $unit = strtolower(substr($value, -1, 1)); $value = (int) $value; switch ($unit) { case 'g': $value *= 1024; // no break (cumulative multiplier) // no break (cumulative multiplier) case 'm': $value *= 1024; // no break (cumulative multiplier) // no break (cumulative multiplier) case 'k': $value *= 1024; } return $value; }; $memoryLimit = trim(ini_get('memory_limit')); // Increase memory_limit if it is lower than 1GB if ($memoryLimit != -1 && $memoryInBytes($memoryLimit) < 1024 * 1024 * 1024) { ini_set('memory_limit', '1G'); } /** @var \Illuminate\Foundation\Application $app */ app()->terminating(function () use($writer, $callback) { $pid = getmypid(); Log::info("[plugin operation] start running composer run [pid={$pid}]"); // call `composer install` command programmatically $vendorName = PluginHandler::PLUGIN_VENDOR_NAME; $input = new ArrayInput(['command' => 'update', "--prefer-lowest", "--with-dependencies", '--working-dir' => base_path(), 'packages' => ["{$vendorName}/*"]]); $output = new BufferedOutput(); $application = new Application(); $application->setAutoExit(false); // prevent `$application->run` method from exitting the script if (!defined('__XE_PLUGIN_MODE__')) { define('__XE_PLUGIN_MODE__', true); } $code = $application->run($input, $output); $outputText = $output->fetch(); file_put_contents(storage_path('logs/plugin.log'), $outputText); if (is_callable($callback)) { $callback($code); } $writer->load(); if ($code !== 0) { $writer->set('xpressengine-plugin.operation.status', ComposerFileWriter::STATUS_FAILED); } else { $writer->set('xpressengine-plugin.operation.status', ComposerFileWriter::STATUS_SUCCESSED); } $writer->write(); Log::info("[plugin operation] plugin operation finished. [exit code: {$code}, memory usage: " . memory_get_usage() . "]"); }); }
/** * @dataProvider getIntegrationTests */ public function testIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectOutput, $expect, $expectResult) { if ($condition) { eval('$res = ' . $condition . ';'); if (!$res) { $this->markTestSkipped($condition); } } $io = new BufferIO('', OutputInterface::VERBOSITY_NORMAL, new OutputFormatter(false)); // Prepare for exceptions if (!is_int($expectResult)) { $normalizedOutput = rtrim(str_replace("\n", PHP_EOL, $expect)); $this->setExpectedException($expectResult, $normalizedOutput); } // Create Composer mock object according to configuration $composer = FactoryMock::create($io, $composerConfig); $this->tempComposerHome = $composer->getConfig()->get('home'); $jsonMock = $this->getMockBuilder('Composer\\Json\\JsonFile')->disableOriginalConstructor()->getMock(); $jsonMock->expects($this->any())->method('read')->will($this->returnValue($installed)); $jsonMock->expects($this->any())->method('exists')->will($this->returnValue(true)); $repositoryManager = $composer->getRepositoryManager(); $repositoryManager->setLocalRepository(new InstalledFilesystemRepositoryMock($jsonMock)); $lockJsonMock = $this->getMockBuilder('Composer\\Json\\JsonFile')->disableOriginalConstructor()->getMock(); $lockJsonMock->expects($this->any())->method('read')->will($this->returnValue($lock)); $lockJsonMock->expects($this->any())->method('exists')->will($this->returnValue(true)); if ($expectLock) { $actualLock = array(); $lockJsonMock->expects($this->atLeastOnce())->method('write')->will($this->returnCallback(function ($hash, $options) use(&$actualLock) { // need to do assertion outside of mock for nice phpunit output // so store value temporarily in reference for later assetion $actualLock = $hash; })); } $contents = json_encode($composerConfig); $locker = new Locker($io, $lockJsonMock, $repositoryManager, $composer->getInstallationManager(), $contents); $composer->setLocker($locker); $eventDispatcher = $this->getMockBuilder('Composer\\EventDispatcher\\EventDispatcher')->disableOriginalConstructor()->getMock(); $autoloadGenerator = $this->getMock('Composer\\Autoload\\AutoloadGenerator', array(), array($eventDispatcher)); $composer->setAutoloadGenerator($autoloadGenerator); $composer->setEventDispatcher($eventDispatcher); $installer = Installer::create($io, $composer); $application = new Application(); $application->get('install')->setCode(function ($input, $output) use($installer) { $installer->setDevMode(!$input->getOption('no-dev'))->setDryRun($input->getOption('dry-run'))->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs')); return $installer->run(); }); $application->get('update')->setCode(function ($input, $output) use($installer) { $installer->setDevMode(!$input->getOption('no-dev'))->setUpdate(true)->setDryRun($input->getOption('dry-run'))->setUpdateWhitelist($input->getArgument('packages'))->setWhitelistDependencies($input->getOption('with-dependencies'))->setPreferStable($input->getOption('prefer-stable'))->setPreferLowest($input->getOption('prefer-lowest'))->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs')); return $installer->run(); }); if (!preg_match('{^(install|update)\\b}', $run)) { throw new \UnexpectedValueException('The run command only supports install and update'); } $application->setAutoExit(false); $appOutput = fopen('php://memory', 'w+'); $result = $application->run(new StringInput($run), new StreamOutput($appOutput)); fseek($appOutput, 0); // Shouldn't check output and results if an exception was expected by this point if (!is_int($expectResult)) { return; } $output = str_replace("\r", '', $io->getOutput()); $this->assertEquals($expectResult, $result, $output . stream_get_contents($appOutput)); if ($expectLock) { unset($actualLock['hash']); unset($actualLock['content-hash']); unset($actualLock['_readme']); $this->assertEquals($expectLock, $actualLock); } $installationManager = $composer->getInstallationManager(); $this->assertSame(rtrim($expect), implode("\n", $installationManager->getTrace())); if ($expectOutput) { $this->assertStringMatchesFormat(rtrim($expectOutput), rtrim($output)); } }
<?php define('EXTRACT_DIRECTORY', realpath("../../")); if (file_exists(EXTRACT_DIRECTORY . '/vendor/autoload.php') == true) { echo "Extracted autoload already exists. Skipping phar extraction as presumably it's already extracted."; } else { $composerPhar = new Phar("composer.phar"); //php.ini setting phar.readonly must be set to 0 $composerPhar->extractTo(EXTRACT_DIRECTORY . '/vendor/'); } //This requires the phar to have been extracted successfully. require_once EXTRACT_DIRECTORY . '/vendor/vendor/autoload.php'; //Use the Composer classes use Composer\Console\Application; use Composer\Command\UpdateCommand; use Symfony\Component\Console\Input\ArrayInput; // change out of the webroot so that the vendors file is not created in // a place that will be visible to the intahwebz chdir('../'); //Create the commands $input = new ArrayInput(array('command' => 'install')); //Create the application and run it with the commands $application = new Application(); $application->run($input);
@ini_set('zlib.output_compression', 0); @ini_set('implicit_flush', 1); print "<pre>Installing GitSync dependencies for the first time ...\n\n"; flush(); if (!file_exists(EXTRACT_DIRECTORY . '/vendor/autoload.php') == true) { if (ini_get('phar.readonly')) { print "Error: unable to proceed. Please set phar.readonly = 0 in php.ini and then reload this page.</pre>"; exit; } $composerPhar = new Phar(__DIR__ . "/composer.phar"); $composerPhar->extractTo(EXTRACT_DIRECTORY); } //This requires the phar to have been extracted successfully. require_once EXTRACT_DIRECTORY . '/vendor/autoload.php'; //Use the Composer classes use Composer\Console\Application; //Create the commands $input = new Symfony\Component\Console\Input\StringInput('install'); $output = new Symfony\Component\Console\Output\StreamOutput(fopen('php://output', 'w')); //Create the application and run it with the commands $application = new Application(); $application->add(new Composer\Command\InstallCommand()); $application->setAutoExit(false); $application->run($input, $output); print "Cleaning up ...\n\n"; flush(); $fs = new \Symfony\Component\Filesystem\Filesystem(); $fs->remove(EXTRACT_DIRECTORY); print "Done. Please reload this page.</pre>"; flush(); exit;
/** * @param string $command * @param bool $quiet * @param array $arguments * @param InputInterface $input * @param OutputInterface $output * @return int */ protected static function callComposer($command, $quiet = true, array $arguments = [], InputInterface $input = null, OutputInterface $output = null) { self::setServerArguments($command, $quiet, $arguments); $application = new Application(); $application->setAutoExit(false); return $application->run($input, $output); }