The parsed arguments provide access to the options and arguments passed via the command line. Usually you can construct an {@link Args} instance by parsing a {@link RawArgs} instance with an {@link ArgsParser}: php $format = ArgsFormat::build() ->addCommandName(new CommandName('server')) ->addCommandName(new CommandName('add')) ->addOption(new Option('port', 'p', Option::VALUE_REQUIRED | Option::INTEGER)) ->addArgument(new Argument('host', Argument::REQUIRED)) ->getFormat(); $args = $parser->parseArgs($rawArgs, $format); The {@link ArgsFormat} defines which rules the console arguments must adhere to. You can also create {@link Args} instances manually. This is especially useful in tests: php $format = ArgsFormat::build() ->addOption(new Option('port', 'p', Option::VALUE_REQUIRED | Option::INTEGER)) ->addArgument(new Argument('host', Argument::REQUIRED)) ->getFormat(); $args = new Args($format); $args->setOption('port', 80); $args->setArgument('host', 'localhost');
Since: 1.0
Author: Bernhard Schussek (bschussek@gmail.com)
Exemplo n.º 1
0
 /**
  * {@inheritdoc}
  */
 public function getCommandFrom($className)
 {
     if (class_exists($className)) {
         $accessor = PropertyAccess::createPropertyAccessor();
         $reflector = new \ReflectionClass($className);
         $instance = $reflector->newInstanceWithoutConstructor();
         foreach ($reflector->getProperties() as $property) {
             if ($instance instanceof ConsoleCommandInterface && $property->getName() == 'io') {
                 continue;
             }
             if (!$this->format->hasArgument($property->getName()) && !$this->format->hasOption($property->getName())) {
                 throw new \InvalidArgumentException(sprintf("There is not '%s' argument defined in the %s command", $property->getName(), $className));
             }
             $value = null;
             if ($this->format->hasArgument($property->getName())) {
                 $value = $this->args->getArgument($property->getName());
             } elseif ($this->format->hasOption($property->getName())) {
                 $value = $this->args->getOption($property->getName());
             }
             $accessor->setValue($instance, $property->getName(), $value);
         }
         return $instance;
     }
     return;
 }
 private function createRunner(Args $args)
 {
     if ($args->getOption('dry-run')) {
         return new DryRunner($this->style, $this->config, !$args->getOption('all'));
     }
     return new VerboseRunner($this->style, $this->config, !$args->getOption('all'));
 }
Exemplo n.º 3
0
 public function testRenderCommandJson()
 {
     $args = new Args($this->helpCommand->getArgsFormat());
     $args->setArgument('command', 'the-command');
     $status = $this->handler->handle($args, $this->io, $this->command);
     $this->assertStringStartsWith('{"name":"the-command",', $this->io->fetchOutput());
     $this->assertSame(0, $status);
 }
Exemplo n.º 4
0
 public function handleDelete(Args $args)
 {
     $installerName = $args->getArgument('name');
     if (!$this->installerManager->hasInstallerDescriptor($installerName)) {
         throw new RuntimeException(sprintf('The installer "%s" does not exist.', $installerName));
     }
     $this->installerManager->removeRootInstallerDescriptor($installerName);
     return 0;
 }
Exemplo n.º 5
0
 /**
  * Handles the "puli plugin --remove" command.
  *
  * @param Args $args The console arguments.
  *
  * @return int The status code.
  */
 public function handleDelete(Args $args)
 {
     $pluginClass = $args->getArgument('class');
     if (!$this->manager->hasPluginClass($pluginClass)) {
         throw new RuntimeException(sprintf('The plugin class "%s" is not installed.', $pluginClass));
     }
     $this->manager->removePluginClass($pluginClass);
     return 0;
 }
Exemplo n.º 6
0
 private function getStability(Args $args)
 {
     if ($args->isOptionSet('stable')) {
         return PuliStrategy::STABLE;
     }
     if ($args->isOptionSet('unstable')) {
         return PuliStrategy::UNSTABLE;
     }
     return preg_match('/\\-(dev|alpha|beta)/', PuliApplicationConfig::VERSION) ? PuliStrategy::UNSTABLE : PuliStrategy::STABLE;
 }
