/**
  * @param string|array $data
  * @param string       $routeName
  * @param array[]      $routeParameters
  */
 public function push($data, $routeName, array $routeParameters = array(), array $context = [])
 {
     $eventName = 'push.' . $this->getName();
     $this->stopwatch->start($eventName, 'websocket');
     $this->pusher->push($data, $routeName, $routeParameters, $context);
     $this->stopwatch->stop($eventName);
     $this->dataCollector->collectData($this->stopwatch->getEvent($eventName), $this->getName());
 }
 /**
  * Stop and assign values to contao debug bar.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  */
 public function stop()
 {
     $rulesEvent = $this->watch->getEvent('dom_manipulator_rules');
     $manipulationEvent = $this->watch->stop('dom_manipulator_manipulation');
     $totalEvent = $this->watch->stop('dom_manipulator');
     $GLOBALS['TL_DEBUG']['dom_manipulator_total'] = $this->formatDuration('total', $totalEvent);
     $GLOBALS['TL_DEBUG']['dom_manipulator_rules'] = $this->formatDuration('rule creation', $rulesEvent);
     $GLOBALS['TL_DEBUG']['dom_manipulator_dom'] = $this->formatDuration('manipulation', $manipulationEvent);
 }
示例#3
0
 /**
  * Locks and gets a file handler.
  *
  * @return resource             The file handler.
  * @throws LockingException
  */
 private function getFile()
 {
     $init = false;
     if (!file_exists($this->file)) {
         $init = true;
         touch($this->file);
     }
     $fHandler = fopen($this->file, 'r+');
     $block = false;
     $stopWatch = new Stopwatch();
     $stopWatch->start('querker.filelock.getfile');
     $locked = false;
     do {
         if (!flock($fHandler, LOCK_EX | LOCK_NB, $block)) {
             if ($block) {
                 if ($stopWatch->getEvent('querker.filelock.getfile')->getDuration() <= self::MAX_WAIT_TIME * 1000) {
                     sleep(0.1);
                 } else {
                     throw new LockingException("Unable to get exclusive lock on file (" . $this->file . ").");
                 }
             }
         } else {
             $locked = true;
         }
     } while (!$locked);
     if ($init) {
         fwrite($fHandler, serialize(new PriorityQueue()));
     }
     $stopWatch->stop('querker.filelock.getfile');
     return $fHandler;
 }
 function it_stops(Stopwatch $stopwatch, StopwatchEvent $event)
 {
     $stopwatch->getEvent('dom_manipulator_rules')->shouldBeCalled()->willReturn($event);
     $stopwatch->stop('dom_manipulator')->shouldBeCalled()->willReturn($event);
     $stopwatch->stop('dom_manipulator_manipulation')->shouldBeCalled()->willReturn($event);
     $this->stop();
 }
示例#5
0
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $verbosity = $output->getVerbosity();
     $resolver = new ConfigurationResolver();
     $resolver->setCwd(getcwd())->setDefaultConfig($this->defaultConfig)->setOptions(array('allow-risky' => $input->getOption('allow-risky'), 'config' => $input->getOption('config'), 'dry-run' => $input->getOption('dry-run'), 'rules' => $input->getOption('rules'), 'path' => $input->getArgument('path'), 'path-mode' => $input->getOption('path-mode'), 'progress' => OutputInterface::VERBOSITY_VERBOSE <= $verbosity && 'txt' === $input->getOption('format'), 'using-cache' => $input->getOption('using-cache'), 'cache-file' => $input->getOption('cache-file'), 'format' => $input->getOption('format')))->resolve();
     $reporter = ReporterFactory::create()->registerBuiltInReporters()->getReporter($resolver->getFormat());
     $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : ('txt' === $reporter->getFormat() ? $output : null);
     if (null !== $stdErr && extension_loaded('xdebug')) {
         $stdErr->writeln(sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'You are running php-cs-fixer with xdebug enabled. This has a major impact on runtime performance.'));
     }
     $config = $resolver->getConfig();
     $configFile = $resolver->getConfigFile();
     if (null !== $stdErr && $configFile) {
         $stdErr->writeln(sprintf('Loaded config from "%s".', $configFile));
     }
     $linter = new NullLinter();
     if ($config->usingLinter()) {
         try {
             $linter = new Linter($config->getPhpExecutable());
         } catch (UnavailableLinterException $e) {
             if (null !== $stdErr && $configFile) {
                 $stdErr->writeln('Unable to use linter, can not find PHP executable.');
             }
         }
     }
     if (null !== $stdErr && $config->usingCache()) {
         $cacheFile = $config->getCacheFile();
         if (is_file($cacheFile)) {
             $stdErr->writeln(sprintf('Using cache file "%s".', $cacheFile));
         }
     }
     $showProgress = $resolver->getProgress();
     $runner = new Runner($config, $input->getOption('diff') ? new SebastianBergmannDiffer() : new NullDiffer(), $showProgress ? $this->eventDispatcher : null, $this->errorsManager, $linter, $resolver->isDryRun());
     $progressOutput = $showProgress && $stdErr ? new ProcessOutput($stdErr, $this->eventDispatcher) : new NullOutput();
     $this->stopwatch->start('fixFiles');
     $changed = $runner->fix();
     $this->stopwatch->stop('fixFiles');
     $progressOutput->printLegend();
     $fixEvent = $this->stopwatch->getEvent('fixFiles');
     $reportSummary = ReportSummary::create()->setChanged($changed)->setAddAppliedFixers(OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity())->setIsDecoratedOutput($output->isDecorated())->setIsDryRun($resolver->isDryRun())->setMemory($fixEvent->getMemory())->setTime($fixEvent->getDuration());
     $output->write($reporter->generate($reportSummary));
     $invalidErrors = $this->errorsManager->getInvalidErrors();
     $exceptionErrors = $this->errorsManager->getExceptionErrors();
     $lintErrors = $this->errorsManager->getLintErrors();
     if (null !== $stdErr) {
         if (count($invalidErrors) > 0) {
             $this->listErrors($stdErr, 'linting before fixing', $invalidErrors);
         }
         if (count($exceptionErrors) > 0) {
             $this->listErrors($stdErr, 'fixing', $exceptionErrors);
         }
         if (count($lintErrors) > 0) {
             $this->listErrors($stdErr, 'linting after fixing', $lintErrors);
         }
     }
     return $this->calculateExitStatus($resolver->isDryRun(), count($changed) > 0, count($invalidErrors) > 0, count($exceptionErrors) > 0);
 }
示例#6
0
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->questionHelper = $this->getHelperSet()->get('question');
        $this->entityManager = $this->getHelperSet()->get('em')->getEntityManager();
        $this->solr = $this->getHelperSet()->get('solr')->getSolr();
        $text = "";
        if (null !== $this->solr) {
            if (true === $this->getHelperSet()->get('solr')->ready()) {
                if ($input->getOption('reset')) {
                    $confirmation = new ConfirmationQuestion('<question>Are you sure to reset Solr index?</question>', false);
                    if ($this->questionHelper->ask($input, $output, $confirmation)) {
                        $update = $this->solr->createUpdate();
                        $update->addDeleteQuery('*:*');
                        $update->addCommit();
                        $this->solr->update($update);
                        $text = '<info>Solr index resetted…</info>' . PHP_EOL;
                    }
                } elseif ($input->getOption('reindex')) {
                    $confirmation = new ConfirmationQuestion('<question>Are you sure to reindex your Node database?</question>', false);
                    if ($this->questionHelper->ask($input, $output, $confirmation)) {
                        $stopwatch = new Stopwatch();
                        $stopwatch->start('global');
                        $this->reindexNodeSources($this->solr, $output);
                        $stopwatch->stop('global');
                        $duration = $stopwatch->getEvent('global')->getDuration();
                        $text = PHP_EOL . sprintf('<info>Node database has been re-indexed in %.2d ms.</info>', $duration) . PHP_EOL;
                    }
                } else {
                    $text .= '<info>Solr search engine server is running…</info>' . PHP_EOL;
                }
            } else {
                $text .= '<error>Solr search engine server does not respond…</error>' . PHP_EOL;
                $text .= 'See your config.yml file to correct your Solr connexion settings.' . PHP_EOL;
            }
        } else {
            $text .= '<error>No Solr search engine server has been configured…</error>' . PHP_EOL;
            $text .= 'Personnalize your config.yml file to enable Solr (sample):' . PHP_EOL;
            $text .= '
solr:
    endpoint:
        localhost:
            host:"localhost"
            port:"8983"
            path:"/solr"
            core:"mycore"
            timeout:3
            username:""
            password:""
            ';
        }
        $output->writeln($text);
    }
