/**
  * @return false|string
  */
 public function getExecutablePath()
 {
     if (null === $this->executablePath) {
         $this->executablePath = $this->executableFinder->find();
     }
     return $this->executablePath;
 }
Example #2
0
 /**
  * Starts the server
  *
  * @param array $options
  * @return void
  */
 public function start(array $options)
 {
     $verbose = isset($options['verbose']) && $options['verbose'];
     if ($this->checkServer()) {
         $this->output->writeln("<error>Queue Manager is already running.</error>");
         return;
     }
     if ($verbose) {
         $this->output->writeln("<info>Queue Manager is starting.</info>");
     }
     $phpFinder = new PhpExecutableFinder();
     $phpPath = $phpFinder->find();
     if ($options['daemon']) {
         $command = $phpPath . ' app/console naroga:queue:start ' . ($verbose ? '-v' : '') . ' &';
         $app = new Process($command);
         $app->setTimeout(0);
         $app->start();
         $pid = $app->getPid();
         $this->memcache->replace('queue.lock', $pid);
         if ($verbose) {
             $this->output->writeln('<info>Queue Manager started with PID = ' . ($pid + 1) . '.</info>');
         }
         return;
     }
     $this->registerListeners($verbose);
     if ($verbose) {
         $pid = $this->memcache->get('queue.lock');
         $this->output->writeln('<info>Queue Manager started with PID = ' . $pid . '.</info>');
     }
     $this->resetServerConfig($options);
     $this->processQueue($options);
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $learning = $input->hasOption('learning') ? $input->getOption('learning') : false;
     $address = $this->validatePort($input->getArgument('address'));
     $finder = new PhpExecutableFinder();
     if (false === ($binary = $finder->find())) {
         $io->error($this->trans('commands.server.errors.binary'));
         return;
     }
     $router = $this->getRouterPath();
     $cli = sprintf('%s %s %s %s', $binary, '-S', $address, $router);
     if ($learning) {
         $io->commentBlock($cli);
     }
     $io->success(sprintf($this->trans('commands.server.messages.executing'), $binary));
     $processBuilder = new ProcessBuilder(explode(' ', $cli));
     $process = $processBuilder->getProcess();
     $process->setWorkingDirectory($this->appRoot);
     if ('\\' !== DIRECTORY_SEPARATOR && file_exists('/dev/tty') && is_readable('/dev/tty')) {
         $process->setTty('true');
     } else {
         $process->setTimeout(null);
     }
     $process->run();
     if (!$process->isSuccessful()) {
         $io->error($process->getErrorOutput());
     }
 }
 public function register(Application $app)
 {
     $app['task-manager.logger'] = $app->share(function (Application $app) {
         $logger = new $app['monolog.logger.class']('task-manager logger');
         $logger->pushHandler(new NullHandler());
         return $logger;
     });
     $app['task-manager'] = $app->share(function (Application $app) {
         $options = $app['task-manager.listener.options'];
         $manager = TaskManager::create($app['dispatcher'], $app['task-manager.logger'], $app['task-manager.task-list'], ['listener_protocol' => $options['protocol'], 'listener_host' => $options['host'], 'listener_port' => $options['port'], 'tick_period' => 1]);
         $manager->addSubscriber($app['ws.task-manager.broadcaster']);
         return $manager;
     });
     $app['task-manager.logger.configuration'] = $app->share(function (Application $app) {
         $conf = array_replace(['enabled' => true, 'level' => 'INFO', 'max-files' => 10], $app['conf']->get(['main', 'task-manager', 'logger'], []));
         $conf['level'] = defined('Monolog\\Logger::' . $conf['level']) ? constant('Monolog\\Logger::' . $conf['level']) : Logger::INFO;
         return $conf;
     });
     $app['task-manager.task-list'] = $app->share(function (Application $app) {
         $conf = $app['conf']->get(['registry', 'executables', 'php-conf-path']);
         $finder = new PhpExecutableFinder();
         $php = $finder->find();
         return new TaskList($app['EM']->getRepository('Phraseanet:Task'), $app['root.path'], $php, $conf);
     });
 }
