comment() public method

Formats a command comment.
public comment ( string | array $message )
$message string | array
Esempio n. 1
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $pools = array();
     $clearers = array();
     $container = $this->getContainer();
     $cacheDir = $container->getParameter('kernel.cache_dir');
     foreach ($input->getArgument('pools') as $id) {
         $pool = $container->get($id);
         if ($pool instanceof CacheItemPoolInterface) {
             $pools[$id] = $pool;
         } elseif ($pool instanceof Psr6CacheClearer) {
             $clearers[$id] = $pool;
         } else {
             throw new \InvalidArgumentException(sprintf('"%s" is not a cache pool nor a cache clearer.', $id));
         }
     }
     foreach ($clearers as $id => $clearer) {
         $io->comment(sprintf('Calling cache clearer: <info>%s</info>', $id));
         $clearer->clear($cacheDir);
     }
     foreach ($pools as $id => $pool) {
         $io->comment(sprintf('Clearing cache pool: <info>%s</info>', $id));
         $pool->clear();
     }
     $io->success('Cache was successfully cleared.');
 }
Esempio n. 2
0
 /**
  *
  * {@inheritdoc}
  *
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $outputIsVerbose = $output->isVerbose();
     $io = new SymfonyStyle($input, $output);
     $realCacheDir = $this->getContainer()->getParameter('kernel.cache_dir');
     // the old cache dir name must not be longer than the real one to avoid exceeding
     // the maximum length of a directory or file path within it (esp. Windows MAX_PATH)
     $oldCacheDir = substr($realCacheDir, 0, -1) . ('~' === substr($realCacheDir, -1) ? '+' : '~');
     $filesystem = $this->getContainer()->get('filesystem');
     if (!is_writable($realCacheDir)) {
         throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $realCacheDir));
     }
     if ($filesystem->exists($oldCacheDir)) {
         $filesystem->remove($oldCacheDir);
     }
     $kernel = $this->getContainer()->get('kernel');
     $io->comment(sprintf('Clearing the cache for the <info>%s</info> environment with debug <info>%s</info>', $kernel->getEnvironment(), var_export($kernel->isDebug(), true)));
     $this->getContainer()->get('cache_clearer')->clear($realCacheDir);
     if ($input->getOption('no-warmup')) {
         $filesystem->rename($realCacheDir, $oldCacheDir);
     } else {
         // the warmup cache dir name must have the same length than the real one
         // to avoid the many problems in serialized resources files
         $realCacheDir = realpath($realCacheDir);
         $warmupDir = substr($realCacheDir, 0, -1) . ('_' === substr($realCacheDir, -1) ? '-' : '_');
         if ($filesystem->exists($warmupDir)) {
             if ($outputIsVerbose) {
                 $io->comment('Clearing outdated warmup directory...');
             }
             $filesystem->remove($warmupDir);
         }
         if ($outputIsVerbose) {
             $io->comment('Warming up cache...');
         }
         $this->warmup($warmupDir, $realCacheDir, !$input->getOption('no-optional-warmers'));
         $filesystem->rename($realCacheDir, $oldCacheDir);
         if ('\\' === DIRECTORY_SEPARATOR) {
             sleep(1);
             // workaround for Windows PHP rename bug
         }
         $filesystem->rename($warmupDir, $realCacheDir);
     }
     if ($outputIsVerbose) {
         $io->comment('Removing old cache directory...');
     }
     $filesystem->remove($oldCacheDir);
     if ($outputIsVerbose) {
         $io->comment('Finished');
     }
     $io->success(sprintf('Cache for the "%s" environment (debug=%s) was successfully cleared.', $kernel->getEnvironment(), var_export($kernel->isDebug(), true)));
 }
Esempio n. 3
0
 /**
  * Loads the local configuration from "~/.localhook/config.json" file.
  */
 protected function loadConfiguration()
 {
     try {
         $configuration = $this->configurationStorage->loadFromFile()->get();
     } catch (NoConfigurationException $e) {
         $this->io->comment($e->getMessage());
         if (!$this->secret) {
             $this->secret = $this->io->ask('Secret');
         }
         $configuration = $this->parseConfigurationKey();
     }
     $this->serverUrl = $configuration['socket_url'];
     $this->secret = $configuration['secret'];
     $this->configurationStorage->merge($configuration)->save();
 }
 /**
  * @param string $username
  * @param string $endpoint
  *
  * @param string $method
  * @param array  $query
  * @param array  $headers
  * @param string $body
  *
  * @return mixed|ResponseInterface
  */
 public function simulate($username, $endpoint, $method = 'POST', $query = ['get_param_1' => 'get_value_1', 'get_param_2' => 'get_value_2'], $headers = ['My-Header' => 'MyHeaderValue'], $body = 'post_param_1=post_value_1&post_param_2=post_value_2')
 {
     $url = $this->router->generate('notifications', array_merge(['username' => $username, 'endpoint' => $endpoint], $query));
     if ($this->io) {
         $this->io->comment('URL: ' . $url);
     }
     $server = [];
     if ($this->requestStack && ($currentRequest = $this->requestStack->getCurrentRequest())) {
         $server = $currentRequest->server->all();
     }
     $request = Request::create($url, $method, [], [], [], $server, $body);
     $request->headers->replace($headers);
     $response = $this->kernel->handle($request, HttpKernelInterface::SUB_REQUEST);
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $io->comment("Warming up the cache (<info>{$this->cacheDir}</info>)");
     $this->cacheWarmer->warmup($this->cacheDir);
     $io->success('Cache warmed up');
 }
 /**
  * @throws \InvalidArgumentException When route does not exist
  */
 protected function outputMailer($name)
 {
     try {
         $service = sprintf('swiftmailer.mailer.%s', $name);
         $mailer = $this->getContainer()->get($service);
     } catch (ServiceNotFoundException $e) {
         throw new \InvalidArgumentException(sprintf('The mailer "%s" does not exist.', $name));
     }
     $tableHeaders = array('Property', 'Value');
     $tableRows = array();
     $transport = $mailer->getTransport();
     $spool = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.spool.enabled', $name)) ? 'YES' : 'NO';
     $delivery = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.delivery.enabled', $name)) ? 'YES' : 'NO';
     $singleAddress = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.single_address', $name));
     $this->io->title(sprintf('Configuration of the Mailer "%s"', $name));
     if ($this->isDefaultMailer($name)) {
         $this->io->comment('This is the default mailer');
     }
     $tableRows[] = array('Name', $name);
     $tableRows[] = array('Service', $service);
     $tableRows[] = array('Class', get_class($mailer));
     $tableRows[] = array('Transport', sprintf('%s (%s)', sprintf('swiftmailer.mailer.%s.transport.name', $name), get_class($transport)));
     $tableRows[] = array('Spool', $spool);
     if ($this->getContainer()->hasParameter(sprintf('swiftmailer.spool.%s.file.path', $name))) {
         $tableRows[] = array('Spool file', $this->getContainer()->getParameter(sprintf('swiftmailer.spool.%s.file.path', $name)));
     }
     $tableRows[] = array('Delivery', $delivery);
     $tableRows[] = array('Single Address', $singleAddress);
     $this->io->table($tableHeaders, $tableRows);
 }