示例#7
0
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $verbosity = $output->getVerbosity();
     $resolver = new ConfigurationResolver($this->defaultConfig, array('allow-risky' => $input->getOption('allow-risky'), 'config' => $input->getOption('config'), 'dry-run' => $input->getOption('dry-run'), 'rules' => $input->getOption('rules'), 'path' => $input->getArgument('path'), 'path-mode' => $input->getOption('path-mode'), 'progress' => OutputInterface::VERBOSITY_VERBOSE <= $verbosity && 'txt' === $input->getOption('format'), 'using-cache' => $input->getOption('using-cache'), 'cache-file' => $input->getOption('cache-file'), 'format' => $input->getOption('format'), 'diff' => $input->getOption('diff')), getcwd());
     $reporter = $resolver->getReporter();
     $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : ('txt' === $reporter->getFormat() ? $output : null);
     if (null !== $stdErr && extension_loaded('xdebug')) {
         $stdErr->writeln(sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'You are running php-cs-fixer with xdebug enabled. This has a major impact on runtime performance.'));
     }
     $configFile = $resolver->getConfigFile();
     if (null !== $stdErr) {
         $stdErr->writeln(sprintf('Loaded config <comment>%s</comment>%s.', $resolver->getConfig()->getName(), null === $configFile ? '' : ' from "' . $configFile . '"'));
     }
     if (null !== $stdErr && $resolver->getUsingCache()) {
         $cacheFile = $resolver->getCacheFile();
         if (is_file($cacheFile)) {
             $stdErr->writeln(sprintf('Using cache file "%s".', $cacheFile));
         }
     }
     $showProgress = $resolver->getProgress();
     $runner = new Runner($resolver->getFinder(), $resolver->getFixers(), $input->getOption('diff') ? new SebastianBergmannDiffer() : new NullDiffer(), $showProgress ? $this->eventDispatcher : null, $this->errorsManager, $resolver->getLinter(), $resolver->isDryRun(), $resolver->getCacheManager());
     $progressOutput = $showProgress && $stdErr ? new ProcessOutput($stdErr, $this->eventDispatcher) : new NullOutput();
     $this->stopwatch->start('fixFiles');
     $changed = $runner->fix();
     $this->stopwatch->stop('fixFiles');
     $progressOutput->printLegend();
     $fixEvent = $this->stopwatch->getEvent('fixFiles');
     $reportSummary = new ReportSummary($changed, $fixEvent->getDuration(), $fixEvent->getMemory(), OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity(), $resolver->isDryRun(), $output->isDecorated());
     if ($output->isDecorated()) {
         $output->write($reporter->generate($reportSummary));
     } else {
         $output->write($reporter->generate($reportSummary), false, OutputInterface::OUTPUT_RAW);
     }
     $invalidErrors = $this->errorsManager->getInvalidErrors();
     $exceptionErrors = $this->errorsManager->getExceptionErrors();
     $lintErrors = $this->errorsManager->getLintErrors();
     if (null !== $stdErr) {
         if (count($invalidErrors) > 0) {
             $this->listErrors($stdErr, 'linting before fixing', $invalidErrors);
         }
         if (count($exceptionErrors) > 0) {
             $this->listErrors($stdErr, 'fixing', $exceptionErrors);
         }
         if (count($lintErrors) > 0) {
             $this->listErrors($stdErr, 'linting after fixing', $lintErrors);
         }
     }
     return $this->calculateExitStatus($resolver->isDryRun(), count($changed) > 0, count($invalidErrors) > 0, count($exceptionErrors) > 0);
 }
 /**
  * @param Stopwatch $stopwatch
  * @param OutputInterface $output
  */
 protected function outputPerformance(Stopwatch $stopwatch, OutputInterface $output)
 {
     if (OutputInterface::VERBOSITY_DEBUG <= $this->verbosity) {
         $output->writeln('Fixing time per file:');
         foreach ($stopwatch->getSectionEvents('fixFile') as $file => $event) {
             if ('__section__' === $file) {
                 continue;
             }
             $output->writeln(sprintf('[%.3f s] %s', $event->getDuration() / 1000, $file));
         }
         $output->writeln('');
     }
     $fixEvent = $stopwatch->getEvent('fixFiles');
     $output->writeln(sprintf('Fixed all files in %.3f seconds, %.3f MB memory used', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
 }
 /**
  * @param string   $testName
  * @param callable $function
  *
  * @return int The duration (in milliseconds)
  */
 protected static function benchmark($testName, $function)
 {
     if (!self::ENABLE_TESTS) {
         return 0;
     }
     if (false !== ($pos = strpos($testName, '::'))) {
         $testName = substr($testName, $pos + 2);
     }
     self::$stopwatch->start($testName);
     for ($i = 0; $i < self::NUMBER_OF_ITERATION; $i++) {
         call_user_func($function);
     }
     self::$stopwatch->stop($testName);
     return self::$stopwatch->getEvent($testName)->getDuration();
 }
 public function testLogger()
 {
     $stopWatch = new Stopwatch();
     $logger = new MemcachedLogger(null, $stopWatch);
     $logger->startMethod('testLogger');
     $event = $stopWatch->getEvent('memcached');
     $this->assertTrue($event->isStarted());
     $logger->stopMethod();
     $this->assertSame($stopWatch, $logger->getStopwatch());
     $event = $stopWatch->getEvent('memcached');
     $this->assertCount(1, $event->getPeriods());
     if (method_exists($stopWatch, 'getSections')) {
         $sections = $stopWatch->getSections();
         $this->assertCount(1, $sections);
     } else {
         $this->markTestSkipped('Requires symfony/stopwatch 2.6 or higher.');
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $errorsManager = new ErrorsManager();
     $stopwatch = new Stopwatch();
     $this->fixer = new Fixer($this->getFinder($input->getArgument('path')), $errorsManager, $stopwatch);
     $this->fixer->registerBuiltInFixers();
     if (!$input->getOption('no-use-reorder')) {
         $this->fixer->addFixer(new OrderedUseFixer());
     }
     $stopwatch->start('fixFiles');
     $changed = $this->fixer->fix($input->getOption('dry-run'));
     $stopwatch->stop('fixFiles');
     $verbosity = $output->getVerbosity();
     $i = 1;
     foreach ($changed as $file => $fixResult) {
         $output->write(sprintf('%4d) %s', $i++, $file));
         if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
             $output->write(sprintf(' (<comment>%s</comment>)', implode(', ', $fixResult)));
         }
         $output->writeln('');
     }
     if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
         $output->writeln('Fixing time per file:');
         foreach ($stopwatch->getSectionEvents('fixFile') as $file => $event) {
             if ('__section__' === $file) {
                 continue;
             }
             $output->writeln(sprintf('[%.3f s] %s', $event->getDuration() / 1000, $file));
         }
         $output->writeln('');
     }
     $fixEvent = $stopwatch->getEvent('fixFiles');
     $output->writeln(sprintf('Fixed all files in %.3f seconds, %.3f MB memory used', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
     if (!$errorsManager->isEmpty()) {
         $output->writeLn('');
         $output->writeLn('Files that were not fixed due to internal error:');
         foreach ($errorsManager->getErrors() as $i => $error) {
             $output->writeLn(sprintf('%4d) %s', $i + 1, $error['filepath']));
         }
     }
     return empty($changed) ? 0 : 1;
 }
示例#12
0
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // setup output
     $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : ('txt' === $input->getOption('format') ? $output : null);
     if (null !== $stdErr && extension_loaded('xdebug')) {
         $stdErr->writeln(sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'You are running php-cs-fixer with xdebug enabled. This has a major impact on runtime performance.'));
     }
     $verbosity = $output->getVerbosity();
     // setup input
     $path = $input->getArgument('path');
     $stdin = false;
     if ('-' === $path) {
         $stdin = true;
         // Can't write to STDIN
         $input->setOption('dry-run', true);
     }
     if (null !== $path) {
         $filesystem = new Filesystem();
         if (!$filesystem->isAbsolutePath($path)) {
             $path = getcwd() . DIRECTORY_SEPARATOR . $path;
         }
     }
     // setup configuration location
     $configFile = $input->getOption('config-file');
     if (null === $configFile) {
         $configDir = $path;
         if (is_file($path) && ($dirName = pathinfo($path, PATHINFO_DIRNAME))) {
             $configDir = $dirName;
         } elseif ($stdin || null === $path) {
             $configDir = getcwd();
             // path is directory
         }
         $configFile = $configDir . DIRECTORY_SEPARATOR . '.php_cs';
     }
     if ($input->getOption('config')) {
         $config = null;
         foreach ($this->fixer->getConfigs() as $c) {
             if ($c->getName() === $input->getOption('config')) {
                 $config = $c;
                 break;
             }
         }
         if (null === $config) {
             throw new InvalidConfigurationException(sprintf('The configuration "%s" is not defined.', $input->getOption('config')));
         }
     } elseif (file_exists($configFile)) {
         $config = (include $configFile);
         // verify that the config has an instance of Config
         if (!$config instanceof ConfigInterface) {
             throw new InvalidConfigurationException(sprintf('The config file "%s" does not return a "Symfony\\CS\\ConfigInterface" instance. Got: "%s".', $configFile, is_object($config) ? get_class($config) : gettype($config)));
         }
         if (null !== $stdErr && $configFile) {
             $stdErr->writeln(sprintf('Loaded config from "%s".', $configFile));
         }
     } else {
         $config = $this->defaultConfig;
     }
     // setup location of source(s) to fix
     if (is_file($path)) {
         $config->finder(new \ArrayIterator(array(new \SplFileInfo($path))));
     } elseif ($stdin) {
         $config->finder(new \ArrayIterator(array(new StdinFileInfo())));
     } elseif (null !== $path) {
         $config->setDir($path);
     }
     // setup Linter
     if ($config->usingLinter()) {
         $this->fixer->setLintManager(new LintManager());
     }
     // register custom fixers from config
     $this->fixer->registerCustomFixers($config->getCustomFixers());
     $resolver = new ConfigurationResolver();
     $resolver->setAllFixers($this->fixer->getFixers())->setConfig($config)->setOptions(array('level' => $input->getOption('level'), 'fixers' => $input->getOption('fixers'), 'progress' => OutputInterface::VERBOSITY_VERBOSE <= $verbosity && 'txt' === $input->getOption('format'), 'format' => $input->getOption('format')))->resolve();
     $config->fixers($resolver->getFixers());
     $showProgress = null !== $stdErr && $resolver->getProgress();
     if ($showProgress) {
         $fileProcessedEventListener = function (FixerFileProcessedEvent $event) use($stdErr) {
             $stdErr->write($event->getStatusAsString());
         };
         $this->fixer->setEventDispatcher($this->eventDispatcher);
         $this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
     }
     $isDiff = $input->getOption('diff');
     $this->stopwatch->start('fixFiles');
     $changed = $this->fixer->fix($config, $input->getOption('dry-run'), $isDiff);
     $this->stopwatch->stop('fixFiles');
     if ($showProgress) {
         $this->fixer->setEventDispatcher(null);
         $this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
         $stdErr->writeln('');
         $legend = array();
         foreach (FixerFileProcessedEvent::getStatusMap() as $status) {
             if ($status['symbol'] && $status['description']) {
                 $legend[] = $status['symbol'] . '-' . $status['description'];
             }
         }
         $stdErr->writeln('Legend: ' . implode(', ', array_unique($legend)));
     }
     $i = 1;
     switch ($resolver->getFormat()) {
         case 'txt':
             $fixerDetailLine = false;
             if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                 $fixerDetailLine = $output->isDecorated() ? ' (<comment>%s</comment>)' : ' %s';
             }
             foreach ($changed as $file => $fixResult) {
                 $output->write(sprintf('%4d) %s', $i++, $file));
                 if ($fixerDetailLine) {
                     $output->write(sprintf($fixerDetailLine, implode(', ', $fixResult['appliedFixers'])));
                 }
                 if ($isDiff) {
                     $output->writeln('');
                     $output->writeln('<comment>      ---------- begin diff ----------</comment>');
                     if ($output->isDecorated()) {
                         $diff = implode(PHP_EOL, array_map(function ($string) {
                             $string = preg_replace('/^(\\+){3}/', '<info>+++</info>', $string);
                             $string = preg_replace('/^(\\+){1}/', '<info>+</info>', $string);
                             $string = preg_replace('/^(\\-){3}/', '<error>---</error>', $string);
                             $string = preg_replace('/^(\\-){1}/', '<error>-</error>', $string);
                             $string = str_repeat(' ', 6) . $string;
                             return $string;
                         }, explode(PHP_EOL, OutputFormatter::escape($fixResult['diff']))));
                         $output->writeln($diff);
                     } else {
                         $output->writeln($fixResult['diff'], OutputInterface::OUTPUT_RAW);
                     }
                     $output->writeln('<comment>      ---------- end diff ----------</comment>');
                 }
                 $output->writeln('');
             }
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $output->writeln('Fixing time per file:');
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $output->writeln(sprintf('[%.3f s] %s', $event->getDuration() / 1000, $file));
                 }
                 $output->writeln('');
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $output->writeln(sprintf('%s all files in %.3f seconds, %.3f MB memory used', $input->getOption('dry-run') ? 'Checked' : 'Fixed', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
             break;
         case 'xml':
             $dom = new \DOMDocument('1.0', 'UTF-8');
             $filesXML = $dom->createElement('files');
             $dom->appendChild($filesXML);
             foreach ($changed as $file => $fixResult) {
                 $fileXML = $dom->createElement('file');
                 $fileXML->setAttribute('id', $i++);
                 $fileXML->setAttribute('name', $file);
                 $filesXML->appendChild($fileXML);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $appliedFixersXML = $dom->createElement('applied_fixers');
                     $fileXML->appendChild($appliedFixersXML);
                     foreach ($fixResult['appliedFixers'] as $appliedFixer) {
                         $appliedFixerXML = $dom->createElement('applied_fixer');
                         $appliedFixerXML->setAttribute('name', $appliedFixer);
                         $appliedFixersXML->appendChild($appliedFixerXML);
                     }
                 }
                 if ($isDiff) {
                     $diffXML = $dom->createElement('diff');
                     $diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
                     $fileXML->appendChild($diffXML);
                 }
             }
             $dom->formatOutput = true;
             $output->write($dom->saveXML(), false, OutputInterface::OUTPUT_RAW);
             break;
         case 'json':
             $jFiles = array();
             foreach ($changed as $file => $fixResult) {
                 $jfile = array('name' => $file);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $jfile['appliedFixers'] = $fixResult['appliedFixers'];
                 }
                 if ($isDiff) {
                     $jfile['diff'] = $fixResult['diff'];
                 }
                 $jFiles[] = $jfile;
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $json = array('files' => $jFiles, 'memory' => round($fixEvent->getMemory() / 1024 / 1024, 3), 'time' => array('total' => round($fixEvent->getDuration() / 1000, 3)));
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $jFileTime = array();
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $jFileTime[$file] = round($event->getDuration() / 1000, 3);
                 }
                 $json['time']['files'] = $jFileTime;
             }
             $output->write(json_encode($json), false, OutputInterface::OUTPUT_RAW);
             break;
     }
     if (null !== $stdErr && !$this->errorsManager->isEmpty()) {
         $stdErr->writeln('');
         $stdErr->writeln('Files that were not fixed due to internal error:');
         foreach ($this->errorsManager->getErrors() as $i => $error) {
             $stdErr->writeln(sprintf('%4d) %s', $i + 1, $error['filepath']));
         }
     }
     return 0 === count($changed) ? 0 : 1;
 }
