setCode() public method

If this method is used, it overrides the code defined in the execute() method.
See also: execute()
public setCode ( callable $code ) : Command
$code callable A callable(InputInterface $input, OutputInterface $output)
return Command The current instance
Example #1
0
 /**
  * @dataProvider inputInteractiveCommandToOutputFilesProvider
  */
 public function testInteractiveOutputs($inputCommandFilepath, $outputFilepath)
 {
     $code = (require $inputCommandFilepath);
     $this->command->setCode($code);
     $this->tester->execute(array(), array('interactive' => true, 'decorated' => false));
     $this->assertStringEqualsFile($outputFilepath, $this->tester->getDisplay(true));
 }
Example #2
0
 public function testLongWordsBlockWrapping()
 {
     $word = 'Lopadotemachoselachogaleokranioleipsanodrimhypotrimmatosilphioparaomelitokatakechymenokichlepikossyphophattoperisteralektryonoptekephalliokigklopeleiolagoiosiraiobaphetraganopterygovgollhjvhvljfezefeqifzeiqgiqzhrsdgihqzridghqridghqirshdghdghieridgheirhsdgehrsdvhqrsidhqshdgihrsidvqhneriqsdvjzergetsrfhgrstsfhsetsfhesrhdgtesfhbzrtfbrztvetbsdfbrsdfbrn';
     $wordLength = strlen($word);
     $maxLineLength = SymfonyStyle::MAX_LINE_LENGTH - 3;
     $this->command->setCode(function (InputInterface $input, OutputInterface $output) use($word) {
         $sfStyle = new SymfonyStyleWithForcedLineLength($input, $output);
         $sfStyle->block($word, 'CUSTOM', 'fg=white;bg=blue', ' § ', false);
     });
     $this->tester->execute(array(), array('interactive' => false, 'decorated' => false));
     $expectedCount = (int) ceil($wordLength / $maxLineLength) + (int) ($wordLength > $maxLineLength - 5);
     $this->assertSame($expectedCount, substr_count($this->tester->getDisplay(true), ' § '));
 }
Example #3
0
 public function testLongWordsBlockWrapping()
 {
     $word = 'Lopadotemachoselachogaleokranioleipsanodrimhypotrimmatosilphioparaomelitokatakechymenokichlepikossyphophattoperisteralektryonoptekephalliokigklopeleiolagoiosiraiobaphetraganopterygon';
     $wordLength = strlen($word);
     $maxLineLength = SymfonyStyle::MAX_LINE_LENGTH - 3;
     $this->command->setCode(function (InputInterface $input, OutputInterface $output) use($word) {
         $sfStyle = new SymfonyStyle($input, $output);
         $sfStyle->block($word, 'CUSTOM', 'fg=white;bg=blue', ' § ', false);
     });
     $this->tester->execute(array(), array('interactive' => false, 'decorated' => false));
     $expectedCount = (int) ceil($wordLength / $maxLineLength) + (int) ($wordLength > $maxLineLength - 5);
     $this->assertSame($expectedCount, substr_count($this->tester->getDisplay(true), ' § '));
 }
Example #4
0
 /**
  * Mount console command.
  *
  * @param string $name Command name
  * @param Closure $closure Closure to mount as command code
  *
  * @return Symfony\Component\Console\Command\Command
  */
 public function command($name, \Closure $closure = null)
 {
     $cmd = new Command($name);
     if (null !== $closure) {
         $cmd->setCode($closure);
     }
     return $this['console']->add($cmd);
 }
 /**
  * @inheritdoc
  */
 public function __construct($name = null)
 {
     parent::__construct($name);
     parent::setCode([$this, 'background']);
     $this->backgroundExecute = [$this, 'execute'];
     // add stop signals
     $this->addSignalCallback(SIGTERM, [$this, 'shutdown']);
     $this->addSignalCallback(SIGINT, [$this, 'shutdown']);
 }
 /**
  * creates a Command based on an Api Method.
  *
  * @param string            $name
  * @param \ReflectionMethod $method
  * @param string            $token
  *
  * @return Command
  */
 private function generateCommand($name, \ReflectionMethod $method, $token = null)
 {
     $methodName = $this->transformer->transform($method->getName());
     $command = new Command(strtolower($name . ':' . $methodName));
     $docBlock = DocBlockFactory::createInstance()->create($method->getDocComment());
     $command->setDefinition($this->buildDefinition($method, $token));
     $command->setDescription($docBlock->getSummary());
     $command->setCode($this->createCode($name, $method));
     return $command;
 }
