Skip to content

Commit

Permalink
minor #27852 Fix coding standards (stof)
Browse files Browse the repository at this point in the history
This PR was squashed before being merged into the 2.8 branch (closes #27852).

Discussion
----------

Fix coding standards

| Q             | A
| ------------- | ---
| Branch?       | 2.8
| Bug fix?      | no
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | n/a
| License       | MIT
| Doc PR        | n/a

This PR is mostly about running the PHP-CS-Fixer (v2.12.1) in the whole codebase.

- I updated the exclude rule to avoid some false positives for the `error_suppression` fixer (we have more files triggering unsilenced deprecations on purpose than when building the initial whitelist, mostly).
- I ran the fixer with this updated config. Most changes were related to fully-qualifying some constants, with the new fixer implemented in PHP-CS-Fixer/PHP-CS-Fixer#3127, for which @nicolas-grekas and I suggested a config to include in the Symfony ruleset. Based on the output, I suggested a feature request in PHP-CS-Fixer/PHP-CS-Fixer#3872 as we might want to avoid the `\` in non-namespaced files to improve readability. We might want to remove the second commit of this PR if we decide to wait for the feature to be implemented (update: implementation is contributed in PHP-CS-Fixer/PHP-CS-Fixer#3876)
- I added the `native_function_invocation` fixer explicitly, to automatically fully-qualify calls to compiler-optimized functions. This feature was implemented in PHP-CS-Fixer based on our feature request (as currently, we do such thing only manually in some hot path, because it could not be automated). I opened PHP-CS-Fixer/PHP-CS-Fixer#3873 to include it in the ruleset automatically.

TODOs:
- [x] agree on the updated rules
- [x] update fabbot to use the new version of PHP-CS-Fixer
- [ ] make separate PRs for newer branches with their own updates (exclude rules, and CS fixes), once this PR gets merged.

Commits
-------

538c69d Fix Clidumper tests
04654cf Enable the fixer enforcing fully-qualified calls for compiler-optimized functions
f00b327 Apply fixers
720ed4d Disable the native_constant_invocation fixer until it can be scoped
8892b98 Update the list of excluded files for the CS fixer
  • Loading branch information
nicolas-grekas committed Jul 26, 2018
2 parents a57549d + 538c69d commit 82d13da
Show file tree
Hide file tree
Showing 720 changed files with 2,268 additions and 2,271 deletions.
10 changes: 8 additions & 2 deletions .php_cs.dist
Expand Up @@ -15,6 +15,10 @@ return PhpCsFixer\Config::create()
// rule disabled due to https://bugs.php.net/bug.php?id=60573 bug;
// to be re-enabled (by dropping next line, rule is part of @Symfony already) on branch that requires PHP 5.4+
'self_accessor' => false,
// TODO remove the disabling once https://github.com/FriendsOfPHP/PHP-CS-Fixer/pull/3876 is merged and released
'native_constant_invocation' => false,
// Part of @Symfony:risky in PHP-CS-Fixer 2.13.0. To be removed from the config file once upgrading
'native_function_invocation' => array('include' => array('@compiler_optimized'), 'scope' => 'namespaced'),
))
->setRiskyAllowed(true)
->setFinder(
Expand All @@ -32,16 +36,18 @@ return PhpCsFixer\Config::create()
'Symfony/Component/VarDumper/Tests/Fixtures',
// resource templates
'Symfony/Bundle/FrameworkBundle/Resources/views/Form',
// explicit trigger_error tests
'Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/',
))
// Support for older PHPunit version
->notPath('Symfony/Bridge/PhpUnit/SymfonyTestsListener.php')
// file content autogenerated by `var_export`
->notPath('Symfony/Component/Translation/Tests/fixtures/resources.php')
// test template
->notPath('Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_name_entry_label.html.php')
// explicit heredoc test
->notPath('Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Resources/views/translation.html.php')
// explicit trigger_error tests
->notPath('Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/default.phpt')
->notPath('Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/weak.phpt')
->notPath('Symfony/Component/Debug/Tests/DebugClassLoaderTest.php')
)
;
6 changes: 3 additions & 3 deletions src/Symfony/Bridge/Doctrine/ContainerAwareEventManager.php
Expand Up @@ -54,7 +54,7 @@ public function dispatchEvent($eventName, EventArgs $eventArgs = null)
$initialized = isset($this->initialized[$eventName]);

