minor #17282 [2.3] Static Code Analysis for Components (kalessil)

This PR was squashed before being merged into the 2.3 branch (closes #17282).

Discussion
----------

[2.3] Static Code Analysis for Components

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

Static Code Analysis with Php Inspections (EA Extended):
    - several code constructs simplification
    - decoupling statements from foreach
    - extra colons/parenthesis removal (code style)
    - correct string functions usage (micro-optimization)
    - variable functions usage (php 5 compatible)

Commits
-------

81f8181 [2.3] Static Code Analysis for Components
This commit is contained in:
Fabien Potencier 2016-01-12 12:31:36 +01:00
commit f1cce4e139
18 changed files with 30 additions and 37 deletions

View File

@ -136,7 +136,7 @@ abstract class Client
*/ */
public function getServerParameter($key, $default = '') public function getServerParameter($key, $default = '')
{ {
return (isset($this->server[$key])) ? $this->server[$key] : $default; return isset($this->server[$key]) ? $this->server[$key] : $default;
} }
/** /**

View File

@ -111,7 +111,7 @@ class TableHelper extends Helper
default: default:
throw new \InvalidArgumentException(sprintf('Invalid table layout "%s".', $layout)); throw new \InvalidArgumentException(sprintf('Invalid table layout "%s".', $layout));
}; }
return $this; return $this;
} }

View File

@ -131,7 +131,7 @@ class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface
PHP_OS, PHP_OS,
); );
return false !== stristr(implode(';', $checks), 'OS400'); return false !== stripos(implode(';', $checks), 'OS400');
} }
/** /**

View File

@ -536,6 +536,6 @@ class Container implements IntrospectableContainerInterface
*/ */
public static function underscore($id) public static function underscore($id)
{ {
return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), strtr($id, '_', '.'))); return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), str_replace('_', '.', $id)));
} }
} }

View File

@ -91,9 +91,7 @@ abstract class Extension implements ExtensionInterface, ConfigurationExtensionIn
$container->addResource(new FileResource($r->getFileName())); $container->addResource(new FileResource($r->getFileName()));
if (!method_exists($class, '__construct')) { if (!method_exists($class, '__construct')) {
$configuration = new $class(); return new $class();
return $configuration;
} }
} }
} }

View File

@ -91,8 +91,9 @@ class XmlFileLoader extends FileLoader
return; return;
} }
$defaultDirectory = dirname($file);
foreach ($imports as $import) { foreach ($imports as $import) {
$this->setCurrentDir(dirname($file)); $this->setCurrentDir($defaultDirectory);
$this->import((string) $import['resource'], null, (bool) $import->getAttributeAsPhp('ignore-errors'), $file); $this->import((string) $import['resource'], null, (bool) $import->getAttributeAsPhp('ignore-errors'), $file);
} }
} }

View File

@ -94,12 +94,13 @@ class YamlFileLoader extends FileLoader
throw new InvalidArgumentException(sprintf('The "imports" key should contain an array in %s. Check your YAML syntax.', $file)); throw new InvalidArgumentException(sprintf('The "imports" key should contain an array in %s. Check your YAML syntax.', $file));
} }
$defaultDirectory = dirname($file);
foreach ($content['imports'] as $import) { foreach ($content['imports'] as $import) {
if (!is_array($import)) { if (!is_array($import)) {
throw new InvalidArgumentException(sprintf('The values in the "imports" key should be arrays in %s. Check your YAML syntax.', $file)); throw new InvalidArgumentException(sprintf('The values in the "imports" key should be arrays in %s. Check your YAML syntax.', $file));
} }
$this->setCurrentDir(dirname($file)); $this->setCurrentDir($defaultDirectory);
$this->import($import['resource'], null, isset($import['ignore_errors']) ? (bool) $import['ignore_errors'] : false, $file); $this->import($import['resource'], null, isset($import['ignore_errors']) ? (bool) $import['ignore_errors'] : false, $file);
} }
} }

View File

@ -431,7 +431,7 @@ class Filesystem
return strspn($file, '/\\', 0, 1) return strspn($file, '/\\', 0, 1)
|| (strlen($file) > 3 && ctype_alpha($file[0]) || (strlen($file) > 3 && ctype_alpha($file[0])
&& substr($file, 1, 1) === ':' && substr($file, 1, 1) === ':'
&& (strspn($file, '/\\', 2, 1)) && strspn($file, '/\\', 2, 1)
) )
|| null !== parse_url($file, PHP_URL_SCHEME) || null !== parse_url($file, PHP_URL_SCHEME)
; ;

