run() public method

run the process.
public run ( Closure | string | array $callback = null ) : integer
$callback Closure | string | array A PHP callback to run whenever there is some output available on STDOUT or STDERR
return integer The exit status code
Example #1
0
 /**
  * Méthode d'execution
  */
 public function run()
 {
     // Initialisation des loggers
     $this->getConfiguration()->initLoggers();
     // Initialisation du process
     $this->createProcess();
     try {
         // Lancement du process
         $this->process->run(function ($type, $buffer) {
             // On affiche le debug à l'écran pour s'assurer qu'aucune erreur
             // bloquante n'est présente et suivre l'exécution des longs process
             if ('err' === $type) {
                 echo 'ERR > ' . $buffer;
             } else {
                 echo 'OUT > ' . $buffer;
             }
         });
         // On récupère la sortie standard en cas de succès (STDOUT)
         if ($this->process->isSuccessful()) {
             $this->message .= $this->process->getOutput();
         } else {
             // On récupère la sortie standard en cas d'erreur (STDERR)
             $this->message .= $this->process->getErrorOutput();
         }
     } catch (\Exception $e) {
         $this->message .= $e->getMessage();
     }
     // Log du process
     $this->report();
     // Envoi des notifications
     $this->notify();
 }
 public function handle(GetResponseEvent $event)
 {
     if (null !== $this->securityContext->getToken()) {
         return;
     }
     $request = $event->getRequest();
     if (!$request->hasSession()) {
         throw new \RuntimeException('This authentication method requires a session.');
     }
     $cookies = array_intersect_key($request->cookies->all(), array_flip(array_filter(array_keys($request->cookies->all()), function ($input) {
         return strpos($input, 'wordpress_logged_in_') === 0;
     })));
     $logger = $this->logger;
     if (empty($cookies)) {
         return;
     }
     if (null !== $this->logger) {
         $this->logger->debug('Found eligible cookies prefixed with wordpress_logged_in_');
     }
     $script = call_user_func($this->script, InjectRequestGlobals::toSubprocessGlobals($request), "\$user = wp_get_current_user(); echo json_encode(\$user);");
     $process = new PhpProcess('<?php ' . $script, $this->documentRoot);
     $process->run();
     $output = $process->getOutput();
     $user = json_decode($output);
     // Attempt to load a WordPress user based on cookies for this site's domain.
     if (!$user || isset($user->ID) && $user->ID === 0) {
         return;
     }
     // Translate WordPress roles into Symfony Security component roles.
     $roles = array_map(function ($input) {
         return 'ROLE_WORDPRESS_' . strtoupper($input);
     }, $user->roles);
     $roles[] = 'ROLE_USER';
     // Generate token.
     $token = new WordpressUserToken($roles);
     $token->setUser($user->data->display_name);
     try {
         // Authorize token.
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         // To deny the authentication clear the token. This will redirect to the login page.
         // Make sure to only clear your token, not those of other authentication listeners.
         $token = $this->securityContext->getToken();
         if ($token instanceof WordpressUserToken) {
             $this->securityContext->setToken(null);
         }
         // Deny authentication with a '403 Forbidden' HTTP response
         $response = new Response();
         $response->setStatusCode(403);
         $event->setResponse($response);
     }
     // By default deny authorization
     $response = new Response();
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
 public function testWordpressBootstrap()
 {
     $app = $this->createApplication();
     $commandline = realpath('./vendor/wp-cli/wp-cli/bin/wp core config');
     $process = new \Symfony\Component\Process\Process($commandline);
     $process->setWorkingDirectory(realpath('./vendor/wordpress/wordpress'));
     $process->run();
     $output = $process->getOutput();
     $script = $app['php.wordpress36.bootstrap']();
     $process = new \Symfony\Component\Process\PhpProcess('<?php ' . $script, realpath('./vendor/wordpress/wordpress'));
     $process->setWorkingDirectory(realpath('./vendor/wordpress/wordpress'));
     $process->run();
     $output = $process->getOutput();
 }
 public function testDrupalBootstrap()
 {
     $app = $this->createApplication();
     $commandline = realpath('./vendor/bin/drush');
     $site = md5(microtime());
     $process = new \Symfony\Component\Process\Process($commandline . ' --yes site-install --db-url=sqlite://sites/' . $site . '/files/.ht.sqlite --sites-subdir=' . $site . ' --pipe');
     $process->setWorkingDirectory(realpath('./vendor/drupal/drupal'));
     $process->run();
     $output = $process->getOutput();
     $script = $app['php.drupal7.bootstrap']('http://' . $site . '/index.php', '', 'echo conf_path();');
     $process = new PhpProcess('<?php ' . $script, realpath('./vendor/drupal/drupal'));
     $process->run();
     $output = $process->getOutput();
     $this->assertEquals('sites/' . $site, $output);
 }
 function assertTranspile($yamlPath)
 {
     $input = new ArrayInput(array());
     $stream = fopen('php://memory', 'rw', false);
     $output = new StreamOutput($stream);
     $symfonyio = new SymfonyIO($input, $output);
     // Load and parse yaml
     $config = Yaml::parse(file_get_contents($yamlPath));
     if (!isset($config['stdout'])) {
         $this->fail('Stdout section not found in $yamlPath');
     }
     if (!isset($config['code'])) {
         $this->fail('Code section not found in $yamlPath');
     }
     // Create temp file for code to transpile
     $tmpPath = tempnam(sys_get_temp_dir(), 'transphpile');
     file_put_contents($tmpPath, "<?php\n" . $config['code']);
     // Transpile code and send to stdout
     $transpiler = new Transpile($symfonyio);
     $transpiler->transpile($tmpPath, '-');
     // unlink tmp file
     unlink($tmpPath);
     // Fetch php5 code written by transpiler
     rewind($stream);
     $php5 = stream_get_contents($stream);
     // Run php5 code
     $process = new PhpProcess($php5);
     $process->run();
     $stdout = $process->getOutput();
     $stderr = $process->getErrorOutput();
     // If we don't define stderr, there should not be any stderr output from our php5 file
     if (!empty($stderr) && !isset($config['stderr'])) {
         $this->fail('Error reported, but no stderr section found in $yamlPath');
     }
     // Check output
     $config['stdout'] = trim($config['stdout']);
     $this->assertRegExp('{' . $config['stdout'] . '}', $stdout, isset($config['name']) ? $config['name'] : "");
     // Check stderr if any
     if (isset($config['stderr'])) {
         $config['stderr'] = trim($config['stderr']);
         if (empty($stderr)) {
             $this->fail('stderr seems empty but should contain an error');
         }
         $this->assertRegExp('{' . $config['stderr'] . '}', $stderr, isset($config['name']) ? $config['name'] : "");
     }
 }
Example #6
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $filename = $input->getArgument('filename');
     if (null !== $filename) {
         $filename = $this->getSnippetsPath() . DIRECTORY_SEPARATOR . $filename;
         if (!file_exists($filename)) {
             throw new InvalidArgumentException(sprintf('file "%s" does not exist', $filename));
         }
         $snippets = array(new \SplFileInfo($filename));
         $nbSnippets = 1;
     } else {
         $snippets = $this->listSnippets(new Finder());
         $nbSnippets = count($snippets->getIterator()->getIterator());
     }
     $dialog = $this->getHelperSet()->get('dialog');
     $i = 0;
     foreach ($snippets as $snippet) {
         $snippetCode = file_get_contents($snippet->getRealpath());
         $output->writeln(sprintf('<info>DEMO [%d/%d]:</info> %s', $i + 1, $nbSnippets, $snippet->getRealPath()));
         $this->hr($output, 20);
         $output->writeln('<info>CODE :</info>');
         $output->writeln($snippetCode);
         $this->hr($output, 20);
         $dialog->askConfirmation($output, '<question>Press enter to see result</question>');
         $output->writeln('<info>RESULT :</info>');
         $process = new PhpProcess($snippetCode);
         $process->run();
         if (!$process->isSuccessful()) {
             $output->writeln(array('<error>Error ::</error>', $process->getErrorOutput()));
         }
         $output->writeln(array('<comment>Output ::</comment>', $process->getOutput()));
         $this->hr($output);
         $i++;
         if ($i < $nbSnippets) {
             $dialog->askConfirmation($output, '<question>Press enter to continue</question>');
             $output->writeln("");
         }
     }
 }
    /**
     * Makes a request in another process.
     *
     * @param Request $request A Request instance
     *
     * @return Response A Response instance
     *
     * @throws \RuntimeException When processing returns exit code
     */
    protected function doRequestInProcess($request)
    {
        // We set the TMPDIR because on Macs, the temp directory changes based on the user.
        $process = new PhpProcess($this->getScript($request), null, array('TMPDIR' => sys_get_temp_dir()));
        $process->run();

        if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
            throw new \RuntimeException($process->getErrorOutput());
        }

        return unserialize($process->getOutput());
    }