Esempio n. 7
0
 /**
  * @param string $cmd
  * @param bool   $ignoreErrors
  *
  * @throws Exception
  */
 private function execCmd($cmd, $ignoreErrors = false)
 {
     $cmd = 'cd ' . $this->workspacePath . ' && ' . $cmd;
     if ($this->io->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
         $this->io->comment($cmd);
     }
     $process = new Process($cmd);
     $process->run(function ($type, $buffer) use($ignoreErrors) {
         if (Process::ERR === $type) {
             if ($ignoreErrors) {
                 if ($this->io->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
                     $this->io->comment($buffer);
                 }
             } else {
                 $this->io->error($buffer);
             }
         } else {
             if ($this->io->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
                 $this->io->comment($buffer);
             }
         }
     });
     if (!$ignoreErrors && !$process->isSuccessful()) {
         throw new Exception($process->getOutput() . $process->getErrorOutput());
     }
 }
Esempio n. 8
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $address = $input->getArgument('address');
     if (strpos($address, ':') === false) {
         $address .= ':' . $input->getOption('port');
     }
     if ($this->isOtherServerProcessRunning($address)) {
         $io->error(sprintf('A process is already listening on http://%s', $address));
         return 1;
     }
     $webDir = $this->app['resources']->getPath('web');
     $router = $webDir . '/index.php';
     $io->success(sprintf('Server running on http://%s', $address));
     $io->comment('Quit the server with CONTROL-C.');
     if (($process = $this->createServerProcess($io, $address, $webDir, $router)) === null) {
         return 1;
     }
     /** @var ProcessHelper $helper */
     $helper = $this->getHelper('process');
     $helper->run($output, $process, null, null, OutputInterface::VERBOSITY_VERBOSE);
     if (!$process->isSuccessful()) {
         $errorMessages = ['Built-in server terminated unexpectedly.'];
         if ($process->isOutputDisabled()) {
             $errorMessages[] = 'Run the command again with -v option for more details.';
         }
         $io->error($errorMessages);
     }
     return $process->getExitCode();
 }
 /**
  * {@inheritdoc}
  *
  * @throws \LogicException
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $name = $input->getArgument('name');
     if (empty($name)) {
         $io->comment('Provide the name of a bundle as the first argument of this command to dump its default configuration.');
         $io->newLine();
         $this->listBundles($output);
         return;
     }
     $extension = $this->findExtension($name);
     $configuration = $extension->getConfiguration(array(), $this->getContainerBuilder());
     $this->validateConfiguration($extension, $configuration);
     if ($name === $extension->getAlias()) {
         $message = sprintf('Default configuration for extension with alias: "%s"', $name);
     } else {
         $message = sprintf('Default configuration for "%s"', $name);
     }
     switch ($input->getOption('format')) {
         case 'yaml':
             $io->writeln(sprintf('# %s', $message));
             $dumper = new YamlReferenceDumper();
             break;
         case 'xml':
             $io->writeln(sprintf('<!-- %s -->', $message));
             $dumper = new XmlReferenceDumper();
             break;
         default:
             $io->writeln($message);
             throw new \InvalidArgumentException('Only the yaml and xml formats are supported.');
     }
     $io->writeln($dumper->dump($configuration, $extension->getNamespace()));
 }
Esempio n. 10
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output = new SymfonyStyle($input, $output);
     if (false !== strpos($input->getFirstArgument(), ':d')) {
         $output->caution('The use of "config:debug" command is deprecated since version 2.7 and will be removed in 3.0. Use the "debug:config" instead.');
     }
     $name = $input->getArgument('name');
     if (empty($name)) {
         $output->comment('Provide the name of a bundle as the first argument of this command to dump its configuration.');
         $output->newLine();
         $this->listBundles($output);
         return;
     }
     $extension = $this->findExtension($name);
     $container = $this->compileContainer();
     $configs = $container->getExtensionConfig($extension->getAlias());
     $configuration = $extension->getConfiguration($configs, $container);
     $this->validateConfiguration($extension, $configuration);
     $configs = $container->getParameterBag()->resolveValue($configs);
     $processor = new Processor();
     $config = $processor->processConfiguration($configuration, $configs);
     if ($name === $extension->getAlias()) {
         $output->title(sprintf('Current configuration for extension with alias "%s"', $name));
     } else {
         $output->title(sprintf('Current configuration for "%s"', $name));
     }
     $output->writeln(Yaml::dump(array($extension->getAlias() => $config), 3));
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $io->comment("Clearing the cache (<info>{$this->cacheDir}</info>)");
     $this->cacheClearer->clear($this->cacheDir);
     $io->success('Cache cleared');
 }
Esempio n. 12
0
 /**
  * @param SymfonyStyle|null $io
  */
 public function updateCode(SymfonyStyle $io = null)
 {
     $io->title('CampaignChain Data Update');
     if (empty($this->versions)) {
         $io->warning('No code updater Service found, maybe you didn\'t enable a bundle?');
         return;
     }
     $io->comment('The following data versions will be updated');
     $migratedVersions = array_map(function (DataUpdateVersion $version) {
         return $version->getVersion();
     }, $this->em->getRepository('CampaignChainUpdateBundle:DataUpdateVersion')->findAll());
     $updated = false;
     foreach ($this->versions as $version => $class) {
         if (in_array($version, $migratedVersions)) {
             continue;
         }
         $io->section('Version ' . $class->getVersion());
         $io->listing($class->getDescription());
         $io->text('Begin data update');
         $result = $class->execute($io);
         if ($result) {
             $dbVersion = new DataUpdateVersion();
             $dbVersion->setVersion($version);
             $this->em->persist($dbVersion);
             $this->em->flush();
             $io->text('Data update finished');
         }
         $updated = true;
     }
     if (!$updated) {
         $io->success('All data is up to date.');
     } else {
         $io->success('Every data version has been updated.');
     }
 }
