Example #1
0
 /**
  * Compare generated class with expected class into resource dir
  *
  * @param string         $resourcesDir     fullPath resources dir
  * @param string         $namespace        namespace of class
  * @param string         $className        class name
  * @param string         $directoryOutput  output directory to compare from
  * @param bool           $createIfNotExist generate file if not exist equals on genereted one
  */
 private function compareClassPhp($resourcesDir, $namespace, $className, $directoryOutput, $createIfNotExist = false)
 {
     $fileExpected = $resourcesDir . '/' . $className . '.php';
     $fileName = $className . '.php';
     $fileActual = $directoryOutput . '/' . $namespace . '/' . $fileName;
     // echo file_get_contents($fileActual);
     /** @var \Symfony\CS\Config\Config $config */
     $config = ConfigBridge::create(__DIR__ . '/../../');
     $config->setUsingCache(false);
     $fixer = new Fixer();
     $fixer->registerBuiltInFixers();
     $fixer->registerBuiltInConfigs();
     // $fixer->setLintManager(new LintManager());
     $fixer->registerCustomFixers($config->getCustomFixers());
     $cresolver = new ConfigurationResolver();
     $cresolver->setConfig($config);
     $cresolver->setAllFixers($fixer->getFixers());
     $cresolver->setOption('level', 'symfony');
     // $cresolver->setOption('fixers', 'eof_ending,strict_param,short_array_syntax,trailing_spaces,indentation,line_after_namespace,php_closing_tag');
     $cresolver->setOption('fixers', 'binary_operator_spaces,blank_line_after_namespace,blank_line_after_opening_tag,blank_line_before_return,
                                      braces,cast_spaces,class_definition,concat_without_spaces,declare_equal_normalize,elseif,encoding,
                                      full_opening_tag,function_declaration,function_typehint_space,hash_to_slash_comment,heredoc_to_nowdoc,
                                      include,lowercase_cast,lowercase_constants,lowercase_keywords,method_argument_space,method_separation,
                                      native_function_casing,new_with_braces,no_alias_functions,no_blank_lines_after_class_opening,
                                      no_blank_lines_after_phpdoc,no_closing_tag,no_empty_phpdoc,no_empty_statement,
                                      no_extra_consecutive_blank_lines,no_leading_import_slash,no_leading_namespace_whitespace,
                                      no_multiline_whitespace_around_double_arrow,no_short_bool_cast,no_singleline_whitespace_before_semicolons,
                                      no_spaces_after_function_name,no_spaces_inside_offset,no_spaces_inside_parenthesis,no_tab_indentation,
                                      no_trailing_comma_in_list_call,no_trailing_comma_in_singleline_array,no_trailing_whitespace,
                                      no_trailing_whitespace_in_comment,no_unneeded_control_parentheses,no_unreachable_default_argument_value,
                                      no_unused_imports,no_whitespace_before_comma_in_array,no_whitespace_in_blank_line,normalize_index_brace,
                                      object_operator_without_whitespace,phpdoc_align,phpdoc_annotation_without_dot,phpdoc_indent,
                                      phpdoc_inline_tag,phpdoc_no_access,phpdoc_no_empty_return,phpdoc_no_package,phpdoc_scalar,
                                      phpdoc_separation,phpdoc_single_line_var_spacing,phpdoc_to_comment,phpdoc_trim,
                                      phpdoc_type_to_var,phpdoc_types,phpdoc_var_without_name,pre_increment,print_to_echo,psr4,self_accessor,
                                      short_scalar_cast,simplified_null_return,single_blank_line_at_eof,single_blank_line_before_namespace,
                                      single_class_element_per_statement,single_import_per_statement,single_line_after_imports,single_quote,
                                      space_after_semicolon,standardize_not_equals,switch_case_semicolon_to_colon,switch_case_space,
                                      ternary_operator_spaces,trailing_comma_in_multiline_array,trim_array_spaces,unalign_double_arrow,
                                      unalign_equals,unary_operator_spaces,unix_line_endings,visibility_required,whitespace_after_comma_in_array,
                                      short_array_syntax,linebreak_after_opening_tag,ordered_imports,no_useless_return,phpdoc_order,ordered_use,
                                      -phpdoc_short_description');
     $cresolver->resolve();
     $config->fixers($cresolver->getFixers());
     // $fileCacheManager = new FileCacheManager(false, $directoryOutput, $cresolver->getFixers());
     $iFile = new SplFileInfo($fileActual, $directoryOutput . '/' . $namespace, $fileName);
     // $fixer->fixFile($iFile, $cresolver->getFixers(), false, false, $fileCacheManager);
     $config->finder(new \ArrayIterator([$iFile]));
     // $changed =
     $fixer->fix($config, false, false);
     $fileActualFixed = $iFile->getPathname();
     $actual = file_get_contents($fileActualFixed);
     if (!file_exists($fileExpected) && $createIfNotExist) {
         file_put_contents($fileExpected, $actual);
     }
     $expected = file_get_contents($fileExpected);
     $this->assertSame($expected, $actual, 'Classe ' . $className . ' invalid');
 }
Example #2
0
 /**
  * Print files
  *
  * @param File[] $files
  * @param string $directory
  */
 public function printFiles($files, $directory)
 {
     foreach ($files as $file) {
         if (!file_exists(dirname($file->getFilename()))) {
             mkdir(dirname($file->getFilename()), 0755, true);
         }
         file_put_contents($file->getFilename(), $this->prettyPrinter->prettyPrintFile([$file->getNode()]));
     }
     if ($this->fixer !== null) {
         $config = Config::create()->setRiskyAllowed(true)->setRules(array('@Symfony' => true, 'empty_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, 'newline_after_open_tag' => true, 'ordered_use' => true, 'phpdoc_order' => true, 'short_array_syntax' => true))->finder(DefaultFinder::create()->in($directory));
         $resolver = new ConfigurationResolver();
         $resolver->setDefaultConfig($config);
         $resolver->resolve();
         $this->fixer->fix($config);
     }
 }
Example #3
0
 /**
  * @covers Symfony\CS\Fixer::fix
  * @covers Symfony\CS\Fixer::fixFile
  * @covers Symfony\CS\Fixer::prepareFixers
  */
 public function testThatFixSuccessfully()
 {
     $fixer = new Fixer();
     $fixer->addFixer(new \Symfony\CS\Fixer\PSR2\VisibilityFixer());
     $fixer->addFixer(new \Symfony\CS\Fixer\PSR0\Psr0Fixer());
     //will be ignored cause of test keyword in namespace
     $config = Config::create()->finder(new \DirectoryIterator(__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'FixerTest'));
     $config->fixers($fixer->getFixers());
     $changed = $fixer->fix($config, true, true);
     $pathToInvalidFile = __DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'FixerTest' . DIRECTORY_SEPARATOR . 'somefile.php';
     $this->assertCount(1, $changed);
     $this->assertCount(2, $changed[$pathToInvalidFile]);
     $this->assertSame(array('appliedFixers', 'diff'), array_keys($changed[$pathToInvalidFile]));
     $this->assertSame('visibility', $changed[$pathToInvalidFile]['appliedFixers'][0]);
 }
Example #4
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;
 }
Example #5
0
 public function testCanFixWithConfigInterfaceImplementation()
 {
     $config = $this->getMockBuilder('Symfony\\CS\\ConfigInterface')->getMock();
     $config->expects($this->any())->method('getFixers')->willReturn(array());
     $config->expects($this->any())->method('getFinder')->willReturn(array());
     $fixer = new Fixer();
     $fixer->fix($config);
 }
Example #6
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;
 }
 /**
  * Uses PHP CS Fixer to make generated files following PSR and Symfony Coding Standards.
  *
  * @param array $files
  */
 private function fixCs(array $files)
 {
     $config = new Config();
     $fixer = new Fixer();
     $fixer->registerBuiltInConfigs();
     $fixer->registerBuiltInFixers();
     $resolver = new ConfigurationResolver();
     $resolver->setAllFixers($fixer->getFixers())->setConfig($config)->setOptions(array('level' => 'symfony', 'fixers' => null, 'progress' => false))->resolve();
     $config->fixers($resolver->getFixers());
     $finder = [];
     foreach ($files as $file) {
         $finder[] = new \SplFileInfo($file);
     }
     $config->finder(new \ArrayIterator($finder));
     $fixer->fix($config);
 }
Example #8
0
 /**
  * Execute the code generation
  */
 public function generate()
 {
     /*
      * PROXY CONFIGURATION
      */
     $proxy = current(array_filter(array(getenv('HTTP_PROXY'), getenv('http_proxy')), 'strlen'));
     if ($proxy) {
         $parsedWsdlPath = Url::createFromUrl($this->config->getWsdlDocumentPath());
         // if not fetching the wsdl file from filesystem and a proxy has been set
         if ($parsedWsdlPath->getScheme()->get() !== 'file') {
             $proxy = Url::createFromUrl($proxy);
             libxml_set_streams_context(stream_context_get_default(array($proxy->getScheme()->get() => array('proxy' => 'tcp://' . $proxy->getAuthority() . $proxy->getRelativeUrl(), 'request_fulluri' => true))));
         }
     }
     unset($proxy);
     /*
      * LOAD THE WSDL DOCUMENT
      */
     $wsdlDocument = SimpleXMLElement::loadFile($this->config->getWsdlDocumentPath());
     $wsdlDocument->registerXPathNamespace('wsdl', static::WSDL_NS);
     $schemaReader = new SchemaReader();
     /* @var \Goetas\XML\XSDReader\Schema\Schema[] $schemas */
     $schemas = array();
     /* @var \Goetas\XML\XSDReader\Schema\Type\Type[] $types */
     $types = array();
     /*
      * LOAD THE XML SCHEMAS
      */
     // read the schemas included in the wsdl document
     foreach ($wsdlDocument->xpath('/wsdl:definitions/wsdl:types/xsd:schema') as $schemaNode) {
         $schemas[] = $schemaReader->readNode(dom_import_simplexml($schemaNode));
     }
     // exclude the schemas having the following namespaces
     $unusedSchemaNamespaces = array(SchemaReader::XML_NS, SchemaReader::XSD_NS);
     // recursively read all the schema chain
     $processedSchemas = array();
     while (!empty($schemas)) {
         /* @var \Goetas\XML\XSDReader\Schema\Schema $currentSchema */
         $currentSchema = array_shift($schemas);
         if (!in_array($currentSchema, $processedSchemas) and !in_array($currentSchema->getTargetNamespace(), $unusedSchemaNamespaces)) {
             $processedSchemas[] = $currentSchema;
             $schemas = array_merge($schemas, $currentSchema->getSchemas());
         }
     }
     $schemas = $processedSchemas;
     // cleanup
     unset($currentSchema);
     unset($processedSchemas);
     unset($unusedSchemaNamespaces);
     unset($schemaNode);
     unset($schemaReader);
     /*
      * LOAD THE DEFINED TYPES
      */
     // get the complete list of defined types
     foreach ($schemas as $schema) {
         $types = array_merge($types, $schema->getTypes());
     }
     /*
      * LOAD THE SERVICES
      */
     $services = $wsdlDocument->xpath('/wsdl:definitions/wsdl:portType');
     /*
      * CODE GENERATION
      */
     $classFactory = new ClassFactory($this->config, $schemas, $types);
     foreach ($types as $type) {
         if ($type instanceof SimpleType) {
             // build the inheritance chain of the current SimpleType
             /* @var \Goetas\XML\XSDReader\Schema\Type\SimpleType[] $inheritanceChain */
             $inheritanceChain = array($type->getRestriction());
             // loop through the type inheritance chain untill the base type
             while (end($inheritanceChain) !== null) {
                 $inheritanceChain[] = end($inheritanceChain)->getBase()->getParent();
             }
             // remove the null value
             array_pop($inheritanceChain);
             // remove the 'anySimpleType'
             array_pop($inheritanceChain);
             // now the last element of the chain is the base simple type
             // enums are built only of string enumerations
             if (end($inheritanceChain)->getBase()->getName() === 'string' and array_key_exists('enumeration', $type->getRestriction()->getChecks())) {
                 $className = $classFactory->createEnum($type);
                 $this->eventDispatcher->dispatch(Event::ENUM_CREATE, new Event($className));
             }
         } elseif ($type instanceof ComplexType) {
             $className = $classFactory->createDTO($type);
             $this->eventDispatcher->dispatch(Event::DTO_CREATE, new Event($className));
         }
     }
     foreach ($services as $service) {
         $className = $classFactory->createService($service);
         $this->eventDispatcher->dispatch(Event::SERVICE_CREATE, new Event($className));
     }
     $className = $classFactory->createClassmap();
     $this->eventDispatcher->dispatch(Event::CLASSMAP_CREATE, new Event($className));
     /*
      * GENERATED CODE FIX
      */
     // create the coding standards fixer
     $fixer = new Fixer();
     $config = new FixerConfig();
     $config->setDir($this->config->getOutputPath());
     // register all the existing fixers
     $fixer->registerBuiltInFixers();
     $config->fixers(array_filter($fixer->getFixers(), function (FixerInterface $fixer) {
         return $fixer->getLevel() === FixerInterface::PSR2_LEVEL;
     }));
     // fix the generated code
     $fixer->fix($config);
 }
Example #9
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;
 }