Example #7
0
 public function testSetCommandEnvironment()
 {
     $command = new Command('acme');
     $command->setCode(function ($input, $output) {
         $output->writeln('acme');
     });
     $commandPlugin = new CommandPlugin();
     $commandPlugin->setCommandEnvironment(new SymfonyCommandEnvironment($command, new ConsoleOutput()));
     $this->assertInstanceOf('Yosymfony\\Spress\\Plugin\\Environment\\CommandEnvironmentInterface', $commandPlugin->getCommandEnvironment());
 }
Example #8
0
 /**
  * @param callable $code
  * @return $this|Command
  */
 public function setCode($code)
 {
     $this->assertCallable($code);
     $command = $this;
     parent::setCode(function (InputInterface $input) use($code, $command) {
         $input = $command->filterByOriginalDefinition($input, $command->getApplication()->getDefinition());
         $args = $input->getArguments();
         $args += $input->getOptions();
         return call_user_func_array($code, $args);
     });
     return $this;
 }
 /**
  * @expectedException Yosymfony\Spress\Plugin\Environment\CommandNotFoundException
  * @expectedExceptionMessage Command "foo" not found.
  */
 public function testRunCommandNotFound()
 {
     $application = new Application();
     $application->setAutoExit(false);
     $command = new Command('acme');
     $command->setCode(function ($input, $output) {
         $output->writeln('acme');
     });
     $application->add($command);
     $environment = new SymfonyCommandEnvironment($command, new ConsoleOutput());
     $environment->runCommand('foo', []);
 }
Example #10
0
 public function addInitRoboFileCommand($roboFile, $roboClass)
 {
     $createRoboFile = new Command('init');
     $createRoboFile->setDescription("Intitalizes basic RoboFile in current dir");
     $createRoboFile->setCode(function () use($roboClass, $roboFile) {
         $output = Config::get('output');
         $output->writeln("<comment>  ~~~ Welcome to Robo! ~~~~ </comment>");
         $output->writeln("<comment>  " . $roboFile . " will be created in current dir </comment>");
         file_put_contents($roboFile, '<?php' . "\n/**" . "\n * This is project's console commands configuration for Robo task runner." . "\n *" . "\n * @see http://robo.li/" . "\n */" . "\nclass " . $roboClass . " extends \\Robo\\Tasks\n{\n    // define public methods as commands\n}");
         $output->writeln("<comment>  Edit RoboFile.php to add your commands! </comment>");
     });
     $this->add($createRoboFile);
 }
 public function testCommandFromApplication()
 {
     $application = new Application();
     $application->setAutoExit(false);
     $command = new Command('foo');
     $command->setCode(function ($input, $output) {
         $output->writeln('foo');
     });
     $application->add($command);
     $tester = new CommandTester($application->find('foo'));
     // check that there is no need to pass the command name here
     $this->assertEquals(0, $tester->execute(array()));
 }
 /**
  * @see Symfony\Component\Console\Command\Command::__construct()
  */
 public function __construct($name = null)
 {
     // Construct our context
     $this->shutdownRequested = false;
     $this->setTimeout(self::DEFAULT_TIMEOUT);
     $this->setReturnCode(0);
     $this->lastUsage = 0;
     $this->lastPeakUsage = 0;
     // Construct parent context (also calls configure)
     parent::__construct($name);
     // Set our runloop as the executable code
     parent::setCode(array($this, 'runloop'));
 }
 /**
  * DaemonCommand constructor
  * @param string $name
  * @throws \InvalidArgumentException
  * @throws \Symfony\Component\Console\Exception\LogicException
  * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
  */
 public function __construct($name = Version::NAME)
 {
     $this->lastPeakUsage = 0;
     $this->lastUsage = 0;
     $this->pid = getmypid();
     $this->pidFilePath = getcwd();
     $this->returnCode = 0;
     $this->setTimeout(self::DEFAULT_TIMEOUT);
     $this->shutdownRequested = false;
     parent::__construct($name);
     parent::setCode([$this, 'runLoop']);
     $this->addOption('run-once', null, InputOption::VALUE_NONE, 'Run the command just once, do not go into an endless loop');
     $this->addOption('detect-leaks', null, InputOption::VALUE_NONE, 'Output information about memory usage');
 }
 /**
  * Build a Symfony Console commands.
  *
  * @param \Yosymfony\Spress\Plugin\CommandPluginInterface $commandPlugin
  *
  * @return \Symfony\Component\Console\Command\Command Symfony Console command.
  */
 protected function buildCommand(CommandPluginInterface $commandPlugin)
 {
     $definition = $commandPlugin->getCommandDefinition();
     $argumentsAndOptions = [];
     $consoleComand = new Command($definition->getName());
     $consoleComand->setDescription($definition->getDescription());
     $consoleComand->setHelp($definition->getHelp());
     foreach ($definition->getArguments() as list($name, $mode, $description, $defaultValue)) {
         $argumentsAndOptions[] = new InputArgument($name, $mode, $description, $defaultValue);
     }
     foreach ($definition->getOptions() as list($name, $shortcut, $mode, $description, $defaultValue)) {
         $argumentsAndOptions[] = new InputOption($name, $shortcut, $mode, $description, $defaultValue);
     }
     $consoleComand->setDefinition($argumentsAndOptions);
     $consoleComand->setCode(function (InputInterface $input, OutputInterface $output) use($commandPlugin) {
         $io = new ConsoleIO($input, $output);
         $arguments = $input->getArguments();
         $options = $input->getOptions();
         $commandPlugin->executeCommand($io, $arguments, $options);
     });
     return $consoleComand;
 }