Exemplo n.º 7
0
 /**
  * Handles the "tree" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handle(Args $args, IO $io)
 {
     $path = Path::makeAbsolute($args->getArgument('path'), $this->currentPath);
     $resource = $this->repo->get($path);
     $total = 0;
     $io->writeLine('<c1>' . $resource->getPath() . '</c1>');
     $this->printTree($io, $resource, $total);
     $io->writeLine('');
     $io->writeLine($total . ' resources');
     return 0;
 }
Exemplo n.º 8
0
 /**
  * Returns the non-root packages selected in the console arguments.
  *
  * @param Args              $args     The console arguments.
  * @param PackageCollection $packages The available packages.
  *
  * @return string[] The package names.
  */
 public static function getPackageNamesWithoutRoot(Args $args, PackageCollection $packages)
 {
     // Display all packages if "all" is set
     if ($args->isOptionSet('all')) {
         return $packages->getInstalledPackageNames();
     }
     $packageNames = array();
     foreach ($args->getOption('package') as $packageName) {
         $packageNames[] = $packageName;
     }
     return $packageNames ?: $packages->getInstalledPackageNames();
 }
Exemplo n.º 9
0
    public function testRenderCommandXml()
    {
        $args = new Args($this->helpCommand->getArgsFormat());
        $args->setArgument('command', 'the-command');
        $status = $this->handler->handle($args, $this->io, $this->command);
        $expected = <<<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<command id="the-command" name="the-command">
EOF;
        $this->assertStringStartsWith($expected, $this->io->fetchOutput());
        $this->assertSame(0, $status);
    }
 /**
  * @param Args $args
  * @param IO $io
  */
 public function handle(Args $args, IO $io)
 {
     parent::parseConfig($io);
     try {
         $retriever = new Retriever();
         $retriever->download($args->getArgument('url'));
         $io->writeLine('Downloaded and extracted');
     } catch (\RuntimeException $e) {
         $io->errorLine('Invalid url');
         exit;
     }
 }
Exemplo n.º 11
0
 /**
  * {@inheritdoc}
  */
 public function handle(Args $args, IO $io, Command $command)
 {
     $application = $command->getApplication();
     if ($args->isArgumentSet('command')) {
         $theCommand = $application->getCommand($args->getArgument('command'));
         $usage = new CommandHelp($theCommand);
     } else {
         $usage = new ApplicationHelp($application);
     }
     $usage->render($io);
     return 0;
 }
Exemplo n.º 12
0
 /**
  * Returns the non-root modules selected in the console arguments.
  *
  * @param Args       $args    The console arguments
  * @param ModuleList $modules The available modules
  *
  * @return string[] The module names
  */
 public static function getModuleNamesWithoutRoot(Args $args, ModuleList $modules)
 {
     // Display all modules if "all" is set
     if ($args->isOptionSet('all')) {
         return $modules->getInstalledModuleNames();
     }
     $moduleNames = array();
     foreach ($args->getOption('module') as $moduleName) {
         $moduleNames[] = $moduleName;
     }
     return $moduleNames ?: $modules->getInstalledModuleNames();
 }
Exemplo n.º 13
0
 /**
  * Handles the "upgrade" command.
  *
  * @param Args $args The console arguments
  * @param IO   $io   The I/O
  *
  * @return int The status code
  */
 public function handle(Args $args, IO $io)
 {
     $moduleFile = $this->moduleFileManager->getModuleFile();
     $originVersion = $moduleFile->getVersion();
     $targetVersion = $args->getArgument('version');
     if (version_compare($originVersion, $targetVersion, '=')) {
         $io->writeLine(sprintf('Your puli.json is already at version %s.', $targetVersion));
         return 0;
     }
     $this->moduleFileManager->migrate($targetVersion);
     $io->writeLine(sprintf('Migrated your puli.json from version %s to version %s.', $originVersion, $targetVersion));
     return 0;
 }