Example #5
0
 /**
  * Actually execute this task
  *
  * @return \Phar
  */
 public function execute()
 {
     $to = $this->get('to');
     if (file_exists($to)) {
         $this->console->getFilesystem()->remove($to);
     }
     $executableFinder = new PhpExecutableFinder();
     $php = $executableFinder->find();
     $php .= ' -d phar.readonly=0';
     $code = "<?php\n";
     foreach (array('to', 'from', 'filter', 'cliStub', 'webStub', 'alias', 'metadata') as $var) {
         $value = $this->get($var);
         $code .= '$' . $var . " = unserialize('" . serialize($value) . "');\n";
     }
     $code .= '
     $phar = new \\Phar($to);
     $phar->buildFromDirectory($from, $filter);
     if ($cliStub || $webStub) {
         $phar->setStub($phar->createDefaultStub($cliStub, $webStub));
     }
     if ($alias) {
         $phar->setAlias($alias);
     }
     if ($metadata) {
         $phar->setMetadata($metadata);
     }
     ?>';
     $process = $this->console->createProcess($php);
     $process->setInput($code);
     $process->run();
     return new \Phar($to);
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $learning = $input->hasOption('learning') ? $input->getOption('learning') : false;
     $address = $input->getArgument('address');
     if (false === strpos($address, ':')) {
         $address = sprintf('%s:8088', $address);
     }
     $finder = new PhpExecutableFinder();
     if (false === ($binary = $finder->find())) {
         $io->error($this->trans('commands.server.errors.binary'));
         return;
     }
     $router = $this->getRouterPath();
     $cli = sprintf('%s %s %s %s', $binary, '-S', $address, $router);
     if ($learning) {
         $io->commentBlock($cli);
     }
     $io->success(sprintf($this->trans('commands.server.messages.executing'), $binary));
     $processBuilder = new ProcessBuilder(explode(' ', $cli));
     $process = $processBuilder->getProcess();
     $process->setWorkingDirectory($this->get('site')->getRoot());
     $process->setTty('true');
     $process->run();
     if (!$process->isSuccessful()) {
         $io->error($process->getErrorOutput());
     }
 }
Example #7
0
 /**
  * @param string $router
  * @param array $env
  * @return UrlScript
  * @throws \RuntimeException
  */
 public function start($router, $env = array())
 {
     $this->slaughter();
     static $port;
     if ($port === NULL) {
         do {
             $port = rand(8000, 10000);
             if (isset($lock)) {
                 @fclose($lock);
             }
             $lock = fopen(dirname(TEMP_DIR) . '/http-server-' . $port . '.lock', 'w');
         } while (!flock($lock, LOCK_EX | LOCK_NB, $wouldBlock) || $wouldBlock);
     }
     $ini = NULL;
     if (($pid = getmypid()) && ($myprocess = `ps -ww -fp {$pid}`)) {
         $fullArgs = preg_split('~[ \\t]+~', explode("\n", $myprocess)[1], 8)[7];
         if (preg_match('~\\s\\-c\\s(?P<ini>[^ \\t]+)\\s~i', $fullArgs, $m)) {
             $ini = '-c ' . $m['ini'] . ' -n';
         }
     }
     $executable = new PhpExecutableFinder();
     $cmd = sprintf('%s %s -d register_argc_argv=on -t %s -S %s:%d %s', escapeshellcmd($executable->find()), $ini, escapeshellarg(dirname($router)), $ip = '127.0.0.1', $port, escapeshellarg($router));
     if (!is_resource($this->process = proc_open($cmd, self::$spec, $this->pipes, dirname($router), $env))) {
         throw new HttpServerException("Could not execute: `{$cmd}`");
     }
     sleep(1);
     // give him some time to boot up
     $status = proc_get_status($this->process);
     if (!$status['running']) {
         throw new HttpServerException("Failed to start php server: " . stream_get_contents($this->pipes[2]));
     }
     $this->url = new UrlScript('http://' . $ip . ':' . $port);
     return $this->getUrl();
 }
Example #8
0
 /**
  * Class constructor
  *
  * @param TraceableEventDispatcher $dispatcher
  * @param AntiDogPileMemcache $memcache
  */
 public function __construct(TraceableEventDispatcher $dispatcher, AntiDogPileMemcache $memcache)
 {
     $this->eventDispatcher = $dispatcher;
     $this->memcache = $memcache;
     $phpFinder = new PhpExecutableFinder();
     $this->phpPath = $phpFinder->find();
 }