Esempio n. 13
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $name = $input->getArgument('name');
     if (empty($name)) {
         $io->comment('Provide the name of a bundle as the first argument of this command to dump its configuration.');
         $io->newLine();
         $this->listBundles($output);
         return;
     }
     $extension = $this->findExtension($name);
     $container = $this->compileContainer();
     $configs = $container->getExtensionConfig($extension->getAlias());
     $configuration = $extension->getConfiguration($configs, $container);
     $this->validateConfiguration($extension, $configuration);
     $configs = $container->getParameterBag()->resolveValue($configs);
     $processor = new Processor();
     $config = $processor->processConfiguration($configuration, $configs);
     if ($name === $extension->getAlias()) {
         $io->title(sprintf('Current configuration for extension with alias "%s"', $name));
     } else {
         $io->title(sprintf('Current configuration for "%s"', $name));
     }
     $io->writeln(Yaml::dump(array($extension->getAlias() => $config), 3));
 }
Esempio n. 14
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $io->title('Slack receive');
     $io->comment('Requesting slack websocket…');
     $latest = null;
     try {
         $latest = $this->container->get('doctrine')->getRepository(ProcessedSlackMessage::class)->findMostRecent();
     } catch (NoResultException $e) {
         $io->error('No message found in base, you should import first.');
         return;
     }
     $slack = $this->container->get('slack.api');
     $channelId = $slack->findChannelId($this->container->getParameter('slack_web_channel'));
     $response = $slack->request('rtm.start');
     $io->comment('Socket URL received, connecting…');
     $ws = new Client(json_decode($response)->url);
     $io->comment('Connected.');
     $exit = function ($sig) use($ws, $io) {
         $io->comment('Received closing signal ' . $sig);
         $ws->close();
         $io->comment('Exiting.');
         return;
     };
     foreach ([SIGTERM, SIGINT, SIGQUIT, SIGHUP] as $sig) {
         pcntl_signal($sig, $exit);
     }
     $ws->setTimeout(20);
     $pingId = 1;
     while (true) {
         try {
             pcntl_signal_dispatch();
             $this->receive($ws, $channelId, $io, $latest);
         } catch (ConnectionException $e) {
             $io->note('Sending Ping…');
             $ws->send(json_encode(['id' => $pingId, 'type' => 'ping']));
             if (!$this->isPong($ws->receive())) {
                 break;
             }
             ++$pingId;
         }
     }
     $ws->close();
 }