Exemplo n.º 14
0
 /**
  * Handles the "url" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handle(Args $args, IO $io)
 {
     foreach ($args->getArgument('path') as $path) {
         if (!Glob::isDynamic($path)) {
             $this->printUrl($path, $io);
             continue;
         }
         foreach ($this->repo->find($path) as $resource) {
             $this->printUrl($resource->getPath(), $io);
         }
     }
     return 0;
 }
Exemplo n.º 15
0
    public function testRenderCommandText()
    {
        $args = new Args($this->helpCommand->getArgsFormat());
        $args->setArgument('command', 'the-command');
        $status = $this->handler->handle($args, $this->io, $this->command);
        $expected = <<<'EOF'
USAGE
  console the-command

GLOBAL OPTIONS
EOF;
        $this->assertStringStartsWith($expected, $this->io->fetchOutput());
        $this->assertSame(0, $status);
    }
Exemplo n.º 16
0
 /**
  * Handles the "ls" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handle(Args $args, IO $io)
 {
     $path = Path::makeAbsolute($args->getArgument('path'), $this->currentPath);
     $resource = $this->repo->get($path);
     if (!$resource->hasChildren()) {
         throw new RuntimeException(sprintf('The resource "%s" does not have children.', $resource->getPath()));
     }
     if ($args->isOptionSet('long')) {
         $this->listLong($io, $resource->listChildren());
     } else {
         $this->listShort($io, $resource->listChildren());
     }
     return 0;
 }
Exemplo n.º 17
0
 private function getStability(Args $args)
 {
     if ($args->isOptionSet('stable')) {
         return GithubStrategy::STABLE;
     }
     if ($args->isOptionSet('unstable')) {
         return GithubStrategy::UNSTABLE;
     }
     foreach (array('-dev', '-alpha', '-beta') as $stability) {
         if (false !== strpos(PuliApplicationConfig::VERSION, $stability)) {
             return GithubStrategy::UNSTABLE;
         }
     }
     return GithubStrategy::STABLE;
 }
Exemplo n.º 18
0
 /**
  * Handles the "ls" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handle(Args $args, IO $io)
 {
     $path = Path::makeAbsolute($args->getArgument('path'), $this->currentPath);
     $resources = $this->repo->find($path);
     if (!count($resources)) {
         $io->errorLine("No resources found for path {$path}");
         return 1;
     }
     foreach ($resources as $resource) {
         if ($resource instanceof BodyResource) {
             $io->writeLine($resource->getBody());
         }
     }
     return 0;
 }
Exemplo n.º 19
0
 /**
  * {@inheritdoc}
  */
 public function handle(Args $args, IO $io, Command $command)
 {
     $descriptor = new XmlDescriptor();
     $output = new IOOutput($io);
     $application = $command->getApplication();
     $applicationAdapter = new ApplicationAdapter($application);
     if ($args->isArgumentSet('command')) {
         $theCommand = $application->getCommand($args->getArgument('command'));
         $commandAdapter = new CommandAdapter($theCommand, $applicationAdapter);
         $descriptor->describe($output, $commandAdapter);
     } else {
         $descriptor->describe($output, $applicationAdapter);
     }
     return 0;
 }
Exemplo n.º 20
0
 /**
  * Creates the arguments from the current class state.
  *
  * @param ArgsFormat $format  The format.
  * @param RawArgs    $rawArgs The raw arguments.
  *
  * @return Args The created console arguments.
  */
 private function createArgs(ArgsFormat $format, RawArgs $rawArgs)
 {
     $args = new Args($format, $rawArgs);
     foreach ($this->arguments as $name => $value) {
         // Filter command names
         if ($format->hasArgument($name)) {
             $args->setArgument($name, $value);
         }
     }
     foreach ($this->options as $name => $value) {
         // Filter command options
         if ($format->hasOption($name)) {
             $args->setOption($name, $value);
         }
     }
     return $args;
 }