示例#13
0
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $input->getArgument('path');
     $stdin = false;
     if ('-' === $path) {
         $stdin = true;
         // Can't write to STDIN
         $input->setOption('dry-run', true);
     }
     if (null !== $path) {
         $filesystem = new Filesystem();
         if (!$filesystem->isAbsolutePath($path)) {
             $path = getcwd() . DIRECTORY_SEPARATOR . $path;
         }
     }
     $configFile = $input->getOption('config-file');
     if (null === $configFile) {
         if (is_file($path) && ($dirName = pathinfo($path, PATHINFO_DIRNAME))) {
             $configDir = $dirName;
         } elseif ($stdin || null === $path) {
             $configDir = getcwd();
             // path is directory
         } else {
             $configDir = $path;
         }
         $configFile = $configDir . DIRECTORY_SEPARATOR . '.php_cs';
     }
     if ($input->getOption('config')) {
         $config = null;
         foreach ($this->fixer->getConfigs() as $c) {
             if ($c->getName() === $input->getOption('config')) {
                 $config = $c;
                 break;
             }
         }
         if (null === $config) {
             throw new \InvalidArgumentException(sprintf('The configuration "%s" is not defined', $input->getOption('config')));
         }
     } elseif (file_exists($configFile)) {
         $config = (include $configFile);
         // verify that the config has an instance of Config
         if (!$config instanceof Config) {
             throw new \UnexpectedValueException(sprintf('The config file "%s" does not return an instance of Symfony\\CS\\Config\\Config', $configFile));
         }
         if ('txt' === $input->getOption('format')) {
             $output->writeln(sprintf('Loaded config from "%s"', $configFile));
         }
     } else {
         $config = $this->defaultConfig;
     }
     if ($config->usingLinter()) {
         $this->fixer->setLintManager(new LintManager());
     }
     if (is_file($path)) {
         $config->finder(new \ArrayIterator(array(new \SplFileInfo($path))));
     } elseif ($stdin) {
         $config->finder(new \ArrayIterator(array(new StdinFileInfo())));
     } elseif (null !== $path) {
         $config->setDir($path);
     }
     // register custom fixers from config
     $this->fixer->registerCustomFixers($config->getCustomFixers());
     $resolver = new ConfigurationResolver();
     $resolver->setAllFixers($this->fixer->getFixers())->setConfig($config)->setOptions(array('level' => $input->getOption('level'), 'fixers' => $input->getOption('fixers'), 'progress' => $output->isVerbose() && 'txt' === $input->getOption('format')))->resolve();
     $config->fixers($resolver->getFixers());
     $showProgress = $resolver->getProgress();
     if ($showProgress) {
         $fileProcessedEventListener = function (FixerFileProcessedEvent $event) use($output) {
             $output->write($event->getStatusAsString());
         };
         $this->fixer->setEventDispatcher($this->eventDispatcher);
         $this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
     }
     $this->stopwatch->start('fixFiles');
     $changed = $this->fixer->fix($config, $input->getOption('dry-run'), $input->getOption('diff'));
     $this->stopwatch->stop('fixFiles');
     if ($showProgress) {
         $this->fixer->setEventDispatcher(null);
         $this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
         $output->writeln('');
         $legend = array();
         foreach (FixerFileProcessedEvent::getStatusMap() as $status) {
             if ($status['symbol'] && $status['description']) {
                 $legend[] = $status['symbol'] . '-' . $status['description'];
             }
         }
         $output->writeln('Legend: ' . implode(', ', array_unique($legend)));
     }
     $verbosity = $output->getVerbosity();
     $i = 1;
     switch ($input->getOption('format')) {
         case 'txt':
             foreach ($changed as $file => $fixResult) {
                 $output->write(sprintf('%4d) %s', $i++, $file));
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $output->write(sprintf(' (<comment>%s</comment>)', implode(', ', $fixResult['appliedFixers'])));
                 }
                 if ($input->getOption('diff')) {
                     $output->writeln('');
                     $output->writeln('<comment>      ---------- begin diff ----------</comment>');
                     $output->writeln($fixResult['diff']);
                     $output->writeln('<comment>      ---------- end diff ----------</comment>');
                 }
                 $output->writeln('');
             }
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $output->writeln('Fixing time per file:');
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $output->writeln(sprintf('[%.3f s] %s', $event->getDuration() / 1000, $file));
                 }
                 $output->writeln('');
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $output->writeln(sprintf('Fixed all files in %.3f seconds, %.3f MB memory used', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
             break;
         case 'xml':
             $dom = new \DOMDocument('1.0', 'UTF-8');
             $filesXML = $dom->createElement('files');
             $dom->appendChild($filesXML);
             foreach ($changed as $file => $fixResult) {
                 $fileXML = $dom->createElement('file');
                 $fileXML->setAttribute('id', $i++);
                 $fileXML->setAttribute('name', $file);
                 $filesXML->appendChild($fileXML);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $appliedFixersXML = $dom->createElement('applied_fixers');
                     $fileXML->appendChild($appliedFixersXML);
                     foreach ($fixResult['appliedFixers'] as $appliedFixer) {
                         $appliedFixerXML = $dom->createElement('applied_fixer');
                         $appliedFixerXML->setAttribute('name', $appliedFixer);
                         $appliedFixersXML->appendChild($appliedFixerXML);
                     }
                 }
                 if ($input->getOption('diff')) {
                     $diffXML = $dom->createElement('diff');
                     $diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
                     $fileXML->appendChild($diffXML);
                 }
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $timeXML = $dom->createElement('time');
             $memoryXML = $dom->createElement('memory');
             $dom->appendChild($timeXML);
             $dom->appendChild($memoryXML);
             $memoryXML->setAttribute('value', round($fixEvent->getMemory() / 1024 / 1024, 3));
             $memoryXML->setAttribute('unit', 'MB');
             $timeXML->setAttribute('unit', 's');
             $timeTotalXML = $dom->createElement('total');
             $timeTotalXML->setAttribute('value', round($fixEvent->getDuration() / 1000, 3));
             $timeXML->appendChild($timeTotalXML);
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $timeFilesXML = $dom->createElement('files');
                 $timeXML->appendChild($timeFilesXML);
                 $eventCounter = 1;
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $timeFileXML = $dom->createElement('file');
                     $timeFilesXML->appendChild($timeFileXML);
                     $timeFileXML->setAttribute('id', $eventCounter++);
                     $timeFileXML->setAttribute('name', $file);
                     $timeFileXML->setAttribute('value', round($event->getDuration() / 1000, 3));
                 }
             }
             $dom->formatOutput = true;
             $output->write($dom->saveXML());
             break;
         case 'json':
             $jFiles = array();
             foreach ($changed as $file => $fixResult) {
                 $jfile = array('name' => $file);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $jfile['appliedFixers'] = $fixResult['appliedFixers'];
                 }
                 if ($input->getOption('diff')) {
                     $jfile['diff'] = $fixResult['diff'];
                 }
                 $jFiles[] = $jfile;
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $json = array('files' => $jFiles, 'memory' => round($fixEvent->getMemory() / 1024 / 1024, 3), 'time' => array('total' => round($fixEvent->getDuration() / 1000, 3)));
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $jFileTime = array();
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $jFileTime[$file] = round($event->getDuration() / 1000, 3);
                 }
                 $json['time']['files'] = $jFileTime;
             }
             $output->write(json_encode($json));
             break;
         default:
             throw new \InvalidArgumentException(sprintf('The format "%s" is not defined.', $input->getOption('format')));
     }
     if (!$this->errorsManager->isEmpty()) {
         $output->writeLn('');
         $output->writeLn('Files that were not fixed due to internal error:');
         foreach ($this->errorsManager->getErrors() as $i => $error) {
             $output->writeLn(sprintf('%4d) %s', $i + 1, $error['filepath']));
         }
     }
     return empty($changed) ? 0 : 1;
 }
