Esempio n. 1
0
 /**
  * @param Fixer|null           $fixer
  * @param ConfigInterface|null $config
  */
 public function __construct(Fixer $fixer = null, ConfigInterface $config = null)
 {
     $this->defaultConfig = $config ?: new Config();
     $this->eventDispatcher = new EventDispatcher();
     $this->fixer = $fixer ?: new Fixer();
     $this->fixer->registerBuiltInFixers();
     $this->fixer->registerBuiltInConfigs();
     $this->errorsManager = $this->fixer->getErrorsManager();
     $this->stopwatch = $this->fixer->getStopwatch();
     parent::__construct();
 }
Esempio n. 2
0
 /**
  * @covers Symfony\CS\Fixer::registerBuiltInFixers
  */
 public function testThatRegisterBuiltInFixers()
 {
     $fixer = new Fixer();
     $this->assertCount(0, $fixer->getFixers());
     $fixer->registerBuiltInFixers();
     $this->assertGreaterThan(0, count($fixer->getFixers()));
 }
Esempio n. 3
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');
 }
 protected function setUp()
 {
     $fixer = new Fixer();
     $fixer->registerBuiltInFixers();
     $fixer->registerBuiltInConfigs();
     $fixersMap = array();
     foreach ($fixer->getFixers() as $singleFixer) {
         $level = $singleFixer->getLevel();
         if (!isset($fixersMap[$level])) {
             $fixersMap[$level] = array();
         }
         $fixersMap[$level][$singleFixer->getName()] = $singleFixer;
     }
     $this->fixersMap = $fixersMap;
     $this->config = new Config();
     $this->resolver = new ConfigurationResolver();
     $this->resolver->setDefaultConfig($this->config)->setFixer($fixer);
 }
 protected function setUp()
 {
     $fixer = new Fixer();
     $fixer->registerBuiltInFixers();
     $fixer->registerBuiltInConfigs();
     $fixersMap = array();
     foreach ($fixer->getFixers() as $singleFixer) {
         $level = $singleFixer->getLevel();
         if (!isset($fixersMap[$level])) {
             $fixersMap[$level] = array();
         }
         $fixersMap[$level][$singleFixer->getName()] = $singleFixer;
     }
     $this->fixersMap = $fixersMap;
     $this->config = $this->getMock('Symfony\\CS\\ConfigInterface');
     $this->resolver = new ConfigurationResolver();
     $this->resolver->setAllFixers($fixer->getFixers())->setConfig($this->config);
 }
Esempio n. 6
0
 public function provideFixersDescriptionConsistencyCases()
 {
     $fixer = new Fixer();
     $fixer->registerBuiltInFixers();
     $fixers = $fixer->getFixers();
     $cases = array();
     foreach ($fixers as $fixer) {
         $cases[] = array($fixer);
     }
     return $cases;
 }