Exemplo n.º 21
0
 public function handle(Args $args, IO $io, Command $command)
 {
     $tabular = Tabular::getInstance();
     $dom = new \DOMDocument('1.0');
     $dom->load($args->getArgument('xml'));
     $tableDom = $tabular->tabulate($dom, $args->getArgument('definition'));
     if ($args->getOption('debug')) {
         $io->writeLine($tableDom->saveXml());
     }
     $rows = $tableDom->toArray();
     $table = new Table(TableStyle::solidBorder());
     $table->setHeaderRow(array_keys(reset($rows) ?: array()));
     foreach ($rows as $row) {
         $table->addRow($row);
     }
     $table->render($io);
 }
 public function handleShow(Args $args, IO $io)
 {
     $this->style->title('Show profile information');
     if ($io->isVerbose()) {
         $this->style->text([sprintf('// Using config file: %s', $this->config->get('config_file', '')), sprintf('// Project directory: %s', $this->config->get('project_directory', '')), sprintf('// Dancer config directory: %s', $this->config->get('dancer_directory', ''))]);
     }
     $profileNames = array_keys($this->config->getProfiles());
     if (!($profileName = $args->getArgument('name'))) {
         $profileName = $this->style->choice('Profile to show', $profileNames);
     }
     if (null === $profileName) {
         $this->style->error(sprintf('Unable to find a profile with name "%s".', $profileName));
         return 1;
     }
     $this->style->section($profileName);
     $this->renderResolvedProfile($this->config->getProfiles()[$profileName], $io->isVerbose());
     return 0;
 }
 /**
  * @param Args $args
  * @param IO $io
  */
 public function handle(Args $args, IO $io)
 {
     parent::parseConfig($io);
     try {
         $filesScanner = new Files\Scanner($args->getArgument('path'));
         $files = $filesScanner->scan();
     } catch (\RuntimeException $e) {
         $io->errorLine("Invalid path");
         exit;
     }
     try {
         $uploader = new Uploader(new Ftp($this->profile));
         $uploader->upload($files);
         $io->writeLine("Uploaded");
     } catch (\RuntimeException $e) {
         $io->errorLine($e->getMessage());
         exit;
     }
 }
Exemplo n.º 24
0
 public function testHasOption()
 {
     $inputArgs = new ArgsInput($this->rawArgs, $this->args);
     $inputNoArgs = new ArgsInput($this->rawArgs);
     $this->args->setOptions(array('option1' => true));
     $this->assertTrue($inputArgs->hasOption('option1'));
     $this->assertTrue($inputArgs->hasOption('option2'));
     $this->assertFalse($inputArgs->hasOption('option3'));
     $this->assertFalse($inputNoArgs->hasOption('option1'));
 }
Exemplo n.º 25
0
 /**
  * Handles the "build" command.
  *
  * @param Args $args The console arguments.
  *
  * @return int The status code.
  */
 public function handle(Args $args)
 {
     $target = $args->getArgument('target');
     if (!in_array($target, self::$targets)) {
         throw new RuntimeException(sprintf('Invalid build target "%s". Expected one of: "%s"', $target, implode('", "', self::$targets)));
     }
     if ('all' === $target || 'factory' === $target) {
         $this->factoryManager->autoGenerateFactoryClass();
     }
     if ('all' === $target || 'repository' === $target) {
         $this->repoManager->clearRepository();
         $this->repoManager->buildRepository();
     }
     if ('all' === $target || 'discovery' === $target) {
         $this->discoveryManager->clearDiscovery();
         $this->discoveryManager->buildDiscovery();
     }
     return 0;
 }
Exemplo n.º 26
0
 /**
  * handle.
  *
  * @param Args $args
  * @param IO   $io
  *
  * @return int
  */
 public function handle(Args $args, IO $io)
 {
     $this->configurationLoader->setRootDirectory($args->getOption('config'));
     $config = $this->configurationLoader->loadConfiguration();
     try {
         $urlProvider = new UrlProvider($config);
         $runner = new Runner($urlProvider, GuzzleClient::createClient($io));
         $renderer = RendererFactory::create($args->getOption('format'), $io);
         $results = $runner->run();
         $renderer->render($results);
         if (isset($config['hogosha_portal']['metric_update']) || isset($config['hogosha_portal']['incident_update'])) {
             $pusher = new PusherManager($config, $io);
             $pusher->push($results);
         }
     } catch (BadResponseException $e) {
         $io->writeLine(sprintf('<error>Exception:</error> "%s"', $e->getMessage()));
     } catch (ConfigurationLoadingException $e) {
         $io->writeLine(sprintf('<info>There is no configuration file in</info> "%s"', $this->configurationLoader->getRootDirectory()));
     }
 }