Esempio n. 15
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $io->title('Slack import');
     $io->comment('Requesting slack history…');
     $om = $this->container->get('doctrine')->getManager();
     $slack = $this->container->get('slack.api');
     $args = ['channel' => $slack->findChannelId($this->container->getParameter('slack_web_channel')), 'count' => 1000];
     try {
         $latest = $om->getRepository(ProcessedSlackMessage::class)->findMostRecent();
         $args['oldest'] = $latest->getDate()->format('U.u');
     } catch (NoResultException $e) {
     }
     $response = $slack->request('channels.history', $args);
     $messages = json_decode($response)->messages;
     $io->progressStart(count($messages));
     foreach ($messages as $message) {
         $io->progressAdvance();
         if (!(new AndX(new IsSlackMessage(), new IsHumanMessage()))->isSatisfiedBy($message)) {
             continue;
         }
         try {
             $url = $this->container->get('parser.slack_message')->parseUrl($message->text);
             $tags = $this->container->get('parser.slack_message')->parseTags($message->text);
             $watchLink = $this->container->get('extractor.watch_link_metadata')->extract($url, $tags);
             $watchLink->setCreatedAt((new \DateTime())->setTimestamp($message->ts));
             $processedMessage = new ProcessedSlackMessage($watchLink->getCreatedAt());
             $om->persist($processedMessage);
             $om->persist($watchLink);
             // Flush required at each round for tags unicity
             $om->flush();
         } catch (\InvalidArgumentException $e) {
             $this->container->get('logger')->addNotice('Unable to insert watchlink', ['exception' => $e, 'message' => $message->text]);
         } catch (\Exception $e) {
             $this->container->get('logger')->addError('Unknow exception', ['exception' => $e, 'message' => $message->text]);
         }
     }
     $io->progressFinish();
     $io->comment('Flush links…');
     $io->comment('Done.');
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output = new SymfonyStyle($input, $output);
     $kernel = $this->getContainer()->get('kernel');
     $output->comment(sprintf('Warming up the cache for the <info>%s</info> environment with debug <info>%s</info>', $kernel->getEnvironment(), var_export($kernel->isDebug(), true)));
     $warmer = $this->getContainer()->get('cache_warmer');
     if (!$input->getOption('no-optional-warmers')) {
         $warmer->enableOptionalWarmers();
     }
     $warmer->warmUp($this->getContainer()->getParameter('kernel.cache_dir'));
     $output->success(sprintf('Cache for the "%s" environment (debug=%s) was successfully warmed.', $kernel->getEnvironment(), var_export($kernel->isDebug(), true)));
 }
Esempio n. 17
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $nullOutput = new NullOutput();
     $io = new SymfonyStyle($input, $output);
     /** @var KernelInterface $kernel */
     $kernel = $this->getContainer()->get('kernel');
     $context = $this->getContainer()->getParameter('sulu.context');
     $io->comment(sprintf('Clearing the <info>%s cache</info> for the <info>%s</info> environment with debug <info>%s</info>', $context, $kernel->getEnvironment(), var_export($kernel->isDebug(), true)));
     parent::execute($input, $nullOutput);
     $io->success(sprintf('%s cache for the "%s" environment (debug=%s) was successfully cleared.', ucfirst($context), $kernel->getEnvironment(), var_export($kernel->isDebug(), true)));
     if (SuluKernel::CONTEXT_ADMIN === $context) {
         /** @var KernelFactoryInterface $kernelFactory */
         $kernelFactory = $this->getContainer()->get('sulu_preview.preview.kernel_factory');
         $previewKernel = $kernelFactory->create($kernel->getEnvironment());
         // set preview container
         $this->setContainer($previewKernel->getContainer());
         $io->comment(sprintf('Clearing the <info>preview cache</info> for the <info>%s</info> environment with debug <info>%s</info>', $kernel->getEnvironment(), var_export($kernel->isDebug(), true)));
         parent::execute($input, $nullOutput);
         $io->success(sprintf('Preview cache for the "%s" environment (debug=%s) was successfully cleared.', $kernel->getEnvironment(), var_export($kernel->isDebug(), true)));
     }
 }