Example #9
0
 /**
  * Creates a new runner.
  *
  * @param string|null $binDir The path to Composer's "bin-dir".
  */
 public function __construct($binDir = null)
 {
     $phpFinder = new PhpExecutableFinder();
     if (!($php = $phpFinder->find())) {
         throw new RuntimeException('The "php" command could not be found.');
     }
     $puliFinder = new ExecutableFinder();
     // Search:
     // 1. in the current working directory
     // 2. in Composer's "bin-dir"
     // 3. in the system path
     $searchPath = array_merge(array(getcwd()), (array) $binDir);
     // Search "puli.phar" in the PATH and the current directory
     if (!($puli = $puliFinder->find('puli.phar', null, $searchPath))) {
         // Search "puli" in the PATH and Composer's "bin-dir"
         if (!($puli = $puliFinder->find('puli', null, $searchPath))) {
             throw new RuntimeException('The "puli"/"puli.phar" command could not be found.');
         }
     }
     if (Path::hasExtension($puli, '.bat', true)) {
         $this->puli = $puli;
     } else {
         $this->puli = $php . ' ' . $puli;
     }
 }
 public function register(Application $app)
 {
     $app['plugins.import-strategy'] = $app->share(function (Application $app) {
         return new ImportStrategy();
     });
     $app['plugins.autoloader-generator'] = $app->share(function (Application $app) {
         return new AutoloaderGenerator($app['plugin.path']);
     });
     $app['plugins.assets-manager'] = $app->share(function (Application $app) {
         return new AssetsManager($app['filesystem'], $app['plugin.path'], $app['root.path']);
     });
     $app['plugins.composer-installer'] = $app->share(function (Application $app) {
         $phpBinary = $app['conf']->get(['main', 'binaries', 'php_binary'], null);
         if (!is_executable($phpBinary)) {
             $finder = new PhpExecutableFinder();
             $phpBinary = $finder->find();
         }
         return new ComposerInstaller($app['composer-setup'], $app['plugin.path'], $phpBinary);
     });
     $app['plugins.explorer'] = $app->share(function (Application $app) {
         return new PluginsExplorer($app['plugin.path']);
     });
     $app['plugins.importer'] = $app->share(function (Application $app) {
         return new Importer($app['plugins.import-strategy'], ['plugins.importer.folder-importer' => $app['plugins.importer.folder-importer']]);
     });
     $app['plugins.importer.folder-importer'] = $app->share(function (Application $app) {
         return new FolderImporter($app['filesystem']);
     });
 }
Example #11
0
 /**
  * @param string $hostname The hostname to register
  */
 public function createHostname($hostname)
 {
     $content = file_get_contents($this->file);
     $lines = explode("\n", $content);
     $matchHostLine = $this->findLine($lines, function ($ip, $hostnames) use($hostname) {
         return in_array($hostname, $hostnames);
     });
     if ($matchHostLine) {
         return;
     }
     $f = new PhpExecutableFinder();
     $php = $f->find();
     if (!$php) {
         throw new \RuntimeException("Failed to determine PHP interpreter");
     }
     $scriptFile = tempnam(sys_get_temp_dir(), 'fix-hosts-php-');
     file_put_contents($scriptFile, "<?php\n" . $this->createScript($content, $lines, $hostname));
     if ($this->isSudo()) {
         echo "Register host \"{$hostname}\" ({$this->ip}) in \"{$this->file}\" via helper \"{$scriptFile}\".\n";
         passthru("sudo  " . escapeshellarg($php) . " " . escapeshellarg($scriptFile), $return);
     } else {
         passthru(escapeshellcmd($php) . " " . escapeshellarg($scriptFile), $return);
     }
     if ($return) {
         throw new \RuntimeException("Failed to update hosts file ({$this->file}) with ({$this->ip} {$hostname}) [{$scriptFile}]");
     }
     unlink($scriptFile);
 }
Example #12
0
 /**
  * Constructor.
  *
  * @param string $environment
  * @param $consoleDir
  */
 public function __construct($consoleDir, $environment)
 {
     $this->consoleDir = $consoleDir;
     $this->environment = $environment;
     $finder = new PhpExecutableFinder();
     $this->phpExecutable = $finder->find();
 }
Example #13
0
 protected function setUp()
 {
     $finder = new PhpExecutableFinder();
     $this->php = escapeshellcmd($finder->find());
     $this->launcher = new ProcessLauncher();
     // Speed up the tests
     $this->launcher->setCheckInterval(0.01);
 }
 private function getPhp()
 {
     $phpFinder = new PhpExecutableFinder();
     if (!($phpPath = $phpFinder->find())) {
         throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again');
     }
     return $phpPath;
 }
Example #15
0
 /**
  * Constructor.
  *
  * @param string $script The PHP script to run (as a string)
  * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  * @param int $timeout The timeout in seconds
  * @param array $options An array of options for proc_open
  */
 public function __construct($script, $cwd = null, array $env = null, $timeout = 60, array $options = array())
 {
     $executableFinder = new PhpExecutableFinder();
     if (false === ($php = $executableFinder->find())) {
         $php = null;
     }
     parent::__construct($php, $cwd, $env, $script, $timeout, $options);
 }
