/** * Compresses a string. * * @param string $content The content to compress * @param string $type The type of content, either "js" or "css" * @param array $options An indexed array of additional options * * @return string The compressed content */ protected function compress($content, $type, $options = array()) { $pb = new ProcessBuilder(array($this->javaPath, '-jar', $this->jarPath)); foreach ($options as $option) { $pb->add($option); } if (null !== $this->charset) { $pb->add('--charset')->add($this->charset); } if (null !== $this->lineBreak) { $pb->add('--line-break')->add($this->lineBreak); } // input and output files $tempDir = realpath(sys_get_temp_dir()); $hash = substr(sha1(time() . rand(11111, 99999)), 0, 7); $input = $tempDir . DIRECTORY_SEPARATOR . $hash . '.' . $type; $output = $tempDir . DIRECTORY_SEPARATOR . $hash . '-min.' . $type; file_put_contents($input, $content); $pb->add('-o')->add($output)->add($input); $proc = $pb->getProcess(); $code = $proc->run(); unlink($input); if (0 < $code) { if (file_exists($output)) { unlink($output); } throw FilterException::fromProcess($proc)->setInput($content); } elseif (!file_exists($output)) { throw new \RuntimeException('Error creating output file.'); } $retval = file_get_contents($output); unlink($output); return $retval; }
/** * Compresses a string. * * @param string $content The content to compress * @param string $type The type of content, either "js" or "css" * @param array $options An indexed array of additional options * * @return string The compressed content */ protected function compress($content, $type, $options = array()) { $pb = new ProcessBuilder(array($this->javaPath, '-jar', $this->jarPath)); foreach ($options as $option) { $pb->add($option); } if (null !== $this->charset) { $pb->add('--charset')->add($this->charset); } if (null !== $this->lineBreak) { $pb->add('--line-break')->add($this->lineBreak); } // input and output files $tempDir = realpath(sys_get_temp_dir()); $input = tempnam($tempDir, 'YUI-IN-'); $output = tempnam($tempDir, 'YUI-OUT-'); file_put_contents($input, $content); $pb->add('-o')->add($output)->add('--type')->add($type)->add($input); $proc = $pb->getProcess(); $code = $proc->run(); unlink($input); if (0 < $code) { if (file_exists($output)) { unlink($output); } throw FilterException::fromProcess($proc)->setInput($content); } if (!file_exists($output)) { throw new \RuntimeException('Error creating output file.'); } $retval = file_get_contents($output); unlink($output); return $retval; }
function execute($argv = array()) { $builder = new ProcessBuilder(); $builder->add($this->executable); if (@$argv[0] instanceof Response) { $builder->setInput(array_shift($argv)->getOutput()); } else { if (is_array(@$argv[0])) { $flags = array_shift($argv); foreach ($flags as $flag => $value) { $builder->add((strlen($flag) > 1 ? "--" : "-") . $flag); $value === true or $builder->add($value); } } } foreach ($argv as $a) { $builder->add($a); } $process = $builder->getProcess(); $process->run(); if (!$process->isSuccessful()) { $status = $process->getExitCode(); $commandLine = $process->getCommandLine(); throw new ErrorException("Command [{$commandLine}] failed with status [{$status}].", $status, $process->getErrorOutput()); } return new Response($process->getOutput(), $process->getErrorOutput()); }
/** * @param BinaryInterface $binary * * @throws ProcessFailedException * * @return BinaryInterface * * @see Implementation taken from Assetic\Filter\optipngFilter */ public function process(BinaryInterface $binary) { $type = strtolower($binary->getMimeType()); if (!in_array($type, array('image/png'))) { return $binary; } if (false === ($input = tempnam(sys_get_temp_dir(), 'imagine_optipng'))) { throw new \RuntimeException(sprintf('Temp file can not be created in "%s".', sys_get_temp_dir())); } $pb = new ProcessBuilder(array($this->optipngBin)); $pb->add('--o7'); $pb->add($input); if ($binary instanceof FileBinaryInterface) { copy($binary->getPath(), $input); } else { file_put_contents($input, $binary->getContent()); } $proc = $pb->getProcess(); $proc->run(); if (false !== strpos($proc->getOutput(), 'ERROR') || 0 !== $proc->getExitCode()) { unlink($input); throw new ProcessFailedException($proc); } $result = new Binary(file_get_contents($input), $binary->getMimeType(), $binary->getFormat()); unlink($input); return $result; }
public function filterDump(AssetInterface $asset) { $pb = new ProcessBuilder(array($this->jpegtranBin)); if ($this->optimize) { $pb->add('-optimize'); } if ($this->copy) { $pb->add('-copy')->add($this->copy); } if ($this->progressive) { $pb->add('-progressive'); } if (null !== $this->restart) { $pb->add('-restart')->add($this->restart); } $pb->add($input = tempnam(sys_get_temp_dir(), 'assetic_jpegtran')); file_put_contents($input, $asset->getContent()); $proc = $pb->getProcess(); $code = $proc->run(); unlink($input); if (0 < $code) { throw FilterException::fromProcess($proc)->setInput($asset->getContent()); } $asset->setContent($proc->getOutput()); }
/** * @param BinaryInterface $binary * @param array $options * * @throws ProcessFailedException * * @return BinaryInterface */ public function processWithConfiguration(BinaryInterface $binary, array $options) { $type = strtolower($binary->getMimeType()); if (!in_array($type, array('image/jpeg', 'image/jpg'))) { return $binary; } $pb = new ProcessBuilder(array($this->mozjpegBin)); // Places emphasis on DC $pb->add('-quant-table'); $pb->add(2); $transformQuality = array_key_exists('quality', $options) ? $options['quality'] : $this->quality; if ($transformQuality !== null) { $pb->add('-quality'); $pb->add($transformQuality); } $pb->add('-optimise'); // Favor stdin/stdout so we don't waste time creating a new file. $pb->setInput($binary->getContent()); $proc = $pb->getProcess(); $proc->run(); if (false !== strpos($proc->getOutput(), 'ERROR') || 0 !== $proc->getExitCode()) { throw new ProcessFailedException($proc); } $result = new Binary($proc->getOutput(), $binary->getMimeType(), $binary->getFormat()); return $result; }
public function filterDump(AssetInterface $asset) { $pb = new ProcessBuilder(array($this->pngoutBin)); if (null !== $this->color) { $pb->add('-c' . $this->color); } if (null !== $this->filter) { $pb->add('-f' . $this->filter); } if (null !== $this->strategy) { $pb->add('-s' . $this->strategy); } if (null !== $this->blockSplitThreshold) { $pb->add('-b' . $this->blockSplitThreshold); } $pb->add($input = tempnam(sys_get_temp_dir(), 'assetic_pngout')); file_put_contents($input, $asset->getContent()); $output = tempnam(sys_get_temp_dir(), 'assetic_pngout'); unlink($output); $pb->add($output .= '.png'); $proc = $pb->getProcess(); $code = $proc->run(); if (0 < $code) { unlink($input); throw FilterException::fromProcess($proc)->setInput($asset->getContent()); } $asset->setContent(file_get_contents($output)); unlink($input); unlink($output); }
/** * Run the asset through UglifyJs * * @see Assetic\Filter\FilterInterface::filterDump() */ public function filterDump(AssetInterface $asset) { $executables = array(); if ($this->nodeJsPath !== null) { $executables[] = $this->nodeJsPath; } $executables[] = $this->uglifyCssPath; $pb = new ProcessBuilder($executables); if ($this->expandVars) { $pb->add('--expand-vars'); } if ($this->uglyComments) { $pb->add('--ugly-comments'); } if ($this->cuteComments) { $pb->add('--cute-comments'); } // input and output files $input = tempnam(sys_get_temp_dir(), 'input'); file_put_contents($input, $asset->getContent()); $pb->add($input); $proc = $pb->getProcess(); $code = $proc->run(); unlink($input); if (127 === $code) { throw new \RuntimeException('Path to node executable could not be resolved.'); } if (0 < $code) { throw FilterException::fromProcess($proc)->setInput($asset->getContent()); } $asset->setContent($proc->getOutput()); }
/** * {@inheritdoc} */ public function process(array $files) { $tmpFile = Filename::temporaryFilename($this->filename); $processBuilder = new ProcessBuilder(); $processBuilder->add('tar'); if (!is_null($this->flags)) { $processBuilder->add($this->flags); } $processBuilder->add($tmpFile); /** * @var FileInterface $backup */ foreach ($files as $backup) { $processBuilder->add($backup->getPath()); } $process = $processBuilder->getProcess(); $process->run(); if (!$process->isSuccessful()) { throw new ProcessorException(sprintf('Unable to create gzip archive, reason: "%s".', $process->getErrorOutput())); } $this->getEventDispatcher()->addListener(BackupEvents::TERMINATE, function () use($tmpFile) { unlink($tmpFile); }); return array(File::fromLocal($tmpFile, dirname($tmpFile))); }
/** * Constructor. * * @param GitRepository $repository The git repository to work on. */ public function __construct(GitRepository $repository) { $this->repository = $repository; $this->processBuilder = new ProcessBuilder(); $this->processBuilder->setWorkingDirectory($repository->getRepositoryPath()); $this->processBuilder->add($this->repository->getConfig()->getGitExecutablePath()); $this->initializeProcessBuilder(); }
/** * Asynchronously start mediainfo operation. * Make call to MediaInfoCommandRunner::wait() afterwards to receive output. */ public function start() { $this->processBuilder->add($this->filePath); $this->processAsync = $this->processBuilder->getProcess(); // just takes advantage of symfony's underlying Process framework // process runs in background $this->processAsync->start(); }
/** * {@inheritdoc} */ protected function configureProcess(ProcessBuilder $processBuilder, Notification $notification) { $script = 'display notification "' . $notification->getBody() . '"'; if ($notification->getTitle()) { $script .= ' with title "' . $notification->getTitle() . '"'; } $processBuilder->add('-e'); $processBuilder->add($script); }
/** * @return string */ public function run() { $this->processBuilder->add($this->filePath); $process = $this->processBuilder->getProcess(); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } return $process->getOutput(); }
/** * 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; }
/** * {@inheritdoc} */ protected function configureProcess(ProcessBuilder $processBuilder, Notification $notification) { if ($notification->getIcon()) { $processBuilder->add('--icon'); $processBuilder->add($notification->getIcon()); } if ($notification->getTitle()) { $processBuilder->add($notification->getTitle()); } $processBuilder->add($notification->getBody()); }
/** * @return ProcessBuilder */ private function getCommandProcessBuilder() { $pb = new ProcessBuilder(); // PHP wraps the process in "sh -c" by default, but we need to control // the process directly. if (!defined('PHP_WINDOWS_VERSION_MAJOR')) { $pb->add('exec'); } $pb->add('php')->add($this->getContainer()->getParameter('kernel.root_dir') . '/console')->add('--env=test'); return $pb; }
/** * @return string * @throws \RuntimeException */ protected function executeCommand() { $this->processBuilder->setArguments(array()); $this->processBuilder->add($this->filePath); $process = $this->processBuilder->getProcess(); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } return $process->getOutput(); }
/** * Generate Thumbnail images with ImageMagick. * * @param string $imageData Image Data * @param int $height Height value * @param int $width Width value * @param int $type Type * * @return string Resized image data * * @throws \RuntimeException */ public function resize($imageData, $height, $width, $type = ElcodiMediaImageResizeTypes::FORCE_MEASURES) { if (ElcodiMediaImageResizeTypes::NO_RESIZE === $type) { return $imageData; } $originalFile = new File(tempnam(sys_get_temp_dir(), '_original')); $resizedFile = new File(tempnam(sys_get_temp_dir(), '_resize')); file_put_contents($originalFile, $imageData); //ImageMagick params $pb = new ProcessBuilder(); $pb->add($this->imageConverterBin)->add($originalFile->getPathname())->add('-profile')->add($this->profile); //Lanczos filter for reduction $pb->add('-filter')->add('Lanczos'); if ($width == 0) { $width = ''; } if ($height == 0) { $height = ''; } /** * Apply some filters depending on type of resizing. */ if ($width || $height) { $pb->add('-resize'); switch ($type) { case ElcodiMediaImageResizeTypes::INSET: $pb->add($width . 'x' . $height); break; case ElcodiMediaImageResizeTypes::INSET_FILL_WHITE: $pb->add($width . 'x' . $height)->add('-gravity')->add('center')->add('-extent')->add($width . 'x' . $height); break; case ElcodiMediaImageResizeTypes::OUTBOUNDS_FILL_WHITE: $pb->add($width . 'x' . $height . ''); break; case ElcodiMediaImageResizeTypes::OUTBOUND_CROP: $pb->add($width . 'x' . $height . '^')->add('-gravity')->add('center')->add('-crop')->add($width . 'x' . $height . '+0+0'); break; case ElcodiMediaImageResizeTypes::FORCE_MEASURES: default: $pb->add($width . 'x' . $height . '!'); break; } } $proc = $pb->add($resizedFile->getPathname())->getProcess(); $proc->run(); if (false !== strpos($proc->getOutput(), 'ERROR')) { throw new \RuntimeException($proc->getOutput()); } $imageContent = file_get_contents($resizedFile->getRealPath()); unlink($originalFile); unlink($resizedFile); return $imageContent; }
function it_throws_exception_if_the_process_fails(ProcessBuilder $processBuilder, Process $process, ContextInterface $context) { $processBuilder->add('--config=default')->shouldBeCalled(); $processBuilder->add('--verbose')->shouldBeCalled(); $processBuilder->add('fix')->shouldBeCalled(); $processBuilder->add('file1.php')->shouldBeCalled(); $processBuilder->setArguments(Argument::type('array'))->shouldBeCalled(); $processBuilder->getProcess()->willReturn($process); $process->getOutput()->shouldBeCalled(); $process->run()->shouldBeCalled(); $process->isSuccessful()->willReturn(false); $context->getFiles()->willReturn(new FilesCollection(array(new SplFileInfo('file1.php')))); $this->shouldThrow('GrumPHP\\Exception\\RuntimeException')->duringRun($context); }
/** * {@inheritdoc} */ public function fetch($scratchDir, LoggerInterface $logger) { $logger->info(sprintf('Running mysqldump for: %s', $this->database)); $processBuilder = new ProcessBuilder(); $processBuilder->setTimeout($this->timeout); if (null !== $this->sshHost && null !== $this->sshUser) { $processBuilder->add('ssh'); $processBuilder->add(sprintf('%s@%s', $this->sshUser, $this->sshHost)); $processBuilder->add(sprintf('-p %s', $this->sshPort)); } $processBuilder->add('mysqldump'); $processBuilder->add(sprintf('-u%s', $this->user)); if (null !== $this->host) { $processBuilder->add(sprintf('-h%s', $this->host)); } if (null !== $this->password) { $processBuilder->add(sprintf('-p%s', $this->password)); } $processBuilder->add($this->database); $process = $processBuilder->getProcess(); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } file_put_contents(sprintf('%s/%s.sql', $scratchDir, $this->database), $process->getOutput()); }
public function filterDump(AssetInterface $asset) { $is64bit = PHP_INT_SIZE === 8; $cleanup = array(); $pb = new ProcessBuilder(array_merge(array($this->javaPath), $is64bit ? array('-server', '-XX:+TieredCompilation') : array('-client', '-d32'), array('-jar', $this->jarPath))); if (null !== $this->timeout) { $pb->setTimeout($this->timeout); } if (null !== $this->compilationLevel) { $pb->add('--compilation_level')->add($this->compilationLevel); } if (null !== $this->jsExterns) { $cleanup[] = $externs = tempnam(sys_get_temp_dir(), 'assetic_google_closure_compiler'); file_put_contents($externs, $this->jsExterns); $pb->add('--externs')->add($externs); } if (null !== $this->externsUrl) { $cleanup[] = $externs = tempnam(sys_get_temp_dir(), 'assetic_google_closure_compiler'); file_put_contents($externs, file_get_contents($this->externsUrl)); $pb->add('--externs')->add($externs); } if (null !== $this->excludeDefaultExterns) { $pb->add('--use_only_custom_externs'); } if (null !== $this->formatting) { $pb->add('--formatting')->add($this->formatting); } if (null !== $this->useClosureLibrary) { $pb->add('--manage_closure_dependencies'); } if (null !== $this->warningLevel) { $pb->add('--warning_level')->add($this->warningLevel); } if (null !== $this->language) { $pb->add('--language_in')->add($this->language); } if (null !== $this->flagFile) { $pb->add('--flagfile')->add($this->flagFile); } $pb->add('--js')->add($cleanup[] = $input = tempnam(sys_get_temp_dir(), 'assetic_google_closure_compiler')); file_put_contents($input, $asset->getContent()); $proc = $pb->getProcess(); $code = $proc->run(); array_map('unlink', $cleanup); if (0 !== $code) { throw FilterException::fromProcess($proc)->setInput($asset->getContent()); } $asset->setContent($proc->getOutput()); }
protected function execute(InputInterface $input, OutputInterface $output) { if ($input->getOption('force')) { $this->doKill($output); return; } // first wait until all jobs are processed $pb = new ProcessBuilder(); // PHP wraps the process in "sh -c" by default, but we need to control // the process directly. if (!defined('PHP_WINDOWS_VERSION_MAJOR')) { $pb->add('exec'); } $pb->add('php')->add($this->getContainer()->getParameter('kernel.root_dir') . '/console')->add('supertag:gearman:monitor')->add('--env=' . $input->getOption('env')); if ($input->getOption('verbose')) { $pb->add('--verbose'); } $output->write("Waiting for all jobs to finish: "); $ns = $this->getContainer()->getParameter('supertag_gearman.namespace'); while (true) { $data = ''; $cb = function ($type, $text) use(&$data) { $data .= $text; }; // run the job command if (0 !== $pb->getProcess()->run($cb)) { throw new \RuntimeException("Failed while attempting to get gearman server stats"); } $lines = explode("\n", $data); // filter jobs by namespace $lines = array_filter($lines, function ($line) use($ns) { return strpos($line, $ns) !== false; }); // filter jobs active jobs $lines = array_filter($lines, function ($line) { $parts = explode(' ', trim($line)); return intval($parts[2]) !== 0 || intval($parts[4]) !== 0; }); if (!count($lines)) { $output->writeLn("\n"); $output->writeLn("There are no active jobs running, will kill workers.."); $this->doKill($output); break; } sleep(1); $output->write("."); } }
public function capture($file, $delay = 2, $device = null) { $processBuilder = new ProcessBuilder(array('imagesnap', '-q', '-w', $delay)); $processBuilder->add('-w')->add($delay); if ($device !== null) { // The device to use to capture the photo $processBuilder->add('-d')->add($device); } // Specify the file path to save the captured photo to $processBuilder->add($file); $process = $processBuilder->getProcess(); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } }
/** * @test */ public function shouldInheritEnvironmentVarsByDefault() { $pb = new ProcessBuilder(); $proc = $pb->add('foo')->getProcess(); $this->assertNull($proc->getEnv()); }
public function getStyles() { $builder = new ProcessBuilder(); $builder->setPrefix("{$this->bin}"); $builder->add("-f{$this->output}"); $builder->add("-S{$this->style}"); // Run the process $process = $builder->getProcess(); $process->run(); // Check the output if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } // Return the result return $process->getOutput(); }
public function testAddEnvironmentVariables() { $pb = new ProcessBuilder(); $env = array('foo' => 'bar', 'foo2' => 'bar2'); $proc = $pb->add('command')->setEnv('foo', 'bar2')->addEnvironmentVariables($env)->inheritEnvironmentVariables(false)->getProcess(); $this->assertSame($env, $proc->getEnv()); }
public function execute() { global $wgPygmentizePath; function lang_filter($val) { return preg_match('/^[a-zA-Z0-9\\-_]+$/', $val); } $header = '// Generated by ' . basename(__FILE__) . "\n\n"; $lexers = array(); $builder = new ProcessBuilder(); $builder->setPrefix($wgPygmentizePath); $process = $builder->add('-L')->add('lexer')->getProcess(); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } $output = $process->getOutput(); foreach (explode("\n", $output) as $line) { if (substr($line, 0, 1) === '*') { $newLexers = explode(', ', trim($line, "* :\n")); $lexers = array_merge($lexers, $newLexers); } } $lexers = array_unique($lexers); sort($lexers); $code = "<?php\n" . $header . 'return ' . var_export($lexers, true) . ";\n"; $code = preg_replace('/(\\d+ \\=\\>| (?=\\())/i', '', $code); $code = preg_replace("/^ +/m", "\t", $code); file_put_contents(__DIR__ . '/../SyntaxHighlight_GeSHi.lexers.php', $code); $this->output("Updated language list written to SyntaxHighlight_GeSHi.lexers.php\n"); }
protected function execute(InputInterface $input, OutputInterface $output) { // Direct access to the Container. /** @var Kengrabber $kg */ $kg = $this->getApplication()->getContainer(); $output->writeln("Build everything..."); $kg['monolog']->addDebug("Build everything..."); $commands = array("videolist:grab", "videolist:download", "cleanup", "verify", "render"); foreach ($commands as $command) { $builder = new ProcessBuilder(array("php", $_SERVER["SCRIPT_FILENAME"], $command)); if ($kg['debug'] === true) { $builder->add("--debug"); } $process = $builder->getProcess(); $process->setTimeout(0); $process->run(function ($type, $buffer) use($kg, $output) { if (Process::ERR === $type) { $output->write("<error>{$buffer}</error>"); } else { $output->write($buffer); } }); } $output->writeln("<info>Finished building...</info>"); }
function it_does_not_do_anything_if_there_are_no_keywords(ProcessBuilder $processBuilder) { $processBuilder->add(Argument::any())->shouldNotBeCalled(); $processBuilder->setArguments(Argument::any())->shouldNotBeCalled(); $processBuilder->getProcess()->shouldNotBeCalled(); $files = new FilesCollection(array(new SplFileInfo('file1.php'))); $this->run($files)->shouldBeNull(); }
public function __construct($source, $outputDirectory) { $this->source = $source; $this->outputDirectory = $outputDirectory; $builder = new ProcessBuilder(array(__DIR__ . '/../Resources/bin/rfc2html.pl')); $builder->add($this->source)->setWorkingDirectory($this->outputDirectory); $this->process = $builder->getProcess(); }