Example #10
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;
 }
 public function main()
 {
     try {
         /*
          * PROPERTIES VALIDATION
          */
         // check if the proxy flag has been set
         $proxy = $this->getProject()->getUserProperty('proxy');
         $proxy = $proxy !== null ? filter_var($proxy, FILTER_VALIDATE_BOOLEAN) : true;
         // determine the url of the WSDL document
         $wsdlUrl = $this->getProject()->getUserProperty('wsdl.url');
         $wsdlUrl = $wsdlUrl ? $wsdlUrl : static::WSDL_URL;
         /*
          * PROXY CONFIGURATION
          */
         // read the proxy configuration from the environment variables
         $proxy = $proxy ? current(array_filter(array(getenv('HTTP_PROXY'), getenv('http_proxy')), 'strlen')) : null;
         // prepare an empty url for the stream context
         $streamContextProxyUrl = null;
         // if the proxy is configured in the system
         if ($proxy) {
             // parse the WSDL url
             $parsedWsdlPath = Url::createFromUrl($wsdlUrl);
             // parse the proxy url
             $proxy = Url::createFromUrl($proxy);
             // if not fetching the wsdl file from filesystem and a proxy has been configured
             if ($parsedWsdlPath->getScheme()->get() !== 'file') {
                 $streamContextProxyUrl = 'tcp://' . $proxy->getAuthority() . $proxy->getRelativeUrl();
                 libxml_set_streams_context(stream_context_get_default(array($proxy->getScheme()->get() => array('proxy' => $streamContextProxyUrl, 'request_fulluri' => true))));
             }
         }
         /*
          * INITIALIZATION
          */
         // prepare the path to the generated code
         $outputDir = $this->project->getBasedir() . '/src';
         $output = new ConsoleOutput();
         $progress = new ProgressBar($output, 100);
         $progress->setFormat(ProgressBar::getFormatDefinition('normal') . ' %message%...');
         $progress->setMessage('Starting');
         $progress->start();
         $progress->setMessage('Cleaning the environment');
         // clean the output directory
         array_map('unlink', glob($outputDir . '/*'));
         $progress->advance(10);
         /*
          * GENERATION
          */
         // prepare the generator configuration
         $progress->setMessage('Configuring the generator');
         $optionFeatures = array();
         if ($proxy) {
             /* @var \League\Url\UrlInterface $proxy */
             $optionFeatures['proxy_host'] = $proxy->getHost()->get();
             $optionFeatures['proxy_port'] = $proxy->getPort()->get();
         }
         $config = new Config($wsdlUrl, $outputDir);
         $config->setNoTypeConstructor(true);
         $config->setOptionFeatures($optionFeatures);
         $config->setCreateAccessors(false);
         $config->setWsdlCache(false);
         $progress->advance(10);
         // generate the code
         $progress->setMessage('Generating the code');
         $gen = new Generator();
         $gen->generate($config);
         $progress->advance(10);
         /*
          * FIX
          */
         // the 'optionFeatures' configuration options is misused by the generator:
         // it is correctly used as the default 'features' options of the service (its values are bitwised and put
         // in the service class constructor), but it is also used as the '$options' argument of the \SoapClient
         // class when it connects to the service to inspect it (hence the need to define the 'proxy_host' and
         // 'proxy_port' keys). this makes the generated code clash, so we need to fix it, removing the unneeded
         // values from the bitwise operation.
         $defaultFeatures = array('SOAP_SINGLE_ELEMENT_ARRAYS', 'SOAP_WAIT_ONE_WAY_CALLS');
         // fix the option 'features' management
         $fileContent = file_get_contents("{$outputDir}/ClabService.php");
         $fileContent = preg_replace('/(\\$options\\[\'features\'\\] = ).*/', '$1' . implode(' | ', $defaultFeatures) . ';', $fileContent, -1, $count);
         // if no features option has been found, they must be added manually
         if ($count === 0) {
             $fileContent = preg_replace('/parent::__construct/', "if (isset(\$options['features']) == false) {\n\$options['features'] = " . implode(' | ', $defaultFeatures) . ";\n}\n\nparent::__construct", $fileContent, -1, $count);
         }
         file_put_contents("{$outputDir}/ClabService.php", $fileContent);
         /*
          * LICENSE MANAGEMENT
          */
         $progress->setMessage('Applying the license to the generated files');
         // read the license header
         $licenseHeader = file_get_contents($this->project->getBasedir() . '/resources/license_header.txt');
         // print the license on top of every file
         foreach (glob($outputDir . '/*.php') as $sourceFile) {
             $fileContent = file_get_contents($sourceFile);
             $fileContent = preg_replace('/^(<\\?php)/', "\$1\n\n" . $licenseHeader, $fileContent);
             file_put_contents($sourceFile, $fileContent);
         }
         unset($sourceFile);
         $progress->advance(10);
         /*
          * CODING STANDARDS FIXES
          */
         // create the coding standards fixer
         $progress->setMessage('Configuring the Coding Standards fixer');
         $fixer = new Fixer();
         $csConfig = new CSConfig();
         $csConfig->setDir($outputDir);
         $progress->advance(10);
         // register all the existing fixers
         $fixer->registerBuiltInFixers();
         $progress->advance(10);
         // register all fixers from all PSR levels
         /* @var $csFixer \Symfony\CS\FixerInterface */
         $fixers = array();
         foreach ($fixer->getFixers() as $csFixer) {
             if ($csFixer->getLevel() === ($csFixer->getLevel() & FixerInterface::PSR2_LEVEL)) {
                 $fixers[] = $csFixer;
             }
         }
         // fix the generated code
         $progress->setMessage('Fixing the generated code');
         $csConfig->fixers($fixers);
         $progress->advance(10);
         $fixer->fix($csConfig);
         $progress->advance(10);
         $progress->setFormat(ProgressBar::getFormatDefinition('normal') . ' %message%');
         $progress->setMessage('Done');
         $progress->finish();
         $output->writeln('');
     } catch (\Exception $e) {
         $this->log($e->getMessage(), \Project::MSG_ERR);
     }
 }
Example #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;
 }