Esempio n. 18
0
 /**
  * @param InputInterface  $input
  * @param OutputInterface $output
  *
  * @return void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $io->title('Start and run sentry monitor');
     $address = $input->getArgument('address');
     $webPath = __DIR__ . '/../../web';
     $processBuilder = new ProcessBuilder([PHP_BINARY, '-S', $address, $webPath . '/index.php']);
     $processBuilder->setWorkingDirectory($webPath . '/scripts')->setTimeout(null);
     $io->success(sprintf('Server running on "%s"', $address));
     $io->comment('Quit the server with CONTROL-C.');
     $process = $processBuilder->getProcess();
     $process->run();
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $seed = $input->getOption('ldif');
     if (null === $seed) {
         $seed = '@CarnegieLearningLdapOrmBundle/Resources/ldap/sample.ldif';
     }
     if (0 === strpos($seed, '@', 0)) {
         $seed = $this->getContainer()->get('kernel')->locateResource($seed);
     }
     if (false === ($path = realpath($seed))) {
         $io->error(sprintf('The LDIF seed file "%s" does not exist', $seed));
         return 1;
     }
     if (!is_readable($seed)) {
         $io->error(sprintf('The LDIF seed file "%s" is not readable', $seed));
         return 1;
     }
     $env = $this->getContainer()->getParameter('kernel.environment');
     $address = $input->getArgument('address');
     if (false === strpos($address, ':')) {
         $address = $address . ':' . $input->getOption('port');
     }
     if ($this->isOtherServerProcessRunning($address)) {
         $io->error(sprintf('A process is already listening on ldap://%s', $address));
         return 1;
     }
     if ('prod' === $env) {
         $io->error('Running UnboundID in-memory LDAP server in production environment is NOT recommended!');
     }
     $io->success(sprintf('Server running on ldap://%s', $address));
     $io->comment('Quit the server with CONTROL-C.');
     $baseDn = $input->getOption('base-dn');
     if (null === ($builder = $this->createLdapProcessBuilder($io, $address, $baseDn, $seed, $env))) {
         return 1;
     }
     $builder->setTimeout(null);
     $process = $builder->getProcess();
     if (OutputInterface::VERBOSITY_VERBOSE > $output->getVerbosity()) {
         $process->disableOutput();
     }
     $this->getHelper('process')->run($output, $process, null, null, OutputInterface::VERBOSITY_VERBOSE);
     if (!$process->isSuccessful()) {
         $errorMessages = ['UnboundID in-memory LDAP server terminated unexpectedly.'];
         if ($process->isOutputDisabled()) {
             $errorMessages[] = 'Run the command again with -v option for more details.';
         }
         $io->error($errorMessages);
     }
     return $process->getExitCode();
 }
Esempio n. 20
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $dbPath = $input->getOption('dbpath');
     $fs = new Filesystem();
     try {
         $fs->mkdir('data/mongodb/');
     } catch (IOException $e) {
         $io->warning('Could not create "data/mongodb/" directory');
     }
     // $env = $this->getContainer()->getParameter('kernel.environment');
     $env = null;
     $address = $input->getArgument('address');
     if (false === strpos($address, ':')) {
         $address = $address . ':' . $input->getOption('port');
     }
     if ($this->isOtherServerProcessRunning($address)) {
         $io->error(sprintf('A process is already listening on mongodb://%s.', $address));
         return 1;
     }
     /*
     if ('prod' === $env) {
         $io->error('Running PHP built-in server in production environment is NOT recommended!');
     }
     */
     $io->success(sprintf('Server running on mongodb://%s', $address));
     $io->comment('Quit the server with CONTROL-C.');
     if (null === ($builder = $this->createProcessBuilder($io, $input->getArgument('address'), $input->getOption('port'), $dbPath))) {
         return 1;
     }
     //$builder->setWorkingDirectory($documentRoot);
     $builder->setTimeout(null);
     $process = $builder->getProcess();
     if (OutputInterface::VERBOSITY_VERBOSE > $output->getVerbosity()) {
         $process->disableOutput();
     }
     $this->getHelper('process')->run($output, $process, null, null, OutputInterface::VERBOSITY_VERBOSE);
     if (!$process->isSuccessful()) {
         $errorMessages = array('Built-in server terminated unexpectedly.');
         if ($process->isOutputDisabled()) {
             $errorMessages[] = 'Run the command again with -v option for more details.';
         }
         $io->error($errorMessages);
     }
     return $process->getExitCode();
 }
 /**
  * Executes the current command.
  *
  * This method is not abstract because you can use this class
  * as a concrete class. In this case, instead of defining the
  * execute() method, you set the code to execute by passing
  * a Closure to the setCode() method.
  *
  * @param InputInterface  $input  An InputInterface instance
  * @param OutputInterface $output An OutputInterface instance
  *
  * @return null|int null or 0 if everything went fine, or an error code
  *
  * @see setCode()
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $styleHelper = new SymfonyStyle($input, $output);
     $config = new Client();
     $lintTool = new GitHubLintImplementation($config);
     $authenticationType = Client::AUTH_HTTP_TOKEN;
     $config->authenticate($input->getOption(self::OPTION_TOKEN), null, $authenticationType);
     $gitHubUsername = $input->getArgument(self::ARGUMENT_GITHUB_USERNAME);
     $gitHubRepository = $input->getArgument(self::ARGUMENT_GITHUB_REPOSITORY);
     $pullRequestId = $input->getArgument(self::ARGUMENT_PULL_REQUEST_ID);
     $printableName = "{$gitHubUsername}/{$gitHubRepository}#{$pullRequestId}";
     $styleHelper->title(self::COMMAND_NAME);
     $styleHelper->comment("Analysing PR {$printableName}");
     $lintTool->analyse($gitHubUsername, $gitHubRepository, (int) $pullRequestId);
     $styleHelper->success("Finished!");
     return 0;
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $documentRoot = $input->getOption('docroot');
     if (null === $documentRoot) {
         $documentRoot = $this->application['root_dir'] . '/public';
     }
     if (!is_dir($documentRoot)) {
         $io->error(sprintf('The given document root directory "%s" does not exist', $documentRoot));
         return 1;
     }
     $env = $this->application['env'];
     $address = $input->getArgument('address');
     if (false === strpos($address, ':')) {
         $address = $address . ':' . $input->getOption('port');
     }
     if ($this->isOtherServerProcessRunning($address)) {
         $io->error(sprintf('A process is already listening on http://%s.', $address));
         return 1;
     }
     if ('prod' === $env) {
         $io->error('Running PHP built-in server in production environment is NOT recommended!');
     }
     $io->success(sprintf('Server running on http://%s', $address));
     $io->comment('Quit the server with CONTROL-C.');
     if (null === ($builder = $this->createPhpProcessBuilder($io, $address, $input->getOption('router'), $env))) {
         return 1;
     }
     $builder->setWorkingDirectory($documentRoot);
     $builder->setTimeout(null);
     $process = $builder->getProcess();
     if (OutputInterface::VERBOSITY_VERBOSE > $output->getVerbosity()) {
         $process->disableOutput();
     }
     $this->getHelper('process')->run($output, $process, null, null, OutputInterface::VERBOSITY_VERBOSE);
     if (!$process->isSuccessful()) {
         $errorMessages = array('Built-in server terminated unexpectedly.');
         if ($process->isOutputDisabled()) {
             $errorMessages[] = 'Run the command again with -v option for more details.';
         }
         $io->error($errorMessages);
     }
     return $process->getExitCode();
 }
Esempio n. 23
0
 /**
  *
  * {@inheritdoc}
  *
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $path = $this->getContainer()->getParameter('kernel.root_dir') . '/' . $input->getArgument('path') . "";
     if (!is_dir($path)) {
         $io->error(sprintf('The given document directory "%s" does not exist', $path));
         return 1;
     }
     $io->success(sprintf('Found sources here here: %s', $path));
     $io->comment('Quit the process with CONTROL-C.');
     $files = scandir($path);
     foreach ($files as $file) {
         if (substr($file, -3) == ".js") {
             $jsoutput = \JShrink\Minifier::minify(file_get_contents($path . '/' . $file), array('flaggedComments' => false));
             file_put_contents($path . '/' . $file, $jsoutput);
             $io->success(sprintf('Shrunk: ' . $path . '/' . $file));
         }
     }
     $io->success(sprintf('Success!'));
 }
 /**
  * Displays a security report as plain text.
  *
  * @param OutputInterface $output
  * @param string          $lockFilePath    The file path to the checked lock file
  * @param array           $vulnerabilities An array of vulnerabilities
  */
 public function displayResults(OutputInterface $output, $lockFilePath, array $vulnerabilities)
 {
     $output = new SymfonyStyle(new ArrayInput(array()), $output);
     $output->title('Symfony Security Check Report');
     $output->comment(sprintf('Checked file: <comment>%s</>', realpath($lockFilePath)));
     if ($count = count($vulnerabilities)) {
         $output->error(sprintf('%d packages have known vulnerabilities.', $count));
     } else {
         $output->success('No packages have known vulnerabilities.');
     }
     if (0 !== $count) {
         foreach ($vulnerabilities as $dependency => $issues) {
             $output->section(sprintf('%s (%s)', $dependency, $issues['version']));
             $details = array_map(function ($value) {
                 return sprintf("<info>%s</>: %s\n   %s", $value['cve'] ?: '(no CVE ID)', $value['title'], $value['link']);
             }, $issues['advisories']);
             $output->listing($details);
         }
     }
     $output->note('This checker can only detect vulnerabilities that are referenced in the SensioLabs security advisories database. Execute this command regularly to check the newly discovered vulnerabilities.');
 }
