Esempio n. 1
0
 /**
  * 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 . '/..']));
 }
 /**
  * Constructs class
  *
  * @param string $pathToComposerHome
  * @param string $pathToComposerJson
  * @param Application $consoleApplication
  * @param ConsoleArrayInputFactory $consoleArrayInputFactory
  * @param BufferedOutput $consoleOutput
  */
 public function __construct($pathToComposerHome, $pathToComposerJson, Application $consoleApplication = null, ConsoleArrayInputFactory $consoleArrayInputFactory = null, BufferedOutput $consoleOutput = null)
 {
     $this->consoleApplication = $consoleApplication ? $consoleApplication : new Application();
     $this->consoleArrayInputFactory = $consoleArrayInputFactory ? $consoleArrayInputFactory : new ConsoleArrayInputFactory();
     $this->consoleOutput = $consoleOutput ? $consoleOutput : new BufferedOutput();
     $this->composerJson = $pathToComposerJson;
     $this->composerHome = $pathToComposerHome;
     putenv('COMPOSER_HOME=' . $pathToComposerHome);
     $this->consoleApplication->setAutoExit(false);
 }
Esempio n. 3
0
 /**
  * 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;
 }
 /**
  * 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'));
 }
Esempio n. 5
0
 /**
  * @return Application
  */
 protected function createComposerApplication()
 {
     $composer = new Application();
     $composer->setAutoExit(false);
     $composer->setCatchExceptions(false);
     return $composer;
 }
Esempio n. 6
0
 /**
  * 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;
 }
Esempio n. 7
0
 private function setup()
 {
     $httpOk = array(200, 301, 302);
     umask(00);
     putenv('COMPOSER_HOME=' . $this->app['resources']->getPath('cache') . '/composer');
     // Since we output JSON most of the time, we do _not_ want notices or warnings.
     // Set the error reporting before initializing Composer, to suppress them.
     $oldErrorReporting = error_reporting(E_ERROR);
     // Create the Composer application object
     $this->composerapp = new ComposerApp();
     // Don't automatically exit after a command execution
     $this->composerapp->setAutoExit(false);
     // re-set error reporting to the value it should be.
     error_reporting($oldErrorReporting);
     if (!is_file($this->packageFile)) {
         $this->execute('init');
     }
     // Check to see if composer.json is writable
     if (is_file($this->packageFile) && !is_writable($this->packageFile)) {
         $this->messages[] = sprintf("The file '%s' is not writable. You will not be able to use this feature without changing the permissions.", $this->packageFile);
         $this->offline = true;
     }
     // Ping the extensions server to confirm connection
     $response = $this->ping($this->app['extend.site'], 'ping', true);
     if (!in_array($response, $httpOk)) {
         $this->messages[] = $this->app['extend.site'] . ' is unreachable.';
         $this->offline = true;
     }
     if ($this->offline) {
         $this->messages[] = 'Unable to install/update extensions!';
         return false;
     }
     $this->execute('config repositories.bolt composer ' . $this->app['extend.site'] . 'satis/');
     $jsonfile = file_get_contents($this->packageFile);
     $json = json_decode($jsonfile);
     $json->repositories->packagist = false;
     $json->{'minimum-stability'} = $this->app['config']->get('general/extensions/stability', 'stable');
     $json->{'prefer-stable'} = true;
     $json->config = array('discard-changes' => true, 'preferred-install' => 'dist');
     $basePackage = "bolt/bolt";
     $json->provide = new \stdClass();
     $json->provide->{$basePackage} = $this->app['bolt_version'];
     $json->scripts = array('post-package-install' => "Bolt\\Composer\\ExtensionInstaller::handle", 'post-package-update' => "Bolt\\Composer\\ExtensionInstaller::handle");
     $pathToWeb = $this->app['resources']->findRelativePath($this->app['resources']->getPath('extensions'), $this->app['resources']->getPath('web'));
     $json->extra = array('bolt-web-path' => $pathToWeb);
     $json->autoload = array('files' => array("installer.php"));
     // Write out the file, but only if it's actually changed, and if it's writable.
     if ($jsonfile !== json_encode($json, 128 | 64)) {
         file_put_contents($this->packageFile, json_encode($json, 128 | 64));
     }
     try {
         $json = json_decode(file_get_contents($this->packageRepo));
         $this->available = $json->packages;
     } catch (\Exception $e) {
         $this->messages[] = Trans::__('The Bolt extensions Repo at %repository% is currently unavailable. Check your connection and try again shortly.', array('%repository%' => $this->packageRepo));
         $this->available = array();
     }
 }
Esempio n. 8
0
 /**
  * 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);
 }
Esempio n. 9
0
 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();
 }
 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();
 }
Esempio n. 11
0
 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();
 }
Esempio n. 12
0
 /**
  * @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;
 }
 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');
     });
 }
Esempio n. 14
0
 /**
  * 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;
 }
Esempio n. 15
0
 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');
 }
Esempio n. 16
0
 /**
  * @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);
     }
 }
 /**
  * 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;
 }
 /**
  * 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;
     }
 }
Esempio n. 19
0
 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);
 }
Esempio n. 20
0
 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');
 }
Esempio n. 21
0
 private function runComposer(InputInterface $input)
 {
     $app = new Composer();
     $app->setAutoExit(false);
     return $app->run($input, $this->getOutputInterface()) == 0;
 }
Esempio n. 22
0
 /**
  * @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();
 }
Esempio n. 23
0
 /**
  * @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));
     }
 }
Esempio n. 24
0
 /**
  * 
  * @return \Composer\Console\Application
  */
 public function get_composer_application()
 {
     if ($this->get_path_to_composer_home()) {
         putenv('COMPOSER_HOME=' . $this->get_path_to_composer_home());
     }
     $application = new Application();
     $application->setAutoExit(false);
     return $application;
 }
Esempio n. 25
0
File: CLI.php Progetto: opis/colibri
 protected function instance()
 {
     $instance = new ComposerConsole();
     $instance->setAutoExit(false);
     return $instance;
 }
Esempio n. 26
0
 /**
  * @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()));
 }
Esempio n. 27
0
    /**
     * @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 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);
 }
Esempio n. 29
0
@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;
 /**
  * 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() . "]");
     });
 }