Example #8
0
 /**
  * Makes a request in another process.
  *
  * @param object $request An origin request instance
  *
  * @return object An origin response instance
  *
  * @throws \RuntimeException When processing returns exit code
  */
 protected function doRequestInProcess($request)
 {
     $process = new PhpProcess($this->getScript($request), null, null);
     $process->run();
     if (!$process->isSuccessful() || !preg_match('/^O\\:\\d+\\:/', $process->getOutput())) {
         throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
     }
     return unserialize($process->getOutput());
 }
Example #9
0
 /**
  * Makes a request in another process.
  *
  * @param object $request An origin request instance
  *
  * @return object An origin response instance
  *
  * @throws \RuntimeException When processing returns exit code
  */
 protected function doRequestInProcess($request)
 {
     // We set the TMPDIR (for Macs) and TEMP (for Windows), because on these platforms the temp directory changes based on the user.
     $process = new PhpProcess($this->getScript($request), null, array('TMPDIR' => sys_get_temp_dir(), 'TEMP' => sys_get_temp_dir()));
     $process->run();
     if (!$process->isSuccessful() || !preg_match('/^O\\:\\d+\\:/', $process->getOutput())) {
         throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
     }
     return unserialize($process->getOutput());
 }
 private function addFallbackAutoloader($phpunitXml)
 {
     $xml = simplexml_load_file($phpunitXml);
     $bootstrap = dirname($phpunitXml) . '/' . $xml['bootstrap'];
     // The bootstrap file does not exists, we can't run the tests
     if (!file_exists($bootstrap)) {
         return false;
     }
     $content = file_get_contents($bootstrap);
     $newPath = sprintf('require_once \'%s\';', realpath(__DIR__ . '/../../../app/autoload.php'));
     // The bundle is trying to run tests into a symfony project, change it!
     if (preg_match('#require(../){2,}app/autoload.php["\'];$#i', $content, $match)) {
         $content = str_replace($match[0], $newPath, $content);
     } else {
         $content .= "\n" . $newPath;
     }
     file_put_contents($bootstrap, $content);
     // test if the bootstrap script can be runned
     $process = new PhpProcess($bootstrap);
     $process->run(function ($type, $data) {
         echo $data;
     });
     if (!$process->isSuccessful()) {
         return false;
     }
     $xml->filter->whitelist->exclude->directory[] = dirname($phpunitXml) . '/vendor';
     $xml->filter->whitelist->exclude->directory[] = dirname($phpunitXml) . '/vendors';
     $xml->asXml($phpunitXml);
     return true;
 }