Example #15
0
$parse_countries->setCode(function (InputInterface $input, ConsoleOutputInterface $output) use($project) {
    $output->writeLn('Starting Parse of Country this may <info>take a while</info>');
    # create a csv parser
    $parser = $project['parser'];
    $parser_options = $project['parser_options'];
    $parser_options->setParser('csv');
    $parser_options->setHasHeaderRow(false);
    $parser_options->setFieldSeperator(59);
    $parser_options->setSkipRows(0);
    # register for the generate event
    $event = $project['event_dispatcher'];
    $connection = $project['faker_database'];
    $event->addListener('row_parsed', function (Faker\Parser\Event\RowParsed $event) use($connection, $output, $input) {
        /* Example of data from names file
           Array
           (
               [FIELD1] => UNITED STATES MINOR OUTLYING ISLANDS
               [FIELD2] => UM
           )
           */
        $data = $event->getData();
        //$output->writeLn(print_r($data,true));
        $connection->transactional(function ($conn) use($output, $data, $input) {
            $conn->insert('countries', array('code' => $data['FIELD2'], 'name' => ucwords(strtolower($data['FIELD1']))));
            if ($input->getOption('verbose')) {
                $output->writeLn(sprintf('Parsed Country <info>%s</info> with code <info>%s</info>', $data['FIELD1'], $data['FIELD2']));
            } else {
                $output->write('.');
            }
        });
    });
    # parse data and load into table
    $parser->parse(__DIR__ . '/list-en1-semic-3.csv', $parser_options);
    $output->writeLn('Finished <info>parsing countries</info> into database');
});
Example #16
0
 /**
  * Allows you to add a command as Command object or as a command name+callable
  *
  * @param string|Command $nameOrCommand
  * @param callable|null $callable Must be a callable if $nameOrCommand is the command's name
  * @return Command The command instance that you can further configure
  * @api
  */
 public function command($nameOrCommand, $callable = null)
 {
     if ($nameOrCommand instanceof Command) {
         $command = $nameOrCommand;
     } else {
         if (!is_callable($callable)) {
             throw new \InvalidArgumentException('$callable must be a valid callable with the command\'s code');
         }
         $command = new Command($nameOrCommand);
         $command->setCode($callable);
     }
     $this['console']->add($command);
     return $command;
 }
 /**
  * {@inheritdoc}
  */
 public function setCode(callable $code)
 {
     $this->decoratedCommand->setCode($code);
     return $this;
 }
Example #18
0
 function it_should_alias_a_command(OutputInterface $output)
 {
     $command = new BaseCommand('test');
     $command->setCode(function () {
         return 123;
     });
     $this->addTask('foo', $command);
     $this->run(new ArrayInput(['command' => 'foo']), $output)->shouldReturn(123);
 }
Example #19
0
 public function testSymfonyStyleCommandWithInputs()
 {
     $questions = array('What\'s your name?', 'How are you?', 'Where do you come from?');
     $command = new Command('foo');
     $command->setCode(function ($input, $output) use($questions, $command) {
         $io = new SymfonyStyle($input, $output);
         $io->ask($questions[0]);
         $io->ask($questions[1]);
         $io->ask($questions[2]);
     });
     $tester = new CommandTester($command);
     $tester->setInputs(array('Bobby', 'Fine', 'France'));
     $tester->execute(array());
     $this->assertEquals(0, $tester->getStatusCode());
 }