Exemplo n.º 27
0
 /**
  * handle.
  *
  * @param Args $args
  * @param IO   $io
  *
  * @return int
  */
 public function handle(Args $args, IO $io)
 {
     $configFileExist = true;
     $overwrite = is_string($args->getOption('force'));
     try {
         $this->configurationLoader->setRootDirectory($args->getOption('config'));
         $configuration = $this->configurationLoader->loadConfiguration();
     } catch (ConfigurationLoadingException $e) {
         $configFileExist = false;
     }
     if (!$configFileExist || $overwrite) {
         $configuration = ['urls' => ['google' => ['url' => 'https://www.google.fr', 'method' => 'GET', 'headers' => [], 'timeout' => 1, 'validator' => [], 'status_code' => 200, 'metric_uuid' => null, 'service_uuid' => null]], 'hogosha_portal' => ['username' => '', 'password' => '', 'base_uri' => 'http://localhost:8000/api/', 'metric_update' => false, 'incident_update' => false, 'default_failed_incident_message' => 'An error as occured, we are investigating %service_name%', 'default_resolved_incident_message' => 'The service %service_name% is back to normal']];
         // Dump configuration
         $content = $this->configurationDumper->dumpConfiguration($configuration);
         $this->filesystem->dumpFile($this->configurationLoader->getConfigurationFilepath(), $content);
         $io->writeLine('<info>Creating monitor file</info>');
     } else {
         $io->writeLine(sprintf('<info>You already have a configuration file in</info> "%s"', $this->configurationLoader->getConfigurationFilepath()));
     }
 }
Exemplo n.º 28
0
 public function handle(Args $args, IO $io, Command $command)
 {
     $output = new ConsoleOutput();
     $style = new OutputFormatterStyle('white', 'black', array('bold'));
     if ($args->getArgument('package') == '') {
         $output->writeln(Cpm\message::USAGE);
         exit;
     }
     if (!file_exists('composer.json')) {
         $output->writeln(Cpm\message::NOComposerJSON);
     }
     $json = file_get_contents('composer.json');
     $array = json_decode($json, TRUE);
     $datas = $array['require'];
     foreach ($datas as $data) {
         $output->getFormatter()->setStyle('bold', $style);
         $output->writeln('<bold>' . $data->name . '</>' . ' ' . $data->description);
         $output->writeln($data->keywords);
     }
     return 0;
 }
Exemplo n.º 29
0
 /**
  * Handles the "add-prefix" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int Returns 0 on success and a positive integer on error.
  */
 public function handle(Args $args, IO $io)
 {
     $prefix = rtrim($args->getArgument('prefix'), '\\');
     $paths = $args->getArgument('path');
     foreach ($paths as $path) {
         if (!$this->filesystem->isAbsolutePath($path)) {
             $path = getcwd() . DIRECTORY_SEPARATOR . $path;
         }
         if (is_dir($path)) {
             $this->finder->files()->name('*.php')->in($path);
             foreach ($this->finder as $file) {
                 $this->scopeFile($file->getPathName(), $prefix, $io);
             }
         }
         if (!is_file($path)) {
             continue;
         }
         $this->scopeFile($path, $prefix, $io);
     }
     return 0;
 }
Exemplo n.º 30
0
 public function handle(Args $args, IO $io, Command $command)
 {
     $table = new Table();
     $table->setHeaderRow(array('Name', 'Description'));
     $output = new ConsoleOutput();
     $style = new OutputFormatterStyle('white', 'black', array('bold'));
     if ($args->getArgument('package') == '') {
         $output->writeln(Cpm\message::USAGE);
         exit;
     }
     $limit = $args->getOption('limit');
     $limit_str = $limit ? 'limit ' . $limit : '';
     $q = $args->getArgument('package');
     $datas = R::findAll('repo', ' name LIKE ? order by download_monthly desc,favers desc,download_total desc' . $limit_str, ['%' . $q . '%']);
     foreach ($datas as $data) {
         $output->getFormatter()->setStyle('bold', $style);
         //            $output->writeln('<bold>'.$data->name.'</>'.' '.$data->description);
         //            $output->writeln($data->keywords);
         $table->addRow(array("(" . $data->favers . ")" . $data->name, $data->description));
     }
     $table->render($io);
     return 0;
 }