Esempio n. 7
0
 public function provideFixersForFinalCheckCases()
 {
     $fixer = new Fixer();
     $fixer->registerBuiltInFixers();
     $fixers = $fixer->getFixers();
     $cases = array();
     foreach ($fixers as $fixer) {
         $cases[] = array(new \ReflectionClass($fixer));
     }
     return $cases;
 }
 /**
  * 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);
 }
Esempio n. 9
0
 public function getFixersPriorityCases()
 {
     $fixer = new Fixer();
     $fixer->registerBuiltInFixers();
     $fixers = array();
     foreach ($fixer->getFixers() as $fixer) {
         $fixers[$fixer->getName()] = $fixer;
     }
     return array(array($fixers['php_closing_tag'], $fixers['short_tag']), array($fixers['unused_use'], $fixers['extra_empty_lines']), array($fixers['multiple_use'], $fixers['unused_use']), array($fixers['multiple_use'], $fixers['ordered_use']), array($fixers['remove_lines_between_uses'], $fixers['ordered_use']), array($fixers['concat_without_spaces'], $fixers['concat_with_spaces']), array($fixers['elseif'], $fixers['braces']), array($fixers['duplicate_semicolon'], $fixers['braces']), array($fixers['duplicate_semicolon'], $fixers['spaces_before_semicolon']), array($fixers['duplicate_semicolon'], $fixers['multiline_spaces_before_semicolon']), array($fixers['standardize_not_equal'], $fixers['strict']));
 }
Esempio n. 10
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);
 }
 /**
  * Parses the '--CONFIG--' block of a '.test' file and determines what fixers should be used.
  *
  * @param string $fileName
  * @param string $config
  *
  * @return FixerInterface[]
  */
 protected function getFixersFromConfig($fileName, $config)
 {
     static $levelMap = array('none' => FixerInterface::NONE_LEVEL, 'psr1' => FixerInterface::PSR1_LEVEL, 'psr2' => FixerInterface::PSR2_LEVEL, 'symfony' => FixerInterface::SYMFONY_LEVEL);
     $lines = explode("\n", $config);
     if (count($lines) < 1) {
         throw new \InvalidArgumentException(sprintf('No configuration options found in "%s".', $fileName));
     }
     $config = array('level' => null, 'fixers' => array(), '--fixers' => array());
     foreach ($lines as $line) {
         $labelValuePair = explode('=', $line);
         if (2 !== count($labelValuePair)) {
             throw new \InvalidArgumentException(sprintf('Invalid configuration line "%s" in "%s".', $line, $fileName));
         }
         $label = strtolower(trim($labelValuePair[0]));
         $value = trim($labelValuePair[1]);
         switch ($label) {
             case 'level':
                 if (!array_key_exists($value, $levelMap)) {
                     throw new \InvalidArgumentException(sprintf('Unknown level "%s" set in configuration in "%s", expected any of "%s".', $value, $fileName, implode(', ', array_keys($levelMap))));
                 }
                 if (null !== $config['level']) {
                     throw new \InvalidArgumentException(sprintf('Cannot use multiple levels in configuration in "%s".', $fileName));
                 }
                 $config['level'] = $value;
                 break;
             case 'fixers':
             case '--fixers':
                 foreach (explode(',', $value) as $fixer) {
                     $config[$label][] = strtolower(trim($fixer));
                 }
                 break;
             default:
                 throw new \InvalidArgumentException(sprintf('Unknown configuration item "%s" in "%s".', $label, $fileName));
         }
     }
     if (null === $config['level']) {
         throw new \InvalidArgumentException(sprintf('Level not set in configuration "%s".', $fileName));
     }
     if (null === self::$builtInFixers) {
         $fixer = new Fixer();
         $fixer->registerBuiltInFixers();
         self::$builtInFixers = $fixer->getFixers();
     }
     $fixers = array();
     for ($i = count(self::$builtInFixers) - 1; $i >= 0; --$i) {
         $fixer = self::$builtInFixers[$i];
         $fixerName = $fixer->getName();
         if ('psr0' === $fixer->getName()) {
             // File based fixer won't work
             continue;
         }
         if ($fixer->getLevel() !== ($fixer->getLevel() & $levelMap[$config['level']])) {
             if (false !== ($key = array_search($fixerName, $config['fixers'], true))) {
                 $fixers[] = $fixer;
                 unset($config['fixers'][$key]);
             }
             continue;
         }
         if (false !== ($key = array_search($fixerName, $config['--fixers'], true))) {
             unset($config['--fixers'][$key]);
             continue;
         }
         if (in_array($fixerName, $config['fixers'], true)) {
             throw new \InvalidArgumentException(sprintf('Additional fixer "%s" configured, but is already part of the level.', $fixerName));
         }
         $fixers[] = $fixer;
     }
     if (!empty($config['fixers']) || !empty($config['--fixers'])) {
         throw new \InvalidArgumentException(sprintf('Unknown fixers in configuration "%s".', implode(',', empty($config['fixers']) ? $config['--fixers'] : $config['fixers'])));
     }
     return $fixers;
 }
 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);
     }
 }
Esempio n. 13
0
 public function getFixersPriorityCases()
 {
     $fixer = new Fixer();
     $fixer->registerBuiltInFixers();
     $fixers = array();
     foreach ($fixer->getFixers() as $fixer) {
         $fixers[$fixer->getName()] = $fixer;
     }
     return array(array($fixers['php_closing_tag'], $fixers['short_tag']), array($fixers['multiple_use'], $fixers['unused_use']), array($fixers['multiple_use'], $fixers['ordered_use']), array($fixers['concat_without_spaces'], $fixers['concat_with_spaces']), array($fixers['elseif'], $fixers['braces']));
 }