Esempio n. 25
0
 /**
  *
  * {@inheritdoc}
  *
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     $path = $this->getContainer()->getParameter('kernel.root_dir') . '/' . $input->getArgument('path');
     if (!is_dir($path)) {
         $io->error(sprintf('The given document directory "%s" does not exist', $path));
         return 1;
     }
     $io->success(sprintf('Found app here: %s', $path));
     $io->comment('Quit the process with CONTROL-C.');
     $process = new Process('cd ' . $path . ' && npm run tsc');
     try {
         $process->mustRun();
         $output->writeln($process->getOutput());
     } catch (ProcessFailedException $e) {
         $io->error($e->getMessage());
         return 1;
     }
     $io->success(sprintf('Successfully compiled the app.'));
     $output->writeln($text);
 }
 /**
  * Database Import
  *
  * @param SymfonyStyle $helper
  *
  * @return null
  */
 private function actionDatabaseImport(SymfonyStyle $helper)
 {
     $timestamp = date('ymdHi');
     /*
      * Select Host
      */
     $remoteHost = $helper->ask('Remote host');
     /*
      * Select external database (default: database_name)
      */
     $remoteDatabase = $helper->ask('Remote database', $this->getContainer()->getParameter('database_name'));
     /*
      * Select local database (default: database_name)
      */
     $localDatabase = $helper->ask('New local database', sprintf('%s_%s', $this->getContainer()->getParameter('database_name'), $timestamp));
     /*
      * mysqldump
      */
     $fileName = sprintf('%s_%s_%s.sql', $remoteDatabase, $timestamp, uniqid());
     $command = sprintf('ssh %s "mysqldump %s > %s"', $remoteHost, $remoteDatabase, $fileName);
     $helper->comment($command);
     $process = new Process($command);
     $process->setTimeout(600);
     $process->run(function ($type, $buffer) use($helper) {
         if (Process::ERR === $type) {
             $helper->error($buffer);
             if (false !== strpos($buffer, 'Access denied')) {
                 $helper->note('Missing .my.cnf for mysql access?');
             }
         } else {
             $helper->comment($buffer);
         }
     });
     /*
      * scp
      */
     $command = sprintf('scp %s:%s %s/%s', $remoteHost, $fileName, sys_get_temp_dir(), $fileName);
     $helper->comment($command);
     $process = new Process($command);
     $process->setTimeout(300);
     $process->run(function ($type, $buffer) use($helper) {
         if (Process::ERR === $type) {
             $helper->error($buffer);
         } else {
             $helper->comment($buffer);
         }
     });
     /*
      * create database database_name_ymdHis
      * if exists: ask for drop
      */
     $command = sprintf('mysql -e "CREATE DATABASE %s;"', $localDatabase);
     $helper->comment($command);
     $process = new Process($command);
     $process->run(function ($type, $buffer) use($helper) {
         if (Process::ERR === $type) {
             $helper->error($buffer);
             if (false !== strpos($buffer, 'Access denied')) {
                 $helper->note('Missing .my.cnf for mysql access?');
             }
         } else {
             $helper->comment($buffer);
         }
     });
     /*
      * mysql -D database_name_ymdhis < /backup/y-m-d_H-i-s_unique.sql
      */
     $command = sprintf('mysql -D %s < %s/%s', $localDatabase, sys_get_temp_dir(), $fileName);
     $helper->comment($command);
     $process = new Process($command);
     $process->setTimeout(3600);
     $process->run(function ($type, $buffer) use($helper) {
         if (Process::ERR === $type) {
             $helper->error($buffer);
         } else {
             $helper->comment($buffer);
         }
     });
     /**
      * Remove
      */
     $command = sprintf('ssh %s "rm %s"', $remoteHost, $fileName);
     $helper->comment($command);
     $process = new Process($command);
     $process->run(function ($type, $buffer) use($helper) {
         if (Process::ERR === $type) {
             $helper->error($buffer);
         } else {
             $helper->comment($buffer);
         }
     });
     $command = sprintf('%s/%s', sys_get_temp_dir(), $fileName);
     $helper->comment(sprintf('unlink %s', $command));
     unlink($command);
     /**
      * Success! New database name:
      */
     $helper->success(['Created new Database', $localDatabase]);
     return null;
 }