示例#14
0
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $verbosity = $output->getVerbosity();
     $resolver = new ConfigurationResolver();
     $resolver->setCwd(getcwd())->setDefaultConfig($this->defaultConfig)->setFixer($this->fixer)->setOptions(array('allow-risky' => $input->getOption('allow-risky'), 'config' => $input->getOption('config'), 'config-file' => $input->getOption('config-file'), 'dry-run' => $input->getOption('dry-run'), 'rules' => $input->getOption('rules'), 'path' => $input->getArgument('path'), 'progress' => OutputInterface::VERBOSITY_VERBOSE <= $verbosity && 'txt' === $input->getOption('format'), 'using-cache' => $input->getOption('using-cache'), 'cache-file' => $input->getOption('cache-file')))->resolve();
     $config = $resolver->getConfig();
     $configFile = $resolver->getConfigFile();
     if ($configFile && 'txt' === $input->getOption('format')) {
         $output->writeln(sprintf('Loaded config from "%s"', $configFile));
     }
     if ($config->usingLinter()) {
         try {
             $this->fixer->setLinter(new Linter($config->getPhpExecutable()));
         } catch (UnavailableLinterException $e) {
             if ($configFile && 'txt' === $input->getOption('format')) {
                 $output->writeln('Unable to use linter, can not find PHP executable');
             }
         }
     }
     $showProgress = $resolver->getProgress();
     if ($showProgress) {
         $this->fixer->setEventDispatcher($this->eventDispatcher);
         $progressOutput = new ProcessOutput($this->eventDispatcher);
     }
     $this->stopwatch->start('fixFiles');
     $changed = $this->fixer->fix($config, $resolver->isDryRun(), $input->getOption('diff'));
     $this->stopwatch->stop('fixFiles');
     if ($showProgress) {
         $progressOutput->printLegend();
         $this->fixer->setEventDispatcher(null);
     }
     $translator = new Translator('en');
     $translator->addResource('yml', __DIR__ . '/../../Resources/translations/messages.en.yml', 'en');
     $translator->addLoader('yml', new YamlFileLoader());
     switch ($input->getOption('format')) {
         case 'txt':
             $helper = new FixResultTxtOutputHelper($output, $translator, $verbosity, $input->getOption('diff'));
             $helper->write($changed, $this->stopwatch);
             break;
         case 'xml':
             $i = 1;
             $dom = new \DOMDocument('1.0', 'UTF-8');
             // new nodes should be added to this or existing children
             $root = $dom->createElement('report');
             $dom->appendChild($root);
             $filesXML = $dom->createElement('files');
             $root->appendChild($filesXML);
             foreach ($changed as $file => $fixResult) {
                 $fileXML = $dom->createElement('file');
                 $fileXML->setAttribute('id', $i++);
                 $fileXML->setAttribute('name', $file);
                 $filesXML->appendChild($fileXML);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $appliedFixersXML = $dom->createElement('applied_fixers');
                     $fileXML->appendChild($appliedFixersXML);
                     foreach ($fixResult['appliedFixers'] as $appliedFixer) {
                         $appliedFixerXML = $dom->createElement('applied_fixer');
                         $appliedFixerXML->setAttribute('name', $appliedFixer);
                         $appliedFixersXML->appendChild($appliedFixerXML);
                     }
                 }
                 if ($input->getOption('diff')) {
                     $diffXML = $dom->createElement('diff');
                     $diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
                     $fileXML->appendChild($diffXML);
                 }
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $timeXML = $dom->createElement('time');
             $memoryXML = $dom->createElement('memory');
             $root->appendChild($timeXML);
             $root->appendChild($memoryXML);
             $memoryXML->setAttribute('value', round($fixEvent->getMemory() / 1024 / 1024, 3));
             $memoryXML->setAttribute('unit', 'MB');
             $timeXML->setAttribute('unit', 's');
             $timeTotalXML = $dom->createElement('total');
             $timeTotalXML->setAttribute('value', round($fixEvent->getDuration() / 1000, 3));
             $timeXML->appendChild($timeTotalXML);
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $timeFilesXML = $dom->createElement('files');
                 $timeXML->appendChild($timeFilesXML);
                 $eventCounter = 1;
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $timeFileXML = $dom->createElement('file');
                     $timeFilesXML->appendChild($timeFileXML);
                     $timeFileXML->setAttribute('id', $eventCounter++);
                     $timeFileXML->setAttribute('name', $file);
                     $timeFileXML->setAttribute('value', round($event->getDuration() / 1000, 3));
                 }
             }
             $dom->formatOutput = true;
             $output->write($dom->saveXML());
             break;
         case 'json':
             $jFiles = array();
             foreach ($changed as $file => $fixResult) {
                 $jfile = array('name' => $file);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $jfile['appliedFixers'] = $fixResult['appliedFixers'];
                 }
                 if ($input->getOption('diff')) {
                     $jfile['diff'] = $fixResult['diff'];
                 }
                 $jFiles[] = $jfile;
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $json = array('files' => $jFiles, 'memory' => round($fixEvent->getMemory() / 1024 / 1024, 3), 'time' => array('total' => round($fixEvent->getDuration() / 1000, 3)));
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $jFileTime = array();
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $jFileTime[$file] = round($event->getDuration() / 1000, 3);
                 }
                 $json['time']['files'] = $jFileTime;
             }
             $output->write(json_encode($json));
             break;
         default:
             throw new \InvalidArgumentException(sprintf('The format "%s" is not defined.', $input->getOption('format')));
     }
     $invalidErrors = $this->errorsManager->getInvalidErrors();
     if (!empty($invalidErrors)) {
         $this->listErrors($output, 'linting before fixing', $invalidErrors);
     }
     $exceptionErrors = $this->errorsManager->getExceptionErrors();
     if (!empty($exceptionErrors)) {
         $this->listErrors($output, 'fixing', $exceptionErrors);
     }
     $lintErrors = $this->errorsManager->getLintErrors();
     if (!empty($lintErrors)) {
         $this->listErrors($output, 'linting after fixing', $lintErrors);
     }
     $exitStatus = 0;
     if (!empty($invalidErrors)) {
         $exitStatus |= self::EXIT_STATUS_FLAG_HAS_INVALID_FILES;
     }
     if (!empty($changed)) {
         $exitStatus |= self::EXIT_STATUS_FLAG_HAS_CHANGED_FILES;
     }
     return $exitStatus;
 }
 /**
  * @expectedException \LogicException
  */
 public function testUnknownEvent()
 {
     $stopwatch = new Stopwatch();
     $stopwatch->getEvent('foo');
 }
