/** * @group legacy */ public function testLegacyInputOptionDefinitionInConstructor() { $this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED); $definition = new InputDefinition(array(new InputOption('foo', null, InputOption::VALUE_REQUIRED))); $input = new StringInput('--foo=bar', $definition); $this->assertEquals('bar', $input->getOption('foo')); }
protected function executeCommand($command) { // Cache can not be warmed up as classes can not be redefined during one request if (preg_match('/^cache:clear/', $command)) { $command .= ' --no-warmup'; } $input = new StringInput($command); $input->setInteractive(false); $output = new StringOutput(); $formatter = $output->getFormatter(); $formatter->setDecorated(true); $output->setFormatter(new HtmlOutputFormatterDecorator($formatter)); $application = $this->getApplication($input); $application->setAutoExit(false); // Some commands (i.e. doctrine:query:dql) dump things out instead of returning a value ob_start(); $errorCode = $application->run($input, $output); // So, if the returned output is empty if (!($result = $output->getBuffer())) { $result = ob_get_contents(); // We replace it by the catched output } ob_end_clean(); return array('input' => $command, 'output' => $result, 'environment' => $this->getKernel($input)->getEnvironment(), 'error_code' => $errorCode); }
public function run(InputInterface $input, OutputInterface $output) { // extract real command name $tokens = preg_split('{\\s+}', $input->__toString()); $args = array(); foreach ($tokens as $token) { if ($token && $token[0] !== '-') { $args[] = $token; if (count($args) >= 2) { break; } } } // show help for this command if no command was found if (count($args) < 2) { return parent::run($input, $output); } // change to global dir $config = Factory::createConfig(); chdir($config->get('home')); $this->getIO()->writeError('<info>Changed current directory to ' . $config->get('home') . '</info>'); // create new input without "global" command prefix $input = new StringInput(preg_replace('{\\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\\b}', '', $input->__toString(), 1)); $this->getApplication()->resetComposer(); return $this->getApplication()->run($input, $output); }
public function execAction($_format = 'json') { chdir($this->container->getParameter('kernel.root_dir') . '/..'); $request = $this->get('request'); $command = $request->request->get('command'); # Cache can not be warmed up as classes can not be redefined during one request if (preg_match('/^cache:clear/', $command)) { $command .= ' --no-warmup'; } $input = new StringInput($command); $input->setInteractive(FALSE); $output = new StringOutput(); $formatter = $output->getFormatter(); $formatter->setDecorated(true); $formatter->setStyle('error', new HtmlOutputFormatterStyle('white', 'red')); $formatter->setStyle('info', new HtmlOutputFormatterStyle('green')); $formatter->setStyle('comment', new HtmlOutputFormatterStyle('yellow')); $formatter->setStyle('question', new HtmlOutputFormatterStyle('black', 'cyan')); $output->setFormatter(new HtmlOutputFormatterDecorator($formatter)); $application = $this->getApplication($input); $application->setAutoExit(FALSE); // Some commands (i.e. doctrine:query:dql) dump things out instead of returning a value // Looks like a hack, but no way to do this differently ob_start(); $application->run($input, $output); $dumped = ob_get_contents(); // We catch it and concatenate it to the output ob_end_clean(); return $this->render('CoreSphereConsoleBundle:Console:result.' . $_format . '.twig', array('input' => $command, 'output' => $output->getBuffer() . $dumped, 'environment' => $this->getKernel($input)->getEnvironment())); }
public function testInputOptionWithGivenString() { $definition = new InputDefinition(array(new InputOption('foo', null, InputOption::VALUE_REQUIRED))); $input = new StringInput('--foo=bar', $definition); $actual = $input->getOption('foo'); $this->assertEquals('bar', $actual); }
/** * @param string $input * @param int $verbosity * @param OutputFormatterInterface|null $formatter */ public function __construct($input = '', $verbosity = StreamOutput::VERBOSITY_NORMAL, OutputFormatterInterface $formatter = null) { $input = new StringInput($input); $input->setInteractive(false); $output = new StreamOutput(fopen('php://memory', 'rw'), $verbosity, $formatter ? $formatter->isDecorated() : false, $formatter); parent::__construct($input, $output, new HelperSet(array())); }
private function runCommandsCommand(OutputInterface $output = null) { $input = new StringInput('modera:upgrade --run-commands ' . __DIR__ . '/versions.json'); $input->setInteractive(false); $app = $this->getApplication(); $result = $app->run($input, $output ?: new NullOutput()); $this->assertEquals(0, $result); }
/** * @When /^I run "([^"]*)" command$/ */ public function iRunCommand($cmd_line) { $input = new StringInput($cmd_line); $command = $this->application->find($input->getFirstArgument('command')); $input = new StringInput($cmd_line, $command->getDefinition()); $this->output = new StreamOutput(fopen('php://memory', 'w', false)); $command->run($input, $this->output); }
public function createStringInput($testCommandline) { $input = new StringInput($testCommandline); $optionDefinitions = [new InputArgument('unused', InputArgument::REQUIRED), new InputOption(FormatterOptions::FORMAT, null, InputOption::VALUE_REQUIRED), new InputOption(FormatterOptions::TABLE_STYLE, null, InputOption::VALUE_REQUIRED), new InputOption(FormatterOptions::FIELD, null, InputOption::VALUE_REQUIRED), new InputOption(FormatterOptions::FIELDS, null, InputOption::VALUE_REQUIRED), new InputOption(FormatterOptions::INCLUDE_FIELD_LABELS, null, InputOption::VALUE_NONE), new InputOption(FormatterOptions::ROW_LABELS, null, InputOption::VALUE_REQUIRED), new InputOption(FormatterOptions::FIELD_LABELS, null, InputOption::VALUE_REQUIRED), new InputOption(FormatterOptions::DEFAULT_FORMAT, null, InputOption::VALUE_REQUIRED), new InputOption(FormatterOptions::DEFAULT_FIELDS, null, InputOption::VALUE_REQUIRED), new InputOption(FormatterOptions::LIST_ORIENTATION, null, InputOption::VALUE_NONE)]; $definition = new InputDefinition($optionDefinitions); $input->bind($definition); return $input; }
/** * Get the command from the current input, takes aliases into account. * * @param string $input * The raw input * * @return string|NULL * The current command. */ protected function getCommandFromInput($input) { // Remove the alias from the start of the string before parsing and // returning the command. Essentially, when choosing a command, we're // ignoring the site alias. $input = preg_replace('|^\\@[^\\s]+|', '', $input); $input = new StringInput($input); return $input->getFirstArgument(); }
/** * @param array $input * * @return integer */ public function run($input = array()) { $this->input = new ArrayInput((array) $input); $this->input->setInteractive(false); $this->output = new StreamOutput(fopen('php://memory', 'r+', false)); $inputStream = $this->getInputStream(); rewind($inputStream); $this->application->getHelperSet()->get('dialog')->setInputStream($inputStream); return $this->application->doRun($this->input, $this->output); }
public function testGetCustomFacts() { $mock = $this->getMockForAbstractClass('SugarCli\\Console\\Command\\Inventory\\AbstractInventoryCommand', array('test')); $input = new StringInput('--custom-fact="foo:bar" --custom-fact "baz.foo:bar" --custom-fact "baz.test:a"'); $input->bind($mock->getDefinition()); $expected = 'bar'; $this->assertEquals($expected, $mock->getCustomFacts($input, 'foo')); $expected = array('foo' => 'bar', 'test' => 'a'); $this->assertEquals($expected, $mock->getCustomFacts($input, 'baz')); $this->assertEquals(array(), $mock->getCustomFacts($input, 'test')); }
/** * Run an Artisan console command by name. * * @param string $command * @param array $parameters * * @return int */ public function call($command, array $parameters = []) { $this->lastOutput = $this->getBufferedOutput(); $this->setCatchExceptions(false); $command = $command . '' . implode(' ', $parameters); $input = new StringInput($command); $input->setInteractive(false); $result = $this->run($input, $this->lastOutput); $this->setCatchExceptions(true); return $result; }
public function testInputOptionWithGivenString() { $definition = new InputDefinition(array(new InputOption('foo', null, InputOption::VALUE_REQUIRED))); // call to bind $input = new StringInput('--foo=bar'); $input->bind($definition); $this->assertEquals('bar', $input->getOption('foo')); // definition in constructor $input = new StringInput('--foo=bar', $definition); $this->assertEquals('bar', $input->getOption('foo')); }
/** * {@inheritDoc} */ public function execute(InputInterface $input, OutputInterface $output) { $config = new Config($this->getComposer()); $this->resetComposers($application = $this->getApplication()); /** @var ComposerApplication $application */ if ($config->binLinksAreEnabled()) { putenv('COMPOSER_BIN_DIR=' . $this->createConfig()->get('bin-dir')); } $vendorRoot = 'vendor-bin'; $namespace = $input->getArgument('namespace'); $input = new StringInput(preg_replace('/bin\\s+' . preg_quote($namespace, '/') . '/', '', $input->__toString(), 1)); return 'all' !== $namespace ? $this->executeInNamespace($application, $vendorRoot . '/' . $namespace, $input, $output) : $this->executeAllNamespaces($application, 'vendor-bin', $input, $output); }
public function run($command) { $kernel = $this->container->get('kernel'); $app = new Application($kernel); $input = new StringInput($command); $input->setInteractive(false); $output = new StreamOutput(fopen('php://temp', 'w')); // Run the command $app->doRun($input, $output); rewind($output->getStream()); $response = stream_get_contents($output->getStream()); return $response; }
/** * handle. * * @throws \InvalidArgumentException */ public function fire() { $command = $this->option('command'); if ($this->needForce($command) === true) { $command .= ' --force'; } $input = new StringInput($command); $input->setInteractive(false); if (isset($this->notSupport[$input->getFirstArgument()]) === true) { throw new InvalidArgumentException('Command "' . $command . '" is not supported'); } $this->artisan->handle($input, $this->getOutput()); }
public function validate() { try { $this->input->validate(); } catch (RuntimeException $exception) { throw new InvalidInput($exception->getMessage(), $this, $exception); } }
/** * Execute symfony cli command. * * @param string $commandString Command to execute * @return array */ public function execute($commandString) { $input = new StringInput($commandString); $input->setInteractive(false); $output = new StringOutput(); $formatter = $output->getFormatter(); $formatter->setDecorated(true); $output->setFormatter(new HtmlConsoleOutputFormatter($formatter)); //$application = new Application($this->getContainer()->get('kernel')); $application = $this->_getApplication($input); $kernel = $application->getKernel(); chdir($kernel->getRootDir() . '/..'); $application->setAutoExit(false); ob_start(); $errorCode = $application->run($input, $output); $result = $output->getBuffer() || ob_get_contents(); ob_end_clean(); return array('input' => $commandString, 'output' => $output->getBuffer(), 'environment' => $kernel->getEnvironment(), 'errorcode' => $errorCode); }
private function configure(InputInterface $input) { preg_match_all('/(\\-\\-skip\\-[a-zA-Z0-9\\.\\-\\/=\\"\']+)/', (string) $input, $matches); $stringInput = new StringInput(implode(' ', $matches[0])); $stringInput->bind($this->getDefinition()); extract(Environment::getVars($stringInput)); $app = new Generic($app_path, $lib_path, $env, $user, 'console', $this->cacheConfig); $config = $app->getConfig(); // add helper sets if (isset($config['console']['helpers']) && is_array($config['console']['helpers'])) { $set_array = array(); foreach ($config['console']['helpers'] as $name => $helper) { $helper = new $helper(); $set_array[$name] = $helper->getHelper($app, $this); } $helperSet = new \Symfony\Component\Console\Helper\HelperSet($set_array); $this->setHelperSet($helperSet); } // add commands if (isset($config['console']['commands']) && is_array($config['console']['commands'])) { foreach ($config['console']['commands'] as $command) { $sets = array(); if (!is_string($command)) { if (!isset($command['class'])) { throw new \Exception('Commands with extra configuration needs a `class` parameter. No class parameter found.'); } $sets = isset($command['set']) ? $command['set'] : $sets; if (!is_array($sets)) { throw new \Exception('Commands with a `sets` parameter must be a hash array of paramerter => service, where parameter is the un-camelised key paramerter and service is the key identifier of the dependant service.'); } $command = $command['class']; } $command = new $command(); Utils::setParametersOn($command, $sets, $app); if ($command instanceof \Skip\ServiceContainerInterface) { $command->setContainer($app); } $this->add($command); } } $this->app = $app; }
/** * @dataProvider inputProvider * @param string $stringInput * @param string $expectedIdeKey */ public function testShouldGetIdeKeyFromCommandOptionOnCommandInitialization($stringInput, $expectedIdeKey) { $this->mockXdebugExtension($isExtensionLoaded = true, $isRemoteEnabled = true); $command = new RunCommand(new EventDispatcher()); $input = new StringInput($stringInput); $output = new BufferedOutput(); $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); // Trigger event to add the xdebug option to the command and bind the definition to the input $this->listener->onCommandConfigure(new BasicConsoleEvent($command)); $input->bind($command->getDefinition()); // Trigger command initialization event $event = new ExtendedConsoleEvent($command, $input, $output); $this->listener->onCommandRunTestsInit($event); if ($expectedIdeKey !== null) { $this->assertContains('Xdebug remote debugging initialized with IDE key: ' . $expectedIdeKey, $output->fetch()); } else { // no output expected (xdebug not triggered) $this->assertEmpty($output->fetch()); } }
/** * @param string $input * @param array $options * * @return integer */ public function run($input, array $options = array()) { if (isset($options['interactive']) && $options['interactive']) { $this->input = new InteractiveStringInput($input); } else { $this->input = new StringInput($input); $this->input->setInteractive(false); } $this->output = new StreamOutput(fopen('php://memory', 'w', false)); if (isset($options['decorated'])) { $this->output->setDecorated($options['decorated']); } if (isset($options['verbosity'])) { $this->output->setVerbosity($options['verbosity']); } $inputStream = $this->getInputStream(); rewind($inputStream); $this->application->getHelperSet()->get('dialog')->setInputStream($inputStream); return $this->application->run($this->input, $this->output); }
public function run(InputInterface $input, OutputInterface $output) { $tokens = preg_split('{\\s+}', $input->__toString()); $args = array(); foreach ($tokens as $token) { if ($token && $token[0] !== '-') { $args[] = $token; if (count($args) >= 2) { break; } } } if (count($args) < 2) { return parent::run($input, $output); } $config = Factory::createConfig(); chdir($config->get('home')); $this->getIO()->writeError('<info>Changed current directory to ' . $config->get('home') . '</info>'); $input = new StringInput(preg_replace('{\\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\\b}', '', $input->__toString(), 1)); return $this->getApplication()->run($input, $output); }
$loader = $this->command->getLoader(); $runner = $this->command->getRunner(); expect($loader)->to->be->an->instanceof('Peridot\\Concurrency\\SuiteLoader'); expect($runner)->to->be->an->instanceof('Peridot\\Concurrency\\Runner\\StreamSelect\\StreamSelectRunner'); }); it('should set the reporter to the concurrency reporter', function () { $reporter = $this->configuration->getReporter(); expect($reporter)->to->equal('concurrent'); }); it('should set configured processes on the concurrency config', function () { $configuration = $this->plugin->getConfiguration(); expect($configuration->getProcesses())->to->equal(4); }); }); it('should not set the suite loader and runner if concurrent options is not set', function () { $input = new StringInput(''); $input->bind($this->definition); $this->emitter->emit('peridot.execute', [$input]); $this->emitter->emit('peridot.load', [$this->command, $this->configuration]); $loader = $this->command->getLoader(); $runner = $this->command->getRunner(); expect($loader)->to->be->an->instanceof('Peridot\\Runner\\SuiteLoader'); expect($runner)->to->be->an->instanceof('Peridot\\Runner\\Runner'); }); }); context('when peridot.configure event is fired', function () use($configure) { beforeEach($configure); it('should store references to the configuration and application objects', function () { expect($this->plugin->getConfiguration())->to->be->an->instanceof('Peridot\\Concurrency\\Configuration'); expect($this->plugin->getApplication())->to->equal($this->app->reveal()); });
function testInteractAndValidate() { $this->commandFileInstance = new \Consolidation\TestUtils\ExampleCommandFile(); $this->commandFactory = new AnnotatedCommandFactory(); $hookInfo = $this->commandFactory->createCommandInfo($this->commandFileInstance, 'interactTestHello'); $this->assertTrue($hookInfo->hasAnnotation('hook')); $this->assertEquals($hookInfo->getAnnotation('hook'), 'interact test:hello'); $this->commandFactory->registerCommandHook($hookInfo, $this->commandFileInstance); $hookInfo = $this->commandFactory->createCommandInfo($this->commandFileInstance, 'validateTestHello'); $this->assertTrue($hookInfo->hasAnnotation('hook')); $this->assertEquals($hookInfo->getAnnotation('hook'), 'validate test:hello'); $this->commandFactory->registerCommandHook($hookInfo, $this->commandFileInstance); $hookCallback = $this->commandFactory->hookManager()->get('test:hello', [HookManager::ARGUMENT_VALIDATOR]); $this->assertTrue($hookCallback != null); $this->assertEquals(1, count($hookCallback)); $this->assertEquals(2, count($hookCallback[0])); $this->assertTrue(is_callable($hookCallback[0])); $this->assertEquals('validateTestHello', $hookCallback[0][1]); $hookCallback = $this->commandFactory->hookManager()->get('test:hello', [HookManager::INTERACT]); $this->assertTrue($hookCallback != null); $this->assertEquals(1, count($hookCallback)); $this->assertEquals(2, count($hookCallback[0])); $this->assertTrue(is_callable($hookCallback[0])); $this->assertEquals('interactTestHello', $hookCallback[0][1]); $commandInfo = $this->commandFactory->createCommandInfo($this->commandFileInstance, 'testHello'); $command = $this->commandFactory->createCommand($commandInfo, $this->commandFileInstance); $this->assertInstanceOf('\\Symfony\\Component\\Console\\Command\\Command', $command); $this->assertEquals('test:hello', $command->getName()); $commandGetNames = $this->callProtected($command, 'getNames'); $this->assertEquals('test:hello,Consolidation\\TestUtils\\ExampleCommandFile', implode(',', $commandGetNames)); $testInteractInput = new StringInput('test:hello'); $definition = new \Symfony\Component\Console\Input\InputDefinition([new \Symfony\Component\Console\Input\InputArgument('application', \Symfony\Component\Console\Input\InputArgument::REQUIRED), new \Symfony\Component\Console\Input\InputArgument('who', \Symfony\Component\Console\Input\InputArgument::REQUIRED)]); $testInteractInput->bind($definition); $testInteractOutput = new BufferedOutput(); $command->commandProcessor()->interact($testInteractInput, $testInteractOutput, $commandGetNames, $command->getAnnotationData()); $this->assertEquals('Goofey', $testInteractInput->getArgument('who')); $hookCallback = $command->commandProcessor()->hookManager()->get('test:hello', 'interact'); $this->assertTrue($hookCallback != null); $this->assertEquals('interactTestHello', $hookCallback[0][1]); $input = new StringInput('test:hello "Mickey Mouse"'); $this->assertRunCommandViaApplicationEquals($command, $input, 'Hello, Mickey Mouse.'); $input = new StringInput('test:hello'); $this->assertRunCommandViaApplicationEquals($command, $input, 'Hello, Goofey.'); $input = new StringInput('test:hello "Donald Duck"'); $this->assertRunCommandViaApplicationEquals($command, $input, "I won't say hello to Donald Duck.", 1); $input = new StringInput('test:hello "Drumph"'); $this->assertRunCommandViaApplicationEquals($command, $input, "Irrational value error.", 1); // Try the last test again with a display error function installed. $this->commandFactory->commandProcessor()->setDisplayErrorFunction(function ($output, $message) { $output->writeln("*** {$message} ****"); }); $input = new StringInput('test:hello "Drumph"'); $this->assertRunCommandViaApplicationEquals($command, $input, "*** Irrational value error. ****", 1); }
public function requestAction() { $request = $this->get('request'); if ($request->isXmlHttpRequest() && $request->getMethod() == 'POST') { // retrieve command string $sf2Command = stripslashes($request->request->get('command')); if ($sf2Command == '.') { // this trick is used to give the possibility to have "php app/console" equivalent $sf2Command = 'list'; } elseif ($sf2Command == 'cache:clear') { // warming up the cache cannot be done after clearing it // fix issue #11 $sf2Command .= ' --no-warmup'; } //TODO: not really efficient $rootFolder = basename($this->container->getParameter('kernel.root_dir')); $app = $request->request->get('app') ?: $rootFolder; if (!in_array($app, $this->container->getParameter('sf2gen_console.apps'))) { return new Response('This application is not allowed...', 200); // set to 200 to allow console display } //Try to run a separate shell process if ($this->container->getParameter('sf2gen_console.new_process')) { //Try to run a separate shell process try { $php = $this->getPhpExecutable(); $commandLine = $php . ' ' . $app . '/' . 'console '; if (!empty($sf2Command)) { $commandLine .= $sf2Command; } $p = new Process($commandLine, $rootFolder, null, null, 30, array('suppress_errors' => false, 'bypass_shell' => false)); $p->run(); $output = $p->getOutput(); /* if the process is not successful: - 1) Symfony throws an error and ouput is not empty; continue without Exception. - 2) Process throws an error and ouput is empty => Exception! */ if (!$p->isSuccessful() && empty($output)) { throw new \RuntimeException('Unabled to run the process.'); } } catch (\Exception $e) { // not trying the other method. It is interesting to know where it is not working (single process or not) return new Response(nl2br("The request failed when using a separated shell process. Try to use 'new_process: false' in configuration.\n Error : " . $e->getMessage())); } } else { //Try to execute a console within this process //TODO: fix cache:clear issue try { $input = new StringInput($sf2Command); //Prepare output ob_start(); $output = new StreamOutput(fopen("php://output", 'w'), StreamOutput::VERBOSITY_NORMAL, true, new OutputFormatterHtml(true)); //Start a kernel/console and an application $env = $input->getParameterOption(array('--env', '-e'), $this->container->getParameter('sf2gen_console.default_env')); $debug = !$input->hasParameterOption(array('--no-debug', '')); $kernel = new \AppKernel($env, $debug); $application = new Application($kernel); $application->setAutoExit(false); //Find, initialize and run the real command $run = $application->run($input, $output); $output = ob_get_contents(); ob_end_clean(); } catch (\Exception $e) { return new Response(nl2br("The request failed when using same process.\n Error : " . $e->getMessage())); } } // common response for both methods if (empty($output)) { $output = 'The command "' . $sf2Command . '" was successful.'; } return new Response($this->convertOutput($output)); } return new Response('This request was not found.', 404); // request is not a POST request }
/** * @group legacy */ public function testLegacyInputOptionDefinitionInConstructor() { $definition = new InputDefinition(array(new InputOption('foo', null, InputOption::VALUE_REQUIRED))); $input = new StringInput('--foo=bar', $definition); $this->assertEquals('bar', $input->getOption('foo')); }
/** * Provide access to the tokens as this is not * allowed by the default StringInput and we require * it for the "alias" feature. */ protected function setTokens(array $tokens) { $this->tokens = $tokens; parent::setTokens($tokens); }
/** * Get a command (if one exists) for the current input string. * * @param string $input * * @return null|Command */ protected function getCommand($input) { $input = new StringInput($input); if ($name = $input->getFirstArgument()) { return $this->get($name); } }
/** * Accepts $command input in format "your:symfony:command" * * @param string $command * @return int * @throws \Exception */ protected static function runCommand($command) { $command = sprintf('%s', $command); $kernel = new \AppKernel('test', true); $kernel->boot(); $application = new Application($kernel); $application->setAutoExit(false); $input = new StringInput($command); $input->setInteractive(false); return $application->run($input); }