Example #16
0
 protected static function getPhp($includeArgs = true)
 {
     $phpFinder = new PhpExecutableFinder();
     if (!($phpPath = $phpFinder->find($includeArgs))) {
         throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again');
     }
     return $phpPath;
 }
 /**
  * @param string         $script  Passed to php binary
  * @param string|null    $cwd     The working directory or null to use the working dir of the current PHP process
  * @param array|null     $env     The environment variables or null to inherit
  * @param int|float|null $timeout The timeout in seconds or null to disable
  */
 public function __construct($script, $cwd = null, array $env = null, $timeout = null)
 {
     $phpFinder = new PhpExecutableFinder();
     // By telling PHP to log errors without having a log file, PHP will write
     // errors to STDERR in a specific format (each line is prefixed with PHP).
     $commandline = sprintf('%s -d log_errors=1 -d error_log=NULL %s', $phpFinder->find(), $script);
     parent::__construct($commandline, $cwd, $env, null, $timeout);
 }
 /**
  * @see \Symfony\Component\Process\PhpExecutableFinder::find
  */
 public function find($includeArgs = true)
 {
     $php = getenv('ORO_PHP_PATH');
     if ($php && is_executable($php)) {
         return $php;
     }
     return $this->finder->find($includeArgs);
 }
 public function testCreateWithCustomBinary()
 {
     $finder = new PhpExecutableFinder();
     $php = $finder->find();
     $driver = ComposerDriver::create(['composer.binaries' => $php]);
     $this->assertInstanceOf('Alchemy\\Phrasea\\Command\\Developer\\Utils\\ComposerDriver', $driver);
     $this->assertEquals($php, $driver->getProcessBuilderFactory()->getBinary());
 }
Example #20
0
 public function testGetPath()
 {
     $expected = escapeshellarg('foo');
     $this->driver->expects($this->once())->method('find')->will($this->returnValue('foo'));
     $this->assertEquals($expected, $this->finder->getPath());
     // test lazy load
     $this->assertEquals($expected, $this->finder->getPath());
 }
 /**
  * Prepares test folders in the temporary directory.
  *
  * @BeforeScenario
  */
 public function prepareProcess()
 {
     $phpFinder = new PhpExecutableFinder();
     if (false === ($php = $phpFinder->find())) {
         throw new \RuntimeException('Unable to find the PHP executable.');
     }
     $this->phpBin = $php;
     $this->process = new Process(null);
 }
 /**
  * tests find() with the env var PHP_PATH.
  */
 public function testFindArguments()
 {
     $f = new PhpExecutableFinder();
     if (defined('HHVM_VERSION')) {
         $this->assertEquals($f->findArguments(), array('--php'), '::findArguments() returns HHVM arguments');
     } else {
         $this->assertEquals($f->findArguments(), array(), '::findArguments() returns no arguments');
     }
 }
Example #23
0
 protected static function executeCheck(CommandEvent $event, $appDir)
 {
     $phpFinder = new PhpExecutableFinder();
     $php = escapeshellarg($phpFinder->find());
     $check = escapeshellarg($appDir . '/check.php');
     $process = new Process($php . ' ' . $check);
     $process->run(function ($type, $buffer) use($event) {
         $event->getIO()->write($buffer, false);
     });
 }
 public function __construct()
 {
     $phpCliFinder = new PhpExecutableFinder();
     if (false === ($phpCli = $phpCliFinder->find())) {
         throw new \RuntimeException('Unable to find the PHP executable.');
     }
     $this->phpCli = $phpCli;
     $this->processCommand = '';
     $this->filesystem = new Filesystem();
 }