View File

@ -113,7 +113,7 @@ class HeaderBag implements \IteratorAggregate, \Countable
*/ */
public function get($key, $default = null, $first = true) public function get($key, $default = null, $first = true)
{ {
$key = strtr(strtolower($key), '_', '-'); $key = str_replace('_', '-', strtolower($key));
if (!array_key_exists($key, $this->headers)) { if (!array_key_exists($key, $this->headers)) {
if (null === $default) { if (null === $default) {
@ -139,7 +139,7 @@ class HeaderBag implements \IteratorAggregate, \Countable
*/ */
public function set($key, $values, $replace = true) public function set($key, $values, $replace = true)
{ {
$key = strtr(strtolower($key), '_', '-'); $key = str_replace('_', '-', strtolower($key));
$values = array_values((array) $values); $values = array_values((array) $values);
@ -163,7 +163,7 @@ class HeaderBag implements \IteratorAggregate, \Countable
*/ */
public function has($key) public function has($key)
{ {
return array_key_exists(strtr(strtolower($key), '_', '-'), $this->headers); return array_key_exists(str_replace('_', '-', strtolower($key)), $this->headers);
} }
/** /**
@ -186,7 +186,7 @@ class HeaderBag implements \IteratorAggregate, \Countable
*/ */
public function remove($key) public function remove($key)
{ {
$key = strtr(strtolower($key), '_', '-'); $key = str_replace('_', '-', strtolower($key));
unset($this->headers[$key]); unset($this->headers[$key]);

View File

@ -99,7 +99,7 @@ class ResponseHeaderBag extends HeaderBag
{ {
parent::set($key, $values, $replace); parent::set($key, $values, $replace);
$uniqueKey = strtr(strtolower($key), '_', '-'); $uniqueKey = str_replace('_', '-', strtolower($key));
$this->headerNames[$uniqueKey] = $key; $this->headerNames[$uniqueKey] = $key;
// ensure the cache-control header has sensible defaults // ensure the cache-control header has sensible defaults
@ -118,7 +118,7 @@ class ResponseHeaderBag extends HeaderBag
{ {
parent::remove($key); parent::remove($key);
$uniqueKey = strtr(strtolower($key), '_', '-'); $uniqueKey = str_replace('_', '-', strtolower($key));
unset($this->headerNames[$uniqueKey]); unset($this->headerNames[$uniqueKey]);
if ('cache-control' === $uniqueKey) { if ('cache-control' === $uniqueKey) {

View File

@ -181,7 +181,7 @@ abstract class Bundle extends ContainerAware implements BundleInterface
foreach ($finder as $file) { foreach ($finder as $file) {
$ns = $prefix; $ns = $prefix;
if ($relativePath = $file->getRelativePath()) { if ($relativePath = $file->getRelativePath()) {
$ns .= '\\'.strtr($relativePath, '/', '\\'); $ns .= '\\'.str_replace('/', '\\', $relativePath);
} }
$r = new \ReflectionClass($ns.'\\'.$file->getBasename('.php')); $r = new \ReflectionClass($ns.'\\'.$file->getBasename('.php'));
if ($r->isSubclassOf('Symfony\\Component\\Console\\Command\\Command') && !$r->isAbstract() && !$r->getConstructor()->getNumberOfRequiredParameters()) { if ($r->isSubclassOf('Symfony\\Component\\Console\\Command\\Command') && !$r->isAbstract() && !$r->getConstructor()->getNumberOfRequiredParameters()) {

View File

@ -38,10 +38,8 @@ class Store implements StoreInterface
public function __construct($root) public function __construct($root)
{ {
$this->root = $root; $this->root = $root;
if (!is_dir($this->root)) { if (!is_dir($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) {
if (false === @mkdir($this->root, 0777, true) && !is_dir($this->root)) { throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
}
} }
$this->keyCache = new \SplObjectStorage(); $this->keyCache = new \SplObjectStorage();
$this->locks = array(); $this->locks = array();
@ -249,10 +247,8 @@ class Store implements StoreInterface
} }
} }
if ($modified) { if ($modified && false === $this->save($key, serialize($entries))) {
if (false === $this->save($key, serialize($entries))) { throw new \RuntimeException('Unable to store the metadata.');
throw new \RuntimeException('Unable to store the metadata.');
}
} }
} }
@ -273,7 +269,7 @@ class Store implements StoreInterface
} }
foreach (preg_split('/[\s,]+/', $vary) as $header) { foreach (preg_split('/[\s,]+/', $vary) as $header) {
$key = strtr(strtolower($header), '_', '-'); $key = str_replace('_', '-', strtolower($header));
$v1 = isset($env1[$key]) ? $env1[$key] : null; $v1 = isset($env1[$key]) ? $env1[$key] : null;
$v2 = isset($env2[$key]) ? $env2[$key] : null; $v2 = isset($env2[$key]) ? $env2[$key] : null;
if ($v1 !== $v2) { if ($v1 !== $v2) {

View File

@ -187,9 +187,8 @@ abstract class PdoProfilerStorage implements ProfilerStorageInterface
$stmt->bindValue($arg, $val, is_int($val) ? \PDO::PARAM_INT : \PDO::PARAM_STR); $stmt->bindValue($arg, $val, is_int($val) ? \PDO::PARAM_INT : \PDO::PARAM_STR);
} }
$stmt->execute(); $stmt->execute();
$return = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $return; return $stmt->fetchAll(\PDO::FETCH_ASSOC);
} }
protected function close($db) protected function close($db)

View File

@ -51,7 +51,7 @@ class UriSigner
$uri = $this->buildUrl($url, $params); $uri = $this->buildUrl($url, $params);
return $uri.(false === (strpos($uri, '?')) ? '?' : '&').'_hash='.$this->computeHash($uri); return $uri.(false === strpos($uri, '?') ? '?' : '&').'_hash='.$this->computeHash($uri);
} }
/** /**

View File

@ -442,11 +442,11 @@ class PropertyAccessor implements PropertyAccessorInterface
} }
foreach ($itemToRemove as $item) { foreach ($itemToRemove as $item) {
call_user_func(array($object, $access[self::ACCESS_REMOVER]), $item); $object->{$access[self::ACCESS_REMOVER]}($item);
} }
foreach ($itemsToAdd as $item) { foreach ($itemsToAdd as $item) {
call_user_func(array($object, $access[self::ACCESS_ADDER]), $item); $object->{$access[self::ACCESS_ADDER]}($item);
} }
} elseif (!$access[self::ACCESS_HAS_PROPERTY] && property_exists($object, $property)) { } elseif (!$access[self::ACCESS_HAS_PROPERTY] && property_exists($object, $property)) {
// Needed to support \stdClass instances. We need to explicitly // Needed to support \stdClass instances. We need to explicitly

View File

@ -172,10 +172,8 @@ class DigestData
throw new BadCredentialsException(sprintf('Missing mandatory digest value; received header "%s" (%s)', $this->header, implode(', ', $keys))); throw new BadCredentialsException(sprintf('Missing mandatory digest value; received header "%s" (%s)', $this->header, implode(', ', $keys)));
} }
if ('auth' === $this->elements['qop']) { if ('auth' === $this->elements['qop'] && !isset($this->elements['nc'], $this->elements['cnonce'])) {
if (!isset($this->elements['nc']) || !isset($this->elements['cnonce'])) { throw new BadCredentialsException(sprintf('Missing mandatory digest value; received header "%s"', $this->header));
throw new BadCredentialsException(sprintf('Missing mandatory digest value; received header "%s"', $this->header));
}
} }
if ($expectedRealm !== $this->elements['realm']) { if ($expectedRealm !== $this->elements['realm']) {

View File

@ -30,8 +30,8 @@ class IcuResFileDumper implements DumperInterface
} }
// save a file for each domain // save a file for each domain
$file = $messages->getLocale().'.'.$this->getExtension();
foreach ($messages->getDomains() as $domain) { foreach ($messages->getDomains() as $domain) {
$file = $messages->getLocale().'.'.$this->getExtension();
$path = $options['path'].'/'.$domain.'/'; $path = $options['path'].'/'.$domain.'/';
if (!is_dir($path) && !@mkdir($path) && !is_dir($path)) { if (!is_dir($path) && !@mkdir($path) && !is_dir($path)) {

View File

@ -190,7 +190,7 @@ class XmlFileLoader extends FileLoader
*/ */
private function loadClassMetadataFromXml(ClassMetadata $metadata, $classDescription) private function loadClassMetadataFromXml(ClassMetadata $metadata, $classDescription)
{ {
foreach ($classDescription->{'group-sequence-provider'} as $_) { if (count($classDescription->{'group-sequence-provider'}) > 0) {
$metadata->setGroupSequenceProvider(true); $metadata->setGroupSequenceProvider(true);
} }