foreach ($this->listeners[$eventName] as $hash => $listener) {
if (!$initialized && is_string($listener)) {
if (!$initialized && \is_string($listener)) {
$this->listeners[$eventName][$hash] = $listener = $this->container->get($listener);
}

Expand Down Expand Up @@ -98,7 +98,7 @@ public function hasListeners($event)
*/
public function addEventListener($events, $listener)
{
if (is_string($listener)) {
if (\is_string($listener)) {
if ($this->initialized) {
throw new \RuntimeException('Adding lazy-loading listeners after construction is not supported.');
}
Expand All @@ -124,7 +124,7 @@ public function addEventListener($events, $listener)
*/
public function removeEventListener($events, $listener)
{
if (is_string($listener)) {
if (\is_string($listener)) {
$hash = '_service_'.$listener;
} else {
// Picks the hash code related to that listener
Expand Down
Expand Up @@ -120,14 +120,14 @@ private function sanitizeQuery($connectionName, $query)
if (null === $query['params']) {
$query['params'] = array();
}
if (!is_array($query['params'])) {
if (!\is_array($query['params'])) {
$query['params'] = array($query['params']);
}
foreach ($query['params'] as $j => $param) {
if (isset($query['types'][$j])) {
// Transform the param according to the type
$type = $query['types'][$j];
if (is_string($type)) {
if (\is_string($type)) {
$type = Type::getType($type);
}
if ($type instanceof Type) {
Expand Down Expand Up @@ -158,11 +158,11 @@ private function sanitizeQuery($connectionName, $query)
*/
private function sanitizeParam($var)
{
if (is_object($var)) {
return array(sprintf('Object(%s)', get_class($var)), false);
if (\is_object($var)) {
return array(sprintf('Object(%s)', \get_class($var)), false);
}

if (is_array($var)) {
if (\is_array($var)) {
$a = array();
$original = true;
foreach ($var as $k => $v) {
Expand All @@ -174,7 +174,7 @@ private function sanitizeParam($var)
return array($a, $original);
}

if (is_resource($var)) {
if (\is_resource($var)) {
return array(sprintf('Resource(%s)', get_resource_type($var)), false);
}

Expand Down
Expand Up @@ -142,7 +142,7 @@ protected function setMappingDriverConfig(array $mappingConfig, $mappingName)
*/
protected function getMappingDriverBundleConfigDefaults(array $bundleConfig, \ReflectionClass $bundle, ContainerBuilder $container)
{
$bundleDir = dirname($bundle->getFileName());
$bundleDir = \dirname($bundle->getFileName());

if (!$bundleConfig['type']) {
$bundleConfig['type'] = $this->detectMetadataDriver($bundleDir, $container);
Expand All @@ -154,7 +154,7 @@ protected function getMappingDriverBundleConfigDefaults(array $bundleConfig, \Re
}

if (!$bundleConfig['dir']) {
if (in_array($bundleConfig['type'], array('annotation', 'staticphp'))) {
if (\in_array($bundleConfig['type'], array('annotation', 'staticphp'))) {
$bundleConfig['dir'] = $bundleDir.'/'.$this->getMappingObjectDefaultName();
} else {
$bundleConfig['dir'] = $bundleDir.'/'.$this->getMappingResourceConfigDirectory();
Expand Down Expand Up @@ -241,7 +241,7 @@ protected function assertValidMappingConfiguration(array $mappingConfig, $object
throw new \InvalidArgumentException(sprintf('Specified non-existing directory "%s" as Doctrine mapping source.', $mappingConfig['dir']));
}

if (!in_array($mappingConfig['type'], array('xml', 'yml', 'annotation', 'php', 'staticphp'))) {
if (!\in_array($mappingConfig['type'], array('xml', 'yml', 'annotation', 'php', 'staticphp'))) {
throw new \InvalidArgumentException(sprintf('Can only configure "xml", "yml", "annotation", "php" or '.
'"staticphp" through the DoctrineBundle. Use your own bundle to configure other metadata drivers. '.
'You can register them by adding a new driver to the '.
Expand All @@ -264,17 +264,17 @@ protected function detectMetadataDriver($dir, ContainerBuilder $container)
$configPath = $this->getMappingResourceConfigDirectory();
$resource = $dir.'/'.$configPath;
while (!is_dir($resource)) {
$resource = dirname($resource);
$resource = \dirname($resource);
}

$container->addResource(new FileResource($resource));

$extension = $this->getMappingResourceExtension();
if (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.xml')) && count($files)) {
if (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.xml')) && \count($files)) {
return 'xml';
} elseif (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.yml')) && count($files)) {
} elseif (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.yml')) && \count($files)) {
return 'yml';
} elseif (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.php')) && count($files)) {
} elseif (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.php')) && \count($files)) {
return 'php';
}

Expand Down
Expand Up @@ -60,7 +60,7 @@ private function updateValidatorMappingFiles(ContainerBuilder $container, $mappi

foreach ($container->getParameter('kernel.bundles') as $bundle) {
$reflection = new \ReflectionClass($bundle);
if (is_file($file = dirname($reflection->getFileName()).'/'.$validationPath)) {
if (is_file($file = \dirname($reflection->getFileName()).'/'.$validationPath)) {
$files[] = $file;
$container->addResource(new FileResource($file));
}
Expand Down
Expand Up @@ -153,7 +153,7 @@ private function findAndSortTags($tagName, ContainerBuilder $container)

if ($sortedTags) {
krsort($sortedTags);
$sortedTags = call_user_func_array('array_merge', $sortedTags);
$sortedTags = \call_user_func_array('array_merge', $sortedTags);
}

return $sortedTags;
Expand Down
Expand Up @@ -124,7 +124,7 @@ public function __construct($driver, array $namespaces, array $managerParameters
$this->managerParameters = $managerParameters;
$this->driverPattern = $driverPattern;
$this->enabledParameter = $enabledParameter;
if (count($aliasMap) && (!$configurationPattern || !$registerAliasMethodName)) {
if (\count($aliasMap) && (!$configurationPattern || !$registerAliasMethodName)) {
throw new \InvalidArgumentException('configurationPattern and registerAliasMethodName are required to register namespace alias');
}
$this->configurationPattern = $configurationPattern;
Expand All @@ -149,7 +149,7 @@ public function process(ContainerBuilder $container)
$chainDriverDef->addMethodCall('addDriver', array($mappingDriverDef, $namespace));
}

if (!count($this->aliasMap)) {
if (!\count($this->aliasMap)) {
return;
}

Expand Down
Expand Up @@ -88,7 +88,7 @@ public function loadValuesForChoices(array $choices, $value = null)

// Optimize performance for single-field identifiers. We already
// know that the IDs are used as values
$optimize = null === $value || is_array($value) && $value[0] === $this->idReader;
$optimize = null === $value || \is_array($value) && $value[0] === $this->idReader;

// Attention: This optimization does not check choices for existence
if ($optimize && !$this->choiceList && $this->idReader->isSingleId()) {
Expand Down Expand Up @@ -125,7 +125,7 @@ public function loadChoicesForValues(array $values, $value = null)

// Optimize performance in case we have an object loader and
// a single-field identifier
$optimize = null === $value || is_array($value) && $value[0] === $this->idReader;
$optimize = null === $value || \is_array($value) && $value[0] === $this->idReader;

if ($optimize && !$this->choiceList && $this->objectLoader && $this->idReader->isSingleId()) {
$unorderedObjects = $this->objectLoader->getEntitiesByIds($this->idReader->getIdField(), $values);
Expand Down
Expand Up @@ -117,7 +117,7 @@ public function __construct(ObjectManager $manager, $class, $labelPath = null, E
$this->entityLoader = $entityLoader;
$this->classMetadata = $manager->getClassMetadata($class);
$this->class = $this->classMetadata->getName();
$this->loaded = is_array($entities) || $entities instanceof \Traversable;
$this->loaded = \is_array($entities) || $entities instanceof \Traversable;
$this->preferredEntities = $preferredEntities;
list(
$this->idAsIndex,
Expand Down Expand Up @@ -449,13 +449,13 @@ private function getIdentifierInfoForClass(ClassMetadata $classMetadata)

$identifiers = $classMetadata->getIdentifierFieldNames();

if (1 === count($identifiers)) {
if (1 === \count($identifiers)) {
$identifier = $identifiers[0];

if (!$classMetadata->hasAssociation($identifier)) {
$idAsValue = true;

if (in_array($classMetadata->getTypeOfField($identifier), array('integer', 'smallint', 'bigint'))) {
if (\in_array($classMetadata->getTypeOfField($identifier), array('integer', 'smallint', 'bigint'))) {
$idAsIndex = true;
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php
Expand Up @@ -42,8 +42,8 @@ public function __construct(ObjectManager $om, ClassMetadata $classMetadata)

$this->om = $om;
$this->classMetadata = $classMetadata;
$this->singleId = 1 === count($ids);
$this->intId = $this->singleId && in_array($idType, array('integer', 'smallint', 'bigint'));
$this->singleId = 1 === \count($ids);
$this->intId = $this->singleId && \in_array($idType, array('integer', 'smallint', 'bigint'));
$this->idField = current($ids);

// single field association are resolved, since the schema column could be an int
Expand Down Expand Up @@ -95,7 +95,7 @@ public function getIdValue($object)
}

if (!$this->om->contains($object)) {
throw new RuntimeException(sprintf('Entity of type "%s" passed to the choice field must be managed. Maybe you forget to persist it in the entity manager?', get_class($object)));
throw new RuntimeException(sprintf('Entity of type "%s" passed to the choice field must be managed. Maybe you forget to persist it in the entity manager?', \get_class($object)));
}

$this->om->initializeObject($object);
Expand Down
Expand Up @@ -98,15 +98,15 @@ public function getEntitiesByIds($identifier, array $values)
// Guess type
$entity = current($qb->getRootEntities());
$metadata = $qb->getEntityManager()->getClassMetadata($entity);
if (in_array($metadata->getTypeOfField($identifier), array('integer', 'bigint', 'smallint'))) {
if (\in_array($metadata->getTypeOfField($identifier), array('integer', 'bigint', 'smallint'))) {
$parameterType = Connection::PARAM_INT_ARRAY;

// Filter out non-integer values (e.g. ""). If we don't, some
// databases such as PostgreSQL fail.
$values = array_values(array_filter($values, function ($v) {
return (string) $v === (string) (int) $v || ctype_digit($v);
}));
} elseif (in_array($metadata->getTypeOfField($identifier), array('uuid', 'guid'))) {
} elseif (\in_array($metadata->getTypeOfField($identifier), array('uuid', 'guid'))) {
$parameterType = Connection::PARAM_STR_ARRAY;

// Like above, but we just filter out empty strings.
Expand Down
Expand Up @@ -36,7 +36,7 @@ public function transform($collection)

// For cases when the collection getter returns $collection->toArray()
// in order to prevent modifications of the returned collection
if (is_array($collection)) {
if (\is_array($collection)) {
return $collection;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php
Expand Up @@ -131,7 +131,7 @@ public function guessMaxLength($class, $property)
return new ValueGuess($mapping['length'], Guess::HIGH_CONFIDENCE);
}

if (in_array($ret[0]->getTypeOfField($property), array(Type::DECIMAL, Type::FLOAT))) {
if (\in_array($ret[0]->getTypeOfField($property), array(Type::DECIMAL, Type::FLOAT))) {
return new ValueGuess(null, Guess::MEDIUM_CONFIDENCE);
}
}
Expand All @@ -144,7 +144,7 @@ public function guessPattern($class, $property)
{
$ret = $this->getMetadata($class);
if ($ret && isset($ret[0]->fieldMappings[$property]) && !$ret[0]->hasAssociation($property)) {
if (in_array($ret[0]->getTypeOfField($property), array(Type::DECIMAL, Type::FLOAT))) {
if (\in_array($ret[0]->getTypeOfField($property), array(Type::DECIMAL, Type::FLOAT))) {
return new ValueGuess(null, Guess::MEDIUM_CONFIDENCE);
}
}
Expand Down
Expand Up @@ -41,7 +41,7 @@ public function onBind(FormEvent $event)

// If all items were removed, call clear which has a higher
// performance on persistent collections
if ($collection instanceof Collection && 0 === count($data)) {
if ($collection instanceof Collection && 0 === \count($data)) {
$collection->clear();
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php
Expand Up @@ -259,8 +259,8 @@ public function configureOptions(OptionsResolver $resolver)
// Invoke the query builder closure so that we can cache choice lists
// for equal query builders
$queryBuilderNormalizer = function (Options $options, $queryBuilder) {
if (is_callable($queryBuilder)) {
$queryBuilder = call_user_func($queryBuilder, $options['em']->getRepository($options['class']));
if (\is_callable($queryBuilder)) {
$queryBuilder = \call_user_func($queryBuilder, $options['em']->getRepository($options['class']));
}

return $queryBuilder;
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Bridge/Doctrine/Form/Type/EntityType.php
Expand Up @@ -28,8 +28,8 @@ public function configureOptions(OptionsResolver $resolver)
// Invoke the query builder closure so that we can cache choice lists
// for equal query builders
$queryBuilderNormalizer = function (Options $options, $queryBuilder) {
if (is_callable($queryBuilder)) {
$queryBuilder = call_user_func($queryBuilder, $options['em']->getRepository($options['class']));
if (\is_callable($queryBuilder)) {
$queryBuilder = \call_user_func($queryBuilder, $options['em']->getRepository($options['class']));

if (null !== $queryBuilder && !$queryBuilder instanceof QueryBuilder) {
throw new UnexpectedTypeException($queryBuilder, 'Doctrine\ORM\QueryBuilder');
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Bridge/Doctrine/Logger/DbalLogger.php
Expand Up @@ -71,12 +71,12 @@ private function normalizeParams(array $params)
{
foreach ($params as $index => $param) {
// normalize recursively
if (is_array($param)) {
if (\is_array($param)) {
$params[$index] = $this->normalizeParams($param);
continue;
}

if (!is_string($params[$index])) {
if (!\is_string($params[$index])) {
continue;
}

Expand Down
Expand Up @@ -52,7 +52,7 @@ public function loadUserByUsername($username)
} else {
if (!$repository instanceof UserLoaderInterface) {
if (!$repository instanceof UserProviderInterface) {
throw new \InvalidArgumentException(sprintf('You must either make the "%s" entity Doctrine Repository ("%s") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.', $this->classOrAlias, get_class($repository)));
throw new \InvalidArgumentException(sprintf('You must either make the "%s" entity Doctrine Repository ("%s") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.', $this->classOrAlias, \get_class($repository)));
}

@trigger_error('Implementing Symfony\Component\Security\Core\User\UserProviderInterface in a Doctrine repository when using the entity provider is deprecated since Symfony 2.8 and will not be supported in 3.0. Make the repository implement Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface instead.', E_USER_DEPRECATED);
Expand All @@ -75,7 +75,7 @@ public function refreshUser(UserInterface $user)
{
$class = $this->getClass();
if (!$user instanceof $class) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
}

$repository = $this->getRepository();
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bridge/Doctrine/Test/DoctrineTestHelper.php
Expand Up @@ -30,7 +30,7 @@ class DoctrineTestHelper
*/
public static function createTestEntityManager()
{
if (!extension_loaded('pdo_sqlite')) {
if (!\extension_loaded('pdo_sqlite')) {
TestCase::markTestSkipped('Extension pdo_sqlite is required.');
}

Expand Down

0 comments on commit 82d13da

Please sign in to comment.