示例#16
0
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $verbosity = $output->getVerbosity();
     $resolver = new ConfigurationResolver();
     $resolver->setCwd(getcwd())->setDefaultConfig($this->defaultConfig)->setFixer($this->fixer)->setOptions(array('config' => $input->getOption('config'), 'config-file' => $input->getOption('config-file'), 'dry-run' => $input->getOption('dry-run'), 'level' => $input->getOption('level'), 'fixers' => $input->getOption('fixers'), 'path' => $input->getArgument('path'), 'progress' => OutputInterface::VERBOSITY_VERBOSE <= $verbosity && 'txt' === $input->getOption('format'), 'using-cache' => $input->getOption('using-cache'), 'cache-file' => $input->getOption('cache-file')))->resolve();
     $config = $resolver->getConfig();
     $configFile = $resolver->getConfigFile();
     if ($configFile && 'txt' === $input->getOption('format')) {
         $output->writeln(sprintf('Loaded config from "%s"', $configFile));
     }
     // register custom fixers from config
     $this->fixer->registerCustomFixers($config->getCustomFixers());
     if ($config->usingLinter()) {
         try {
             $this->fixer->setLinter(new Linter($config->getPhpExecutable()));
         } catch (UnavailableLinterException $e) {
             if ($configFile && 'txt' === $input->getOption('format')) {
                 $output->writeln('Unable to use linter, can not find PHP executable');
             }
         }
     }
     $showProgress = $resolver->getProgress();
     if ($showProgress) {
         $this->fixer->setEventDispatcher($this->eventDispatcher);
         $progressOutput = new ProcessOutput($this->eventDispatcher);
     }
     $this->stopwatch->start('fixFiles');
     $changed = $this->fixer->fix($config, $resolver->isDryRun(), $input->getOption('diff'));
     $this->stopwatch->stop('fixFiles');
     if ($showProgress) {
         $progressOutput->printLegend();
         $this->fixer->setEventDispatcher(null);
     }
     $i = 1;
     switch ($input->getOption('format')) {
         case 'txt':
             foreach ($changed as $file => $fixResult) {
                 $output->write(sprintf('%4d) %s', $i++, $file));
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $output->write(sprintf(' (<comment>%s</comment>)', implode(', ', $fixResult['appliedFixers'])));
                 }
                 if ($input->getOption('diff')) {
                     $output->writeln('');
                     $output->writeln('<comment>      ---------- begin diff ----------</comment>');
                     $output->writeln($fixResult['diff']);
                     $output->writeln('<comment>      ---------- end diff ----------</comment>');
                 }
                 $output->writeln('');
             }
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $output->writeln('Fixing time per file:');
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $output->writeln(sprintf('[%.3f s] %s', $event->getDuration() / 1000, $file));
                 }
                 $output->writeln('');
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $output->writeln(sprintf('Fixed all files in %.3f seconds, %.3f MB memory used', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
             break;
         case 'xml':
             $dom = new \DOMDocument('1.0', 'UTF-8');
             $filesXML = $dom->createElement('files');
             $dom->appendChild($filesXML);
             foreach ($changed as $file => $fixResult) {
                 $fileXML = $dom->createElement('file');
                 $fileXML->setAttribute('id', $i++);
                 $fileXML->setAttribute('name', $file);
                 $filesXML->appendChild($fileXML);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $appliedFixersXML = $dom->createElement('applied_fixers');
                     $fileXML->appendChild($appliedFixersXML);
                     foreach ($fixResult['appliedFixers'] as $appliedFixer) {
                         $appliedFixerXML = $dom->createElement('applied_fixer');
                         $appliedFixerXML->setAttribute('name', $appliedFixer);
                         $appliedFixersXML->appendChild($appliedFixerXML);
                     }
                 }
                 if ($input->getOption('diff')) {
                     $diffXML = $dom->createElement('diff');
                     $diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
                     $fileXML->appendChild($diffXML);
                 }
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $timeXML = $dom->createElement('time');
             $memoryXML = $dom->createElement('memory');
             $dom->appendChild($timeXML);
             $dom->appendChild($memoryXML);
             $memoryXML->setAttribute('value', round($fixEvent->getMemory() / 1024 / 1024, 3));
             $memoryXML->setAttribute('unit', 'MB');
             $timeXML->setAttribute('unit', 's');
             $timeTotalXML = $dom->createElement('total');
             $timeTotalXML->setAttribute('value', round($fixEvent->getDuration() / 1000, 3));
             $timeXML->appendChild($timeTotalXML);
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $timeFilesXML = $dom->createElement('files');
                 $timeXML->appendChild($timeFilesXML);
                 $eventCounter = 1;
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $timeFileXML = $dom->createElement('file');
                     $timeFilesXML->appendChild($timeFileXML);
                     $timeFileXML->setAttribute('id', $eventCounter++);
                     $timeFileXML->setAttribute('name', $file);
                     $timeFileXML->setAttribute('value', round($event->getDuration() / 1000, 3));
                 }
             }
             $dom->formatOutput = true;
             $output->write($dom->saveXML());
             break;
         case 'json':
             $jFiles = array();
             foreach ($changed as $file => $fixResult) {
                 $jfile = array('name' => $file);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $jfile['appliedFixers'] = $fixResult['appliedFixers'];
                 }
                 if ($input->getOption('diff')) {
                     $jfile['diff'] = $fixResult['diff'];
                 }
                 $jFiles[] = $jfile;
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $json = array('files' => $jFiles, 'memory' => round($fixEvent->getMemory() / 1024 / 1024, 3), 'time' => array('total' => round($fixEvent->getDuration() / 1000, 3)));
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $jFileTime = array();
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $jFileTime[$file] = round($event->getDuration() / 1000, 3);
                 }
                 $json['time']['files'] = $jFileTime;
             }
             $output->write(json_encode($json));
             break;
         default:
             throw new \InvalidArgumentException(sprintf('The format "%s" is not defined.', $input->getOption('format')));
     }
     $invalidErrors = $this->errorsManager->getInvalidErrors();
     if (!empty($invalidErrors)) {
         $this->listErrors($output, 'linting before fixing', $invalidErrors);
     }
     $exceptionErrors = $this->errorsManager->getExceptionErrors();
     if (!empty($exceptionErrors)) {
         $this->listErrors($output, 'fixing', $exceptionErrors);
     }
     $lintErrors = $this->errorsManager->getLintErrors();
     if (!empty($lintErrors)) {
         $this->listErrors($output, 'linting after fixing', $lintErrors);
     }
     return !$resolver->isDryRun() || empty($changed) ? 0 : 3;
 }