Esempio n. 27
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new SymfonyStyle($input, $output);
     // check presence of force or dump-message
     if ($input->getOption('force') !== true && $input->getOption('dump-messages') !== true) {
         $io->error('You must choose one of --force or --dump-messages');
         return 1;
     }
     // check format
     $writer = $this->getContainer()->get('translation.writer');
     $supportedFormats = $writer->getFormats();
     if (!in_array($input->getOption('output-format'), $supportedFormats)) {
         $io->error(array('Wrong output format', 'Supported formats are: ' . implode(', ', $supportedFormats) . '.'));
         return 1;
     }
     $kernel = $this->getContainer()->get('kernel');
     // Define Root Path to App folder
     $transPaths = array($kernel->getRootDir() . '/Resources/');
     $currentName = 'app folder';
     // Override with provided Bundle info
     if (null !== $input->getArgument('bundle')) {
         try {
             $foundBundle = $kernel->getBundle($input->getArgument('bundle'));
             $transPaths = array($foundBundle->getPath() . '/Resources/', sprintf('%s/Resources/%s/', $kernel->getRootDir(), $foundBundle->getName()));
             $currentName = $foundBundle->getName();
         } catch (\InvalidArgumentException $e) {
             // such a bundle does not exist, so treat the argument as path
             $transPaths = array($input->getArgument('bundle') . '/Resources/');
             $currentName = $transPaths[0];
             if (!is_dir($transPaths[0])) {
                 throw new \InvalidArgumentException(sprintf('<error>"%s" is neither an enabled bundle nor a directory.</error>', $transPaths[0]));
             }
         }
     }
     $io->title('Translation Messages Extractor and Dumper');
     $io->comment(sprintf('Generating "<info>%s</info>" translation files for "<info>%s</info>"', $input->getArgument('locale'), $currentName));
     // load any messages from templates
     $extractedCatalogue = new MessageCatalogue($input->getArgument('locale'));
     $io->comment('Parsing templates...');
     $extractor = $this->getContainer()->get('translation.extractor');
     $extractor->setPrefix($input->getOption('prefix'));
     foreach ($transPaths as $path) {
         $path .= 'views';
         if (is_dir($path)) {
             $extractor->extract($path, $extractedCatalogue);
         }
     }
     // load any existing messages from the translation files
     $currentCatalogue = new MessageCatalogue($input->getArgument('locale'));
     $io->comment('Loading translation files...');
     $loader = $this->getContainer()->get('translation.loader');
     foreach ($transPaths as $path) {
         $path .= 'translations';
         if (is_dir($path)) {
             $loader->loadMessages($path, $currentCatalogue);
         }
     }
     // process catalogues
     $operation = $input->getOption('clean') ? new TargetOperation($currentCatalogue, $extractedCatalogue) : new MergeOperation($currentCatalogue, $extractedCatalogue);
     // Exit if no messages found.
     if (!count($operation->getDomains())) {
         $io->warning('No translation messages were found.');
         return;
     }
     // show compiled list of messages
     if (true === $input->getOption('dump-messages')) {
         $extractedMessagesCount = 0;
         $io->newLine();
         foreach ($operation->getDomains() as $domain) {
             $newKeys = array_keys($operation->getNewMessages($domain));
             $allKeys = array_keys($operation->getMessages($domain));
             $domainMessagesCount = count($newKeys) + count($allKeys);
             $io->section(sprintf('Messages extracted for domain "<info>%s</info>" (%d messages)', $domain, $domainMessagesCount));
             $io->listing(array_merge(array_diff($allKeys, $newKeys), array_map(function ($id) {
                 return sprintf('<fg=green>%s</>', $id);
             }, $newKeys), array_map(function ($id) {
                 return sprintf('<fg=red>%s</>', $id);
             }, array_keys($operation->getObsoleteMessages($domain)))));
             $extractedMessagesCount += $domainMessagesCount;
         }
         if ($input->getOption('output-format') == 'xlf') {
             $io->comment('Xliff output version is <info>1.2</info>');
         }
         $resultMessage = sprintf('%d messages were successfully extracted', $extractedMessagesCount);
     }
     if ($input->getOption('no-backup') === true) {
         $writer->disableBackup();
     }
     // save the files
     if ($input->getOption('force') === true) {
         $io->comment('Writing files...');
         $bundleTransPath = false;
         foreach ($transPaths as $path) {
             $path .= 'translations';
             if (is_dir($path)) {
                 $bundleTransPath = $path;
             }
         }
         if (!$bundleTransPath) {
             $bundleTransPath = end($transPaths) . 'translations';
         }
         $writer->writeTranslations($operation->getResult(), $input->getOption('output-format'), array('path' => $bundleTransPath, 'default_locale' => $this->getContainer()->getParameter('kernel.default_locale')));
         if (true === $input->getOption('dump-messages')) {
             $resultMessage .= ' and translation files were updated.';
         } else {
             $resultMessage = 'Translation files were successfully updated.';
         }
     }
     $io->success($resultMessage);
 }