Example #20
0
 /**
  * Registers a command.
  * 
  * @param string $name Name of the command.
  * @param string $commandClass Class name of the command.
  */
 public function addCommand($name, $commandClass)
 {
     // must extend AbstractCommand
     $abstractCommandClass = AbstractCommand::class;
     if (!Debugger::isExtending($commandClass, $abstractCommandClass)) {
         throw new InvalidCommandException('Command "' . $commandClass . '" must extend "' . $abstractCommandClass . '".');
     }
     // name cannot be empty
     $name = trim($name);
     if (empty($name)) {
         throw new InvalidArgumentException('Command name cannot be empty for "' . $commandClass . '"!');
     }
     // configure the command
     $console = $this;
     $consoleCommand = new ConsoleCommand($name);
     $consoleCommand->setDescription($commandClass::getDescription());
     $consoleCommand->setHelp($commandClass::getHelp());
     $consoleCommand->setCode(function (InputInterface $input, OutputInterface $output) use($console, $name) {
         $console->exec($name, $input, $output);
     });
     // read some meta info about the command
     $commandReflection = new \ReflectionClass($commandClass);
     $arguments = array();
     $argumentsDescriptions = $commandClass::getArguments();
     try {
         $methodReflection = $commandReflection->getMethod('execute');
         if (!$methodReflection->isPublic() || $methodReflection->isStatic()) {
             throw new InvalidCommandException('The "execute()" method for ommand "' . $commandClass . '" must be public and non-static.');
         }
         // get the execute() method's arguments so we can translate them to CLI arguments
         $parametersReflection = $methodReflection->getParameters();
         foreach ($parametersReflection as $param) {
             $optional = $param->isDefaultValueAvailable();
             $paramName = $param->getName();
             $arguments[] = array('name' => $paramName, 'optional' => $optional, 'default' => $optional ? $param->getDefaultValue() : null, 'description' => isset($argumentsDescriptions[$paramName]) ? $argumentsDescriptions[$paramName] : '');
         }
     } catch (\ReflectionException $e) {
         throw new InvalidCommandException('Command "' . $commandClass . '" must implement public function "execute()"!');
     }
     foreach ($arguments as $argument) {
         $consoleCommand->addArgument($argument['name'], $argument['optional'] ? InputArgument::OPTIONAL : InputArgument::REQUIRED, $argument['description'], $argument['default']);
     }
     // also register command's options
     $options = $commandClass::getOptions();
     foreach ($options as $option => $optionInfo) {
         $value = isset($optionInfo['required']) && $optionInfo['required'] ? InputOption::VALUE_REQUIRED : (!isset($optionInfo['default']) || empty($optionInfo['default']) || $optionInfo['default'] === null ? InputOption::VALUE_NONE : InputOption::VALUE_OPTIONAL);
         $consoleCommand->addOption($option, isset($optionInfo['shortcut']) ? $optionInfo['shortcut'] : null, $value, isset($optionInfo['description']) ? $optionInfo['description'] : '', $value === InputOption::VALUE_REQUIRED || $value === InputOption::VALUE_NONE ? null : (isset($optionInfo['default']) ? $optionInfo['default'] : null));
     }
     // register the command
     $this->commands[$name] = array('name' => $name, 'class' => $commandClass, 'command' => $consoleCommand, 'arguments' => $arguments, 'options' => $options);
     $this->consoleApplication->add($consoleCommand);
 }
Example #21
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
$say = function (InputInterface $in, OutputInterface $out) {
    $phrase = $in->getArgument('phrase');
    $out->writeln($phrase);
};
$sayCommand = new Command('say');
$sayCommand->addArgument('phrase', InputArgument::OPTIONAL, ' The phrase you want to say', ' I don\'t have anything to say');
$sayCommand->setCode($say);
$application = new Application();
$application->add($sayCommand);
$application->run();
Example #22
0
 public function setCode($code)
 {
     return $this->innerCommand->setCode($code);
 }
Example #23
0
 /**
  * Create Command.
  *
  * @param string   $expression
  * @param callable $callable
  *
  * @return \Symfony\Component\Console\Command\Command
  */
 protected function createCommand(string $expression, callable $callable) : SymfonyCommand
 {
     $result = $this->expressionParser->parse($expression);
     $command = new SymfonyCommand($result['name']);
     $command->getDefinition()->addArguments($result['arguments']);
     $command->getDefinition()->addOptions($result['options']);
     $command->setCode($callable);
     return $command;
 }