Example #25
0
 /**
  * @throws \RuntimeException
  *
  * @return string
  */
 public function getPath()
 {
     if (!$this->php_path) {
         if (!($this->php_path = $this->finder->find())) {
             throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again');
         }
         $this->php_path = escapeshellarg($this->php_path);
     }
     return $this->php_path;
 }
 /**
  * Launches a command.
  * If '--process-isolation' parameter is specified the command will be launched as a separate process.
  * In this case you can parameter '--process-timeout' to set the process timeout
  * in seconds. Default timeout is 60 seconds.
  * If '--ignore-errors' parameter is specified any errors are ignored;
  * otherwise, an exception is raises if an error happened.
  *
  * @param string $command
  * @param array  $params
  * @return CommandExecutor
  * @throws \RuntimeException if command failed and '--ignore-errors' parameter is not specified
  */
 public function runCommand($command, $params = array())
 {
     $params = array_merge(array('command' => $command, '--no-debug' => true), $params);
     if ($this->env && $this->env !== 'dev') {
         $params['--env'] = $this->env;
     }
     $ignoreErrors = false;
     if (array_key_exists('--ignore-errors', $params)) {
         $ignoreErrors = true;
         unset($params['--ignore-errors']);
     }
     if (array_key_exists('--process-isolation', $params)) {
         unset($params['--process-isolation']);
         $phpFinder = new PhpExecutableFinder();
         $php = $phpFinder->find();
         $pb = new ProcessBuilder();
         $pb->add($php)->add($_SERVER['argv'][0]);
         if (array_key_exists('--process-timeout', $params)) {
             $pb->setTimeout($params['--process-timeout']);
             unset($params['--process-timeout']);
         }
         foreach ($params as $param => $val) {
             if ($param && '-' === $param[0]) {
                 if ($val === true) {
                     $pb->add($param);
                 } elseif (is_array($val)) {
                     foreach ($val as $value) {
                         $pb->add($param . '=' . $value);
                     }
                 } else {
                     $pb->add($param . '=' . $val);
                 }
             } else {
                 $pb->add($val);
             }
         }
         $process = $pb->inheritEnvironmentVariables(true)->getProcess();
         $output = $this->output;
         $process->run(function ($type, $data) use($output) {
             $output->write($data);
         });
         $ret = $process->getExitCode();
     } else {
         $this->application->setAutoExit(false);
         $ret = $this->application->run(new ArrayInput($params), $this->output);
     }
     if (0 !== $ret) {
         if ($ignoreErrors) {
             $this->output->writeln(sprintf('<error>The command terminated with an error code: %u.</error>', $ret));
         } else {
             throw new \RuntimeException(sprintf('The command terminated with an error status: %u.', $ret));
         }
     }
     return $this;
 }
Example #27
0
 /**
  * @param string|null $executable PHP executable, null for autodetection
  */
 public function __construct($executable = null)
 {
     if (null === $executable) {
         $executableFinder = new PhpExecutableFinder();
         $executable = $executableFinder->find(false);
         if (false === $executable) {
             throw new UnavailableLinterException();
         }
     }
     $this->executable = $executable;
 }
Example #28
0
 protected static function executeBuildBootstrap($appDir)
 {
     $phpFinder = new PhpExecutableFinder();
     $php = escapeshellarg($phpFinder->find());
     $cmd = escapeshellarg(__DIR__ . '/../Resources/bin/build_bootstrap.php');
     $appDir = escapeshellarg($appDir);
     $process = new Process($php . ' ' . $cmd . ' ' . $appDir);
     $process->run(function ($type, $buffer) {
         echo $buffer;
     });
 }
 public static function setUpBeforeClass()
 {
     if (version_compare(PHP_VERSION, '5.4.0', '<')) {
         self::markTestSkipped('PHP Webserver is available from PHP 5.4');
     }
     $phpFinder = new PhpExecutableFinder();
     self::$webserver = ProcessBuilder::create(array('exec', $phpFinder->find(), '-S', sprintf('localhost:%d', WEBSERVER_PORT), '-t', __DIR__ . DIRECTORY_SEPARATOR . 'Fixtures'))->getProcess();
     self::$webserver->start();
     usleep(100000);
     self::$websererPortLength = strlen(WEBSERVER_PORT);
 }
 /**
  * Creates a new runner.
  *
  * @param string|null $binDir The path to Composer's "bin-dir".
  */
 public function __construct($binDir = null)
 {
     $phpFinder = new PhpExecutableFinder();
     if (!($php = $phpFinder->find())) {
         throw new RuntimeException('The "php" command could not be found.');
     }
     $finder = new ExecutableFinder();
     // Search:
     // 1. in the current working directory
     // 2. in Composer's "bin-dir"
     // 3. in the system path
     $searchPath = array_merge(array(getcwd()), (array) $binDir);
     // Search "puli.phar" in the PATH and the current directory
     if (!($puli = $this->find('puli.phar', $searchPath, $finder))) {
         // Search "puli" in the PATH and Composer's "bin-dir"
         if (!($puli = $this->find('puli', $searchPath, $finder))) {
             throw new RuntimeException('The "puli"/"puli.phar" command could not be found.');
         }
     }
     // Fix slashes
     $php = strtr($php, '\\', '/');
     $puli = strtr($puli, '\\', '/');
     $content = file_get_contents($puli, null, null, -1, 18);
     if ($content === '#!/usr/bin/env php' || 0 === strpos($content, '<?php')) {
         $this->puli = ProcessUtils::escapeArgument($php) . ' ' . ProcessUtils::escapeArgument($puli);
     } else {
         $this->puli = ProcessUtils::escapeArgument($puli);
     }
 }