Esempio n. 28
0
 /**
  * @param string $msg
  * @param        $color
  */
 protected function verboseLog($msg, $color)
 {
     if ($this->io && $this->io->getVerbosity() === OutputInterface::VERBOSITY_DEBUG) {
         $this->io->comment('<' . $color . '>' . date('[Y-m-d H:i:s]') . $msg . '</' . $color . '>');
     }
 }
 /**
  * Detailed debug information.
  *
  * @param string $message
  * @param array $context
  * @return null
  */
 public function debug($message, array $context = array())
 {
     $this->outputStyle->comment($message);
 }
Esempio n. 30
0
 private function displayTxt(OutputInterface $output, SymfonyStyle $io, $filesInfo)
 {
     $errors = 0;
     foreach ($filesInfo as $info) {
         if ($info['valid'] && $output->isVerbose()) {
             $io->comment('<info>OK</info>' . ($info['file'] ? sprintf(' in %s', $info['file']) : ''));
         } elseif (!$info['valid']) {
             ++$errors;
             $this->renderException($io, $info['template'], $info['exception'], $info['file']);
         }
     }
     if ($errors === 0) {
         $io->success(sprintf('All %d Twig files contain valid syntax.', count($filesInfo)));
     } else {
         $io->warning(sprintf('%d Twig files have valid syntax and %d contain errors.', count($filesInfo) - $errors, $errors));
     }
     return min($errors, 1);
 }