Example #1
0
 public function testCanFixWithConfigInterfaceImplementation()
 {
     $config = $this->getMockBuilder('PhpCsFixer\\ConfigInterface')->getMock();
     $config->expects($this->any())->method('getFixers')->willReturn(array());
     $config->expects($this->any())->method('getRules')->willReturn(array());
     $config->expects($this->any())->method('getFinder')->willReturn(new \ArrayIterator(array()));
     $fixer = new Fixer();
     $fixer->fix($config);
 }
 /**
  * Applies the given fixers on the input and checks the result.
  *
  * It will write the input to a temp file. The file will be fixed by a Fixer instance
  * configured with the given fixers. The result is compared with the expected output.
  * It checks if no errors were reported during the fixing.
  *
  * @param IntegrationCase $case
  */
 protected function doTest($case)
 {
     if (defined('HHVM_VERSION') && false === $case->getRequirement('hhvm')) {
         $this->markTestSkipped('HHVM is not supported.');
     }
     if (version_compare(PHP_VERSION, $case->getRequirement('php')) < 0) {
         $this->markTestSkipped(sprintf('PHP %s (or later) is required.', $case->getRequirement('php')));
     }
     $input = $case->getInputCode();
     $expected = $case->getExpectedCode();
     $input = $case->hasInputCode() ? $input : $expected;
     $this->assertNull($this->lintSource($input));
     $fixer = new Fixer();
     $tmpFile = static::getTempFile();
     if (false === @file_put_contents($tmpFile, $input)) {
         throw new IOException(sprintf('Failed to write to tmp. file "%s".', $tmpFile));
     }
     $changed = $fixer->fixFile(new \SplFileInfo($tmpFile), $case->getFixers(), false, true, new FileCacheManager(false, null, $case->getFixers()));
     $errorsManager = $fixer->getErrorsManager();
     if (!$errorsManager->isEmpty()) {
         $errors = $errorsManager->getExceptionErrors();
         $this->assertEmpty($errors, sprintf('Errors reported during fixing: %s', $this->implodeErrors($errors)));
         $errors = $errorsManager->getInvalidErrors();
         $this->assertEmpty($errors, sprintf('Errors reported during linting before fixing: %s.', $this->implodeErrors($errors)));
         $errors = $errorsManager->getLintErrors();
         $this->assertEmpty($errors, sprintf('Errors reported during linting after fixing: %s.', $this->implodeErrors($errors)));
     }
     if (!$case->hasInputCode()) {
         $this->assertEmpty($changed, sprintf("Expected no changes made to test \"%s\" in \"%s\".\nFixers applied:\n\"%s\".\nDiff.:\n\"%s\".", $case->getTitle(), $case->getFileName(), $changed === null ? '[None]' : implode(',', $changed['appliedFixers']), $changed === null ? '[None]' : $changed['diff']));
         return;
     }
     $this->assertNotEmpty($changed, sprintf('Expected changes made to test "%s" in "%s".', $case->getTitle(), $case->getFileName()));
     $fixedInputCode = file_get_contents($tmpFile);
     $this->assertSame($expected, $fixedInputCode, sprintf('Expected changes do not match result for "%s" in "%s".', $case->getTitle(), $case->getFileName()));
     if ($case->shouldCheckPriority()) {
         $priorities = array_map(function (FixerInterface $fixer) {
             return $fixer->getPriority();
         }, $case->getFixers());
         $this->assertNotCount(1, array_unique($priorities), 'All used fixers must not have the same priority, integration tests should cover fixers with different priorities.');
         $tmpFile = static::getTempFile();
         if (false === @file_put_contents($tmpFile, $input)) {
             throw new IOException(sprintf('Failed to write to tmp. file "%s".', $tmpFile));
         }
         $changed = $fixer->fixFile(new \SplFileInfo($tmpFile), array_reverse($case->getFixers()), false, true, new FileCacheManager(false, null, $case->getFixers()));
         $fixedInputCodeWithReversedFixers = file_get_contents($tmpFile);
         $this->assertNotSame($fixedInputCode, $fixedInputCodeWithReversedFixers, 'Set priorities must be significant. If fixers used in reverse order return same output then the integration test is not sufficient or the priority relation between used fixers should not be set.');
     }
     // run the test again with the `expected` part, this should always stay the same
     $this->testIntegration($case->setTitle($case->getTitle() . ' "--EXPECT-- part run"')->setInputCode(null));
 }
 /**
  * Use php cs fixer to have a nice formatting of generated files
  *
  * @param string $directory
  *
  * @return array|void
  */
 protected function fix($directory)
 {
     if (!class_exists('PhpCsFixer\\Config')) {
         return;
     }
     /** @var Config $fixerConfig */
     $fixerConfig = $this->fixerConfig;
     if (null === $fixerConfig) {
         $fixerConfig = Config::create()->setRiskyAllowed(true)->setRules(array('@Symfony' => true, 'simplified_null_return' => false, 'concat_without_spaces' => false, 'double_arrow_multiline_whitespaces' => false, 'unalign_equals' => false, 'unalign_double_arrow' => false, 'align_double_arrow' => true, 'align_equals' => true, 'concat_with_spaces' => true, 'ordered_imports' => true, 'phpdoc_order' => true, 'short_array_syntax' => true));
         $resolver = new ConfigurationResolver();
         $resolver->setDefaultConfig($fixerConfig);
         $resolver->resolve();
     }
     $finder = new Finder();
     $finder->in($directory);
     $fixerConfig->finder($finder);
     $fixer = new Fixer();
     return $fixer->fix($fixerConfig);
 }
Example #4
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)->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'), '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;
 }