Example #11
0
 /**
  * Makes a request in another process.
  *
  * @param Request $request A Request instance
  *
  * @return Response A Response instance
  *
  * @throws \RuntimeException When processing returns exit code
  */
 protected function doRequestInProcess($request)
 {
     $process = new PhpProcess($this->getScript($request));
     $process->run();
     if (!$process->isSuccessful()) {
         throw new \RuntimeException($process->getErrorOutput());
     }
     return unserialize($process->getOutput());
 }
Example #12
0
    public function updateCanonicalConfigFile(Bundle $bundle)
    {
        self::$canonicalConfiguration = '';
        $gitRepo = $this->gitRepoManager->getRepo($bundle);
        /**
         * Currently there is only support for bundles whose configuration is stored exactly under Configuration.php
         */
        $relativePath = 'DependencyInjection' . DIRECTORY_SEPARATOR . 'Configuration.php';
        if ($gitRepo->hasFile($relativePath)) {
            $absolutePath = $gitRepo->getDir() . DIRECTORY_SEPARATOR . $relativePath;
            $tokens = token_get_all(file_get_contents($absolutePath));
            $start = false;
            $namespace = '';
            foreach ($tokens as $token) {
                if ($token == ';') {
                    break;
                }
                $tokenName = is_array($token) ? $token[0] : null;
                if (T_NAMESPACE === $tokenName) {
                    $start = true;
                    continue;
                }
                // Still not found namespace, skip this part of code
                if ($start === false) {
                    continue;
                }
                $tokenData = is_array($token) ? $token[1] : $token;
                if ($tokenData == ' ') {
                    continue;
                }
                $namespace .= $tokenData;
            }
            unset($tokens);
            $autoloaderPath = __DIR__ . '/../../../../../vendor/autoload.php';
            $script = <<<EOF
<?php

include_once "{$autoloaderPath}";
include_once "{$absolutePath}";

use Knp\\Bundle\\KnpBundlesBundle\\Github\\Repo;

\$configuration = new \\ReflectionClass("{$namespace}\\Configuration");
// only dumps if it implements interface ConfigurationInterface
if (in_array('Symfony\\Component\\Config\\Definition\\ConfigurationInterface', \$configuration->getInterfaceNames())) {
    \$configuration = \$configuration->newInstance();
    \$configuration = Repo::outputNode(\$configuration->getConfigTreeBuilder()->buildTree());

    echo Repo::\$canonicalConfiguration;
} else {
    echo '';
}

?>
EOF;
            // Workaround for bundles with external deps called in DI configuration, i.e. FOSRestBundle
            $process = new PhpProcess($script);
            $process->run();
            if ($process->isSuccessful()) {
                $bundle->setCanonicalConfig(Repo::$canonicalConfiguration = $process->getOutput());
            }
        }
    }
 protected function loadRaw($model, $parsePhp = false)
 {
     $content = file_get_contents(sprintf(__DIR__ . '/%s.yml', $model));
     if ($parsePhp) {
         $process = new PhpProcess($content);
         $process->run();
         if (!$process->isSuccessful()) {
             throw new \RuntimeException($process->getErrorOutput());
         }
         $content = $process->getOutput();
     }
     return Yaml::parse($content);
 }
Example #14
0
 /**
  * Makes a request in another process.
  *
  * @param object $request An origin request instance
  *
  * @return object An origin response instance
  *
  * @throws \RuntimeException When processing returns exit code
  * @see \Symfony\Component\BrowserKit\Client
  * @see \Symfony\Component\HttpKernel\Client
  */
 protected function doRequestInProcess($request)
 {
     // We set the TMPDIR (for Macs) and TEMP (for Windows), because on these platforms the temp directory changes based on the user.
     $process = new PhpProcess($this->getScript($request), $this->rootDir, array('TMPDIR' => sys_get_temp_dir(), 'TEMP' => sys_get_temp_dir()));
     $process->setPhpBinary('php-cgi');
     $process->run();
     // I think the second hcheck validates that the response is serialized, but that's not what we want here.
     //if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
     if (!$process->isSuccessful()) {
         throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
     }
     return $process->getOutput();
 }