示例#17
0
 /**
  * Execute the command line :
  * php app/console swagger:generate --file=Resources/example/swagger.json.
  *
  *
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $style = new OutputFormatterStyle('red', 'yellow', array('bold', 'blink'));
     $output->getFormatter()->setStyle('fire', $style);
     $verbosity = $output->getVerbosity();
     $manager = $this->getCreatorsManager();
     $conf = $manager->getConfig();
     if (isset($conf['definitions'])) {
         $output->writeln('Start creating definitions...');
         $manager->createDefinitions($conf['definitions'], $output);
         $output->writeln('Finish creating definitions.');
     } else {
         $output->writeln('');
         $output->writeln('WARNING: definitions not found');
     }
     if (isset($conf['paths'])) {
         $output->writeln('Start creating controllers...');
         $buildRoutingAnnotations = 'annotation' === $manager->getRoutingType();
         $manager->createControllers($conf['paths'], $buildRoutingAnnotations, $output);
         $output->writeln('Finish creating controllers.');
         if ('yaml' == $manager->getRoutingType()) {
             $output->writeln('Start creating routing yaml file...');
             $manager->createRoutingYamlFile($conf['paths'], $output);
             $output->writeln('Finish creating routing yaml file.');
         }
     } else {
         $output->writeln('');
         $output->writeln('WARNING: paths not found');
     }
     //security:
     $security = isset($conf['security']) ? $conf['security'] : null;
     $paths = isset($conf['paths']) ? $conf['paths'] : array();
     $manager->createSecurityYamlFile($conf['basePath'], $security, $paths, $output);
     $output->writeln('Finish creating security yaml file.');
     if (!$input->getOption('no-csfixer')) {
         $watcher = new Stopwatch();
         $eventDispatcher = new EventDispatcher();
         $dirs = array($manager->getOutputPath() . 'Controller/Api/', $manager->getOutputPath() . 'Api/Model');
         $fixer = new fixer();
         $fixer->setStopwatch(new Stopwatch());
         $fixer->registerBuiltInFixers();
         $fixer->registerBuiltInConfigs();
         $config = new config();
         $config->fixers($fixer->getFixers());
         foreach ($dirs as $dir) {
             if (file_exists($dir) && is_dir($dir)) {
                 $config->getFinder()->setDir($dir);
             }
         }
         $fileProcessedEventListener = function (FixerFileProcessedEvent $event) use($output) {
             $output->write($event->getStatusAsString());
         };
         $fixer->setEventDispatcher($eventDispatcher);
         $eventDispatcher->addListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
         $watcher->start('fixFiles');
         $changed = $fixer->fix($config);
         $watcher->stop('fixFiles');
         $fixer->setEventDispatcher(null);
         $eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
         $output->writeln('');
         $legend = array();
         foreach (FixerFileProcessedEvent::getStatusMap() as $status) {
             if ($status['symbol'] && $status['description']) {
                 $legend[] = $status['symbol'] . '-' . $status['description'];
             }
         }
         $output->writeln('Legend: ' . implode(', ', array_unique($legend)));
         if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
             $i = 1;
             foreach ($changed as $file => $fixResult) {
                 $output->writeln(sprintf('%4d) %s', $i++, $file));
             }
             $output->writeln('');
             $fixEvent = $watcher->getEvent('fixFiles');
             $output->writeln(sprintf('Fixed all files in %.3f seconds, %.3f MB memory used', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
         }
     }
 }
示例#18
0
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : null;
     if ($stdErr && extension_loaded('xdebug')) {
         $stdErr->writeln(sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'You are running php-cs-fixer with xdebug enabled. This has a major impact on runtime performance.'));
     }
     $verbosity = $output->getVerbosity();
     $resolver = new ConfigurationResolver();
     $resolver->setCwd(getcwd())->setDefaultConfig($this->defaultConfig)->setFixer($this->fixer)->setOptions(array('allow-risky' => $input->getOption('allow-risky'), 'config' => $input->getOption('config'), 'config-file' => $input->getOption('config-file'), 'dry-run' => $input->getOption('dry-run'), 'rules' => $input->getOption('rules'), 'path' => $input->getArgument('path'), 'progress' => OutputInterface::VERBOSITY_VERBOSE <= $verbosity && 'txt' === $input->getOption('format'), 'using-cache' => $input->getOption('using-cache'), 'cache-file' => $input->getOption('cache-file'), 'format' => $input->getOption('format')))->resolve();
     $config = $resolver->getConfig();
     $configFile = $resolver->getConfigFile();
     if ($configFile && 'txt' === $input->getOption('format')) {
         $output->writeln(sprintf('Loaded config from "%s"', $configFile));
     }
     if ($config->usingLinter()) {
         try {
             $this->fixer->setLinter(new Linter($config->getPhpExecutable()));
         } catch (UnavailableLinterException $e) {
             if ($configFile && 'txt' === $input->getOption('format')) {
                 $output->writeln('Unable to use linter, can not find PHP executable');
             }
         }
     }
     $showProgress = $resolver->getProgress();
     if ($showProgress) {
         $this->fixer->setEventDispatcher($this->eventDispatcher);
         $progressOutput = new ProcessOutput($this->eventDispatcher);
     }
     $this->stopwatch->start('fixFiles');
     $changed = $this->fixer->fix($config, $resolver->isDryRun(), $input->getOption('diff'));
     $this->stopwatch->stop('fixFiles');
     if ($showProgress) {
         $progressOutput->printLegend();
         $this->fixer->setEventDispatcher(null);
     }
     $i = 1;
     switch ($resolver->getFormat()) {
         case 'txt':
             $fixerDetailLine = false;
             if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                 $fixerDetailLine = $output->isDecorated() ? ' (<comment>%s</comment>)' : ' %s';
             }
             foreach ($changed as $file => $fixResult) {
                 $output->write(sprintf('%4d) %s', $i++, $file));
                 if ($fixerDetailLine) {
                     $output->write(sprintf($fixerDetailLine, implode(', ', $fixResult['appliedFixers'])));
                 }
                 if ($input->getOption('diff')) {
                     $output->writeln('');
                     $output->writeln('<comment>      ---------- begin diff ----------</comment>');
                     $output->writeln($fixResult['diff']);
                     $output->writeln('<comment>      ---------- end diff ----------</comment>');
                 }
                 $output->writeln('');
             }
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $output->writeln('Fixing time per file:');
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $output->writeln(sprintf('[%.3f s] %s', $event->getDuration() / 1000, $file));
                 }
                 $output->writeln('');
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $output->writeln(sprintf('%s all files in %.3f seconds, %.3f MB memory used', $input->getOption('dry-run') ? 'Checked' : 'Fixed', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
             break;
         case 'xml':
             $dom = new \DOMDocument('1.0', 'UTF-8');
             // new nodes should be added to this or existing children
             $root = $dom->createElement('report');
             $dom->appendChild($root);
             $filesXML = $dom->createElement('files');
             $root->appendChild($filesXML);
             foreach ($changed as $file => $fixResult) {
                 $fileXML = $dom->createElement('file');
                 $fileXML->setAttribute('id', $i++);
                 $fileXML->setAttribute('name', $file);
                 $filesXML->appendChild($fileXML);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $appliedFixersXML = $dom->createElement('applied_fixers');
                     $fileXML->appendChild($appliedFixersXML);
                     foreach ($fixResult['appliedFixers'] as $appliedFixer) {
                         $appliedFixerXML = $dom->createElement('applied_fixer');
                         $appliedFixerXML->setAttribute('name', $appliedFixer);
                         $appliedFixersXML->appendChild($appliedFixerXML);
                     }
                 }
                 if ($input->getOption('diff')) {
                     $diffXML = $dom->createElement('diff');
                     $diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
                     $fileXML->appendChild($diffXML);
                 }
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $timeXML = $dom->createElement('time');
             $memoryXML = $dom->createElement('memory');
             $root->appendChild($timeXML);
             $root->appendChild($memoryXML);
             $memoryXML->setAttribute('value', round($fixEvent->getMemory() / 1024 / 1024, 3));
             $memoryXML->setAttribute('unit', 'MB');
             $timeXML->setAttribute('unit', 's');
             $timeTotalXML = $dom->createElement('total');
             $timeTotalXML->setAttribute('value', round($fixEvent->getDuration() / 1000, 3));
             $timeXML->appendChild($timeTotalXML);
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $timeFilesXML = $dom->createElement('files');
                 $timeXML->appendChild($timeFilesXML);
                 $eventCounter = 1;
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $timeFileXML = $dom->createElement('file');
                     $timeFilesXML->appendChild($timeFileXML);
                     $timeFileXML->setAttribute('id', $eventCounter++);
                     $timeFileXML->setAttribute('name', $file);
                     $timeFileXML->setAttribute('value', round($event->getDuration() / 1000, 3));
                 }
             }
             $dom->formatOutput = true;
             $output->write($dom->saveXML());
             break;
         case 'json':
             $jFiles = array();
             foreach ($changed as $file => $fixResult) {
                 $jfile = array('name' => $file);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $jfile['appliedFixers'] = $fixResult['appliedFixers'];
                 }
                 if ($input->getOption('diff')) {
                     $jfile['diff'] = $fixResult['diff'];
                 }
                 $jFiles[] = $jfile;
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $json = array('files' => $jFiles, 'memory' => round($fixEvent->getMemory() / 1024 / 1024, 3), 'time' => array('total' => round($fixEvent->getDuration() / 1000, 3)));
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $jFileTime = array();
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $jFileTime[$file] = round($event->getDuration() / 1000, 3);
                 }
                 $json['time']['files'] = $jFileTime;
             }
             $output->write(json_encode($json));
             break;
     }
     $invalidErrors = $this->errorsManager->getInvalidErrors();
     if (!empty($invalidErrors)) {
         $this->listErrors($output, 'linting before fixing', $invalidErrors);
     }
     $exceptionErrors = $this->errorsManager->getExceptionErrors();
     if (!empty($exceptionErrors)) {
         $this->listErrors($output, 'fixing', $exceptionErrors);
     }
     $lintErrors = $this->errorsManager->getLintErrors();
     if (!empty($lintErrors)) {
         $this->listErrors($output, 'linting after fixing', $lintErrors);
     }
     $exitStatus = 0;
     if ($resolver->isDryRun()) {
         if (!empty($invalidErrors)) {
             $exitStatus |= self::EXIT_STATUS_FLAG_HAS_INVALID_FILES;
         }
         if (!empty($changed)) {
             $exitStatus |= self::EXIT_STATUS_FLAG_HAS_CHANGED_FILES;
         }
     }
     return $exitStatus;
 }
示例#19
0
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $input->getArgument('path');
     $stdin = false;
     if ('-' === $path) {
         $stdin = true;
         // Can't write to STDIN
         $input->setOption('dry-run', true);
     }
     if (null !== $path) {
         $filesystem = new Filesystem();
         if (!$filesystem->isAbsolutePath($path)) {
             $path = getcwd() . DIRECTORY_SEPARATOR . $path;
         }
     }
     $configFile = $input->getOption('config-file');
     if (null === $configFile) {
         if (is_file($path) && ($dirName = pathinfo($path, PATHINFO_DIRNAME))) {
             $configDir = $dirName;
         } elseif ($stdin || null === $path) {
             $configDir = getcwd();
             // path is directory
         } else {
             $configDir = $path;
         }
         $configFile = $configDir . DIRECTORY_SEPARATOR . '.php_cs';
     }
     if ($input->getOption('config')) {
         $config = null;
         foreach ($this->fixer->getConfigs() as $c) {
             if ($c->getName() === $input->getOption('config')) {
                 $config = $c;
                 break;
             }
         }
         if (null === $config) {
             throw new \InvalidArgumentException(sprintf('The configuration "%s" is not defined', $input->getOption('config')));
         }
     } elseif (file_exists($configFile)) {
         $config = (include $configFile);
         // verify that the config has an instance of Config
         if (!$config instanceof Config) {
             throw new \UnexpectedValueException(sprintf('The config file "%s" does not return an instance of Symfony\\CS\\Config\\Config', $configFile));
         } else {
             $output->writeln(sprintf('Loaded config from "%s"', $configFile));
         }
     } else {
         $config = $this->defaultConfig;
     }
     if (is_file($path)) {
         $config->finder(new \ArrayIterator(array(new \SplFileInfo($path))));
     } elseif ($stdin) {
         $config->finder(new \ArrayIterator(array(new StdinFileInfo())));
     } elseif (null !== $path) {
         $config->setDir($path);
     }
     // register custom fixers from config
     $this->fixer->registerCustomFixers($config->getCustomFixers());
     $allFixers = $this->fixer->getFixers();
     switch ($input->getOption('level')) {
         case 'psr0':
             $level = FixerInterface::PSR0_LEVEL;
             break;
         case 'psr1':
             $level = FixerInterface::PSR1_LEVEL;
             break;
         case 'psr2':
             $level = FixerInterface::PSR2_LEVEL;
             break;
         case 'symfony':
             $level = FixerInterface::SYMFONY_LEVEL;
             break;
         case null:
             $fixerOption = $input->getOption('fixers');
             if (empty($fixerOption) || preg_match('{(^|,)-}', $fixerOption)) {
                 $level = $config->getFixers();
             } else {
                 $level = null;
             }
             break;
         default:
             throw new \InvalidArgumentException(sprintf('The level "%s" is not defined.', $input->getOption('level')));
     }
     // select base fixers for the given level
     $fixers = array();
     if (is_array($level)) {
         foreach ($allFixers as $fixer) {
             if (in_array($fixer->getName(), $level, true) || in_array($fixer, $level, true)) {
                 $fixers[] = $fixer;
             }
         }
     } else {
         foreach ($allFixers as $fixer) {
             if ($fixer->getLevel() === ($fixer->getLevel() & $level)) {
                 $fixers[] = $fixer;
             }
         }
     }
     // remove/add fixers based on the fixers option
     if (preg_match('{(^|,)-}', $input->getOption('fixers'))) {
         foreach ($fixers as $key => $fixer) {
             if (preg_match('{(^|,)-' . preg_quote($fixer->getName()) . '}', $input->getOption('fixers'))) {
                 unset($fixers[$key]);
             }
         }
     } elseif ($input->getOption('fixers')) {
         $names = array_map('trim', explode(',', $input->getOption('fixers')));
         foreach ($allFixers as $fixer) {
             if (in_array($fixer->getName(), $names, true) && !in_array($fixer, $fixers, true)) {
                 $fixers[] = $fixer;
             }
         }
     }
     $config->fixers($fixers);
     $verbosity = $output->getVerbosity();
     $listenForFixerFileProcessedEvent = OutputInterface::VERBOSITY_VERY_VERBOSE <= $verbosity;
     if ($listenForFixerFileProcessedEvent) {
         $fileProcessedEventListener = function (FixerFileProcessedEvent $event) use($output) {
             $output->write($event->getStatusAsString());
         };
     }
     if ($listenForFixerFileProcessedEvent) {
         $this->fixer->setEventDispatcher($this->eventDispatcher);
         $this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
     }
     $this->stopwatch->start('fixFiles');
     $changed = $this->fixer->fix($config, $input->getOption('dry-run'), $input->getOption('diff'));
     $this->stopwatch->stop('fixFiles');
     if ($listenForFixerFileProcessedEvent) {
         $this->fixer->setEventDispatcher(null);
         $this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
         $output->writeln('');
     }
     $i = 1;
     switch ($input->getOption('format')) {
         case 'txt':
             foreach ($changed as $file => $fixResult) {
                 $output->write(sprintf('%4d) %s', $i++, $file));
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $output->write(sprintf(' (<comment>%s</comment>)', implode(', ', $fixResult['appliedFixers'])));
                     if ($input->getOption('diff')) {
                         $output->writeln('');
                         $output->writeln('<comment>      ---------- begin diff ----------</comment>');
                         $output->writeln($fixResult['diff']);
                         $output->writeln('<comment>      ---------- end diff ----------</comment>');
                     }
                 }
                 $output->writeln('');
             }
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $output->writeln('Fixing time per file:');
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $output->writeln(sprintf('[%.3f s] %s', $event->getDuration() / 1000, $file));
                 }
                 $output->writeln('');
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $output->writeln(sprintf('Fixed all files in %.3f seconds, %.3f MB memory used', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
             break;
         case 'xml':
             $dom = new \DOMDocument('1.0', 'UTF-8');
             $dom->appendChild($filesXML = $dom->createElement('files'));
             foreach ($changed as $file => $fixResult) {
                 $filesXML->appendChild($fileXML = $dom->createElement('file'));
                 $fileXML->setAttribute('id', $i++);
                 $fileXML->setAttribute('name', $file);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $fileXML->appendChild($appliedFixersXML = $dom->createElement('applied_fixers'));
                     foreach ($fixResult['appliedFixers'] as $appliedFixer) {
                         $appliedFixersXML->appendChild($appliedFixerXML = $dom->createElement('applied_fixer'));
                         $appliedFixerXML->setAttribute('name', $appliedFixer);
                     }
                     if ($input->getOption('diff')) {
                         $fileXML->appendChild($diffXML = $dom->createElement('diff'));
                         $diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
                     }
                 }
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $timeXML = $dom->createElement('time');
             $memoryXML = $dom->createElement('memory');
             $dom->appendChild($timeXML);
             $dom->appendChild($memoryXML);
             $memoryXML->setAttribute('value', round($fixEvent->getMemory() / 1024 / 1024, 3));
             $memoryXML->setAttribute('unit', 'MB');
             $timeXML->setAttribute('unit', 's');
             $timeTotalXML = $dom->createElement('total');
             $timeTotalXML->setAttribute('value', round($fixEvent->getDuration() / 1000, 3));
             $timeXML->appendChild($timeTotalXML);
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $timeFilesXML = $dom->createElement('files');
                 $timeXML->appendChild($timeFilesXML);
                 $eventCounter = 1;
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $timeFileXML = $dom->createElement('file');
                     $timeFilesXML->appendChild($timeFileXML);
                     $timeFileXML->setAttribute('id', $eventCounter++);
                     $timeFileXML->setAttribute('name', $file);
                     $timeFileXML->setAttribute('value', round($event->getDuration() / 1000, 3));
                 }
             }
             $dom->formatOutput = true;
             $output->write($dom->saveXML());
             break;
         case 'json':
             $jFiles = array();
             foreach ($changed as $file => $fixResult) {
                 $jfile = array('name' => $file);
                 if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                     $jfile['appliedFixers'] = $fixResult['appliedFixers'];
                     if ($input->getOption('diff')) {
                         $jfile['diff'] = $fixResult['diff'];
                     }
                 }
                 $jFiles[] = $jfile;
             }
             $fixEvent = $this->stopwatch->getEvent('fixFiles');
             $json = array('files' => $jFiles, 'memory' => round($fixEvent->getMemory() / 1024 / 1024, 3), 'time' => array('total' => round($fixEvent->getDuration() / 1000, 3)));
             if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                 $jFileTime = array();
                 foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                     if ('__section__' === $file) {
                         continue;
                     }
                     $jFileTime[$file] = round($event->getDuration() / 1000, 3);
                 }
                 $json['time']['files'] = $jFileTime;
             }
             $output->write(json_encode($json));
             break;
         default:
             throw new \InvalidArgumentException(sprintf('The format "%s" is not defined.', $input->getOption('format')));
     }
     return empty($changed) ? 0 : 1;
 }