Php Inspections (EA Extended) - static code analysis includes:

Reduce couple count calls in [Yaml]
Modernize type casting, fix several strict comparisons
Unsets merged
Elvis operator usage
Short syntax for applied operations
This commit is contained in:
Vladimir Reznichenko 2015-03-07 20:12:23 +01:00
parent e64b75f7d3
commit 968275624a
19 changed files with 45 additions and 51 deletions

View File

@ -84,7 +84,7 @@ class TwigExtractor implements ExtractorInterface
$this->twig->parse($this->twig->tokenize($template)); $this->twig->parse($this->twig->tokenize($template));
foreach ($visitor->getMessages() as $message) { foreach ($visitor->getMessages() as $message) {
$catalogue->set(trim($message[0]), $this->prefix.trim($message[0]), $message[1] ? $message[1] : $this->defaultDomain); $catalogue->set(trim($message[0]), $this->prefix.trim($message[0]), $message[1] ?: $this->defaultDomain);
} }
$visitor->disable(); $visitor->disable();

View File

@ -305,7 +305,7 @@ EOF
$synthetic = $definition->isSynthetic() ? 'yes' : 'no'; $synthetic = $definition->isSynthetic() ? 'yes' : 'no';
$output->writeln(sprintf('<comment>Synthetic</comment> %s', $synthetic)); $output->writeln(sprintf('<comment>Synthetic</comment> %s', $synthetic));
$file = $definition->getFile() ? $definition->getFile() : '-'; $file = $definition->getFile() ?: '-';
$output->writeln(sprintf('<comment>Required File</comment> %s', $file)); $output->writeln(sprintf('<comment>Required File</comment> %s', $file));
} elseif ($definition instanceof Alias) { } elseif ($definition instanceof Alias) {
$alias = $definition; $alias = $definition;

View File

@ -191,17 +191,17 @@ class XmlUtils
return; return;
case ctype_digit($value): case ctype_digit($value):
$raw = $value; $raw = $value;
$cast = intval($value); $cast = (int) $value;
return '0' == $value[0] ? octdec($value) : (((string) $raw == (string) $cast) ? $cast : $raw); return '0' == $value[0] ? octdec($value) : (((string) $raw === (string) $cast) ? $cast : $raw);
case 'true' === $lowercaseValue: case 'true' === $lowercaseValue:
return true; return true;
case 'false' === $lowercaseValue: case 'false' === $lowercaseValue:
return false; return false;
case is_numeric($value): case is_numeric($value):
return '0x' == $value[0].$value[1] ? hexdec($value) : floatval($value); return '0x' === $value[0].$value[1] ? hexdec($value) : (float) $value;
case preg_match('/^(-|\+)?[0-9]+(\.[0-9]+)?$/', $value): case preg_match('/^(-|\+)?[0-9]+(\.[0-9]+)?$/', $value):
return floatval($value); return (float) $value;
default: default:
return $value; return $value;
} }

View File

@ -235,11 +235,11 @@ class ProgressHelper extends Helper
$redraw = true; $redraw = true;
} }
$prevPeriod = intval($this->current / $this->redrawFreq); $prevPeriod = (int) ($this->current / $this->redrawFreq);
$this->current += $step; $this->current += $step;
$currPeriod = intval($this->current / $this->redrawFreq); $currPeriod = (int) ($this->current / $this->redrawFreq);
if ($redraw || $prevPeriod !== $currPeriod || $this->max === $this->current) { if ($redraw || $prevPeriod !== $currPeriod || $this->max === $this->current) {
$this->display(); $this->display();
} }
@ -269,11 +269,11 @@ class ProgressHelper extends Helper
$redraw = true; $redraw = true;
} }
$prevPeriod = intval($this->current / $this->redrawFreq); $prevPeriod = (int) ($this->current / $this->redrawFreq);
$this->current = $current; $this->current = $current;
$currPeriod = intval($this->current / $this->redrawFreq); $currPeriod = (int) ($this->current / $this->redrawFreq);
if ($redraw || $prevPeriod !== $currPeriod || $this->max === $this->current) { if ($redraw || $prevPeriod !== $currPeriod || $this->max === $this->current) {
$this->display(); $this->display();
} }

View File

@ -1341,13 +1341,13 @@ EOF;
if ('' === $name) { if ('' === $name) {
$name .= $firstChars[$i%$firstCharsLength]; $name .= $firstChars[$i%$firstCharsLength];
$i = intval($i/$firstCharsLength); $i = (int) ($i/$firstCharsLength);
} }
while ($i > 0) { while ($i > 0) {
--$i; --$i;
$name .= $nonFirstChars[$i%$nonFirstCharsLength]; $name .= $nonFirstChars[$i%$nonFirstCharsLength];
$i = intval($i/$nonFirstCharsLength); $i = (int) ($i/$nonFirstCharsLength);
} }
++$this->variableCount; ++$this->variableCount;

View File

@ -154,7 +154,7 @@ class Link
} }
if ('.' === substr($path, -1)) { if ('.' === substr($path, -1)) {
$path = $path.'/'; $path .= '/';
} }
$output = array(); $output = array();

View File

@ -436,9 +436,9 @@ class Finder implements \IteratorAggregate, \Countable
public function ignoreDotFiles($ignoreDotFiles) public function ignoreDotFiles($ignoreDotFiles)
{ {
if ($ignoreDotFiles) { if ($ignoreDotFiles) {
$this->ignore = $this->ignore | static::IGNORE_DOT_FILES; $this->ignore |= static::IGNORE_DOT_FILES;
} else { } else {
$this->ignore = $this->ignore & ~static::IGNORE_DOT_FILES; $this->ignore &= ~static::IGNORE_DOT_FILES;
} }
return $this; return $this;
@ -458,9 +458,9 @@ class Finder implements \IteratorAggregate, \Countable
public function ignoreVCS($ignoreVCS) public function ignoreVCS($ignoreVCS)
{ {
if ($ignoreVCS) { if ($ignoreVCS) {
$this->ignore = $this->ignore | static::IGNORE_VCS_FILES; $this->ignore |= static::IGNORE_VCS_FILES;
} else { } else {
$this->ignore = $this->ignore & ~static::IGNORE_VCS_FILES; $this->ignore &= ~static::IGNORE_VCS_FILES;
} }
return $this; return $this;

View File

@ -131,7 +131,7 @@ class ChoiceType extends AbstractType
// Add "[]" to the name in case a select tag with multiple options is // Add "[]" to the name in case a select tag with multiple options is
// displayed. Otherwise only one of the selected options is sent in the // displayed. Otherwise only one of the selected options is sent in the
// POST request. // POST request.
$view->vars['full_name'] = $view->vars['full_name'].'[]'; $view->vars['full_name'] .= '[]';
} }
} }

View File

@ -35,7 +35,7 @@ class ServerParams
} elseif (0 === strpos($max, '0')) { } elseif (0 === strpos($max, '0')) {
$max = intval($max, 8); $max = intval($max, 8);
} else { } else {
$max = intval($max); $max = (int) $max;
} }
switch (substr($iniMax, -1)) { switch (substr($iniMax, -1)) {

View File

@ -270,7 +270,7 @@ class UploadedFile extends File
} elseif (0 === strpos($max, '0')) { } elseif (0 === strpos($max, '0')) {
$max = intval($max, 8); $max = intval($max, 8);
} else { } else {
$max = intval($max); $max = (int) $max;
} }
switch (substr($iniMax, -1)) { switch (substr($iniMax, -1)) {

View File

@ -975,7 +975,7 @@ class Request
} }
if (false !== $pos) { if (false !== $pos) {
return intval(substr($host, $pos + 1)); return (int) substr($host, $pos + 1);
} }
return 'https' === $this->getScheme() ? 443 : 80; return 'https' === $this->getScheme() ? 443 : 80;

View File

@ -1195,7 +1195,7 @@ class Response
protected function ensureIEOverSSLCompatibility(Request $request) protected function ensureIEOverSSLCompatibility(Request $request)
{ {
if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) == 1 && true === $request->isSecure()) { if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) == 1 && true === $request->isSecure()) {
if (intval(preg_replace("/(MSIE )(.*?);/", "$2", $match[0])) < 9) { if ((int) preg_replace("/(MSIE )(.*?);/", "$2", $match[0]) < 9) {
$this->headers->remove('Cache-Control'); $this->headers->remove('Cache-Control');
} }
} }

View File

@ -86,7 +86,7 @@ class MemoryDataCollector extends DataCollector
} elseif (0 === strpos($max, '0')) { } elseif (0 === strpos($max, '0')) {
$max = intval($max, 8); $max = intval($max, 8);
} else { } else {
$max = intval($max); $max = (int) $max;
} }
switch (substr($memoryLimit, -1)) { switch (substr($memoryLimit, -1)) {

View File

@ -92,8 +92,7 @@ class Options implements \ArrayAccess, \Iterator, \Countable
// Setting is equivalent to overloading while discarding the previous // Setting is equivalent to overloading while discarding the previous
// option value // option value
unset($this->options[$option]); unset($this->options[$option], $this->lazy[$option]);
unset($this->lazy[$option]);
$this->overload($option, $value); $this->overload($option, $value);
} }
@ -270,9 +269,7 @@ class Options implements \ArrayAccess, \Iterator, \Countable
throw new OptionDefinitionException('Options cannot be removed anymore once options have been read.'); throw new OptionDefinitionException('Options cannot be removed anymore once options have been read.');
} }
unset($this->options[$option]); unset($this->options[$option], $this->lazy[$option], $this->normalizers[$option]);
unset($this->lazy[$option]);
unset($this->normalizers[$option]);
} }
/** /**
@ -470,10 +467,8 @@ class Options implements \ArrayAccess, \Iterator, \Countable
foreach ($this->lazy[$option] as $closure) { foreach ($this->lazy[$option] as $closure) {
$this->options[$option] = $closure($this, $this->options[$option]); $this->options[$option] = $closure($this, $this->options[$option]);
} }
unset($this->lock[$option]);
// The option now isn't lazy anymore // The option now isn't lazy anymore
unset($this->lazy[$option]); unset($this->lock[$option], $this->lazy[$option]);
} }
/** /**
@ -509,9 +504,7 @@ class Options implements \ArrayAccess, \Iterator, \Countable
$this->lock[$option] = true; $this->lock[$option] = true;
$this->options[$option] = $normalizer($this, array_key_exists($option, $this->options) ? $this->options[$option] : null); $this->options[$option] = $normalizer($this, array_key_exists($option, $this->options) ? $this->options[$option] : null);
unset($this->lock[$option]);
// The option is now normalized // The option is now normalized
unset($this->normalizers[$option]); unset($this->lock[$option], $this->normalizers[$option]);
} }
} }

View File

@ -242,7 +242,7 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf
if (null === $propertyChanges['parentAcl'][1]) { if (null === $propertyChanges['parentAcl'][1]) {
$sets[] = 'parent_object_identity_id = NULL'; $sets[] = 'parent_object_identity_id = NULL';
} else { } else {
$sets[] = 'parent_object_identity_id = '.intval($propertyChanges['parentAcl'][1]->getId()); $sets[] = 'parent_object_identity_id = '.(int) $propertyChanges['parentAcl'][1]->getId();
} }
$this->regenerateAncestorRelations($acl); $this->regenerateAncestorRelations($acl);
@ -453,7 +453,7 @@ QUERY;
$query, $query,
$this->options['entry_table_name'], $this->options['entry_table_name'],
$classId, $classId,
null === $objectIdentityId ? 'NULL' : intval($objectIdentityId), null === $objectIdentityId ? 'NULL' : (int) $objectIdentityId,
null === $field ? 'NULL' : $this->connection->quote($field), null === $field ? 'NULL' : $this->connection->quote($field),
$aceOrder, $aceOrder,
$securityIdentityId, $securityIdentityId,
@ -571,7 +571,7 @@ QUERY;
$classId, $classId,
null === $oid ? null === $oid ?
$this->connection->getDatabasePlatform()->getIsNullExpression('object_identity_id') $this->connection->getDatabasePlatform()->getIsNullExpression('object_identity_id')
: 'object_identity_id = '.intval($oid), : 'object_identity_id = '.(int) $oid,
null === $field ? null === $field ?
$this->connection->getDatabasePlatform()->getIsNullExpression('field_name') $this->connection->getDatabasePlatform()->getIsNullExpression('field_name')
: 'field_name = '.$this->connection->quote($field), : 'field_name = '.$this->connection->quote($field),
@ -812,7 +812,7 @@ QUERY;
$aceIdProperty = new \ReflectionProperty('Symfony\Component\Security\Acl\Domain\Entry', 'id'); $aceIdProperty = new \ReflectionProperty('Symfony\Component\Security\Acl\Domain\Entry', 'id');
$aceIdProperty->setAccessible(true); $aceIdProperty->setAccessible(true);
$aceIdProperty->setValue($ace, intval($aceId)); $aceIdProperty->setValue($ace, (int) $aceId);
} else { } else {
$currentIds[$ace->getId()] = true; $currentIds[$ace->getId()] = true;
} }
@ -888,7 +888,7 @@ QUERY;
$aceIdProperty = new \ReflectionProperty($ace, 'id'); $aceIdProperty = new \ReflectionProperty($ace, 'id');
$aceIdProperty->setAccessible(true); $aceIdProperty->setAccessible(true);
$aceIdProperty->setValue($ace, intval($aceId)); $aceIdProperty->setValue($ace, (int) $aceId);
} }
} }
} }

View File

@ -50,7 +50,7 @@ class DigestAuthenticationEntryPoint implements AuthenticationEntryPointInterfac
$authenticateHeader = sprintf('Digest realm="%s", qop="auth", nonce="%s"', $this->realmName, $nonceValueBase64); $authenticateHeader = sprintf('Digest realm="%s", qop="auth", nonce="%s"', $this->realmName, $nonceValueBase64);
if ($authException instanceof NonceExpiredException) { if ($authException instanceof NonceExpiredException) {
$authenticateHeader = $authenticateHeader.', stale="true"'; $authenticateHeader .= ', stale="true"';
} }
if (null !== $this->logger) { if (null !== $this->logger) {

View File

@ -81,7 +81,7 @@ class IsbnValidator extends ConstraintValidator
return false; return false;
} }
$checkSum += $digit * intval(10 - $i); $checkSum += $digit * (10 - $i);
} }
return 0 === $checkSum % 11; return 0 === $checkSum % 11;

View File

@ -125,7 +125,7 @@ class Inline
if (false !== $locale) { if (false !== $locale) {
setlocale(LC_NUMERIC, 'C'); setlocale(LC_NUMERIC, 'C');
} }
$repr = is_string($value) ? "'$value'" : (is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : strval($value)); $repr = is_string($value) ? "'$value'" : (is_infinite($value) ? str_ireplace('INF', '.Inf', (string) $value) : (string) $value);
if (false !== $locale) { if (false !== $locale) {
setlocale(LC_NUMERIC, $locale); setlocale(LC_NUMERIC, $locale);
@ -157,8 +157,9 @@ class Inline
{ {
// array // array
$keys = array_keys($value); $keys = array_keys($value);
if ((1 == count($keys) && '0' == $keys[0]) $keysCount = count($keys);
|| (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (int) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2) if ((1 === $keysCount && '0' == $keys[0])
|| ($keysCount > 1 && array_reduce($keys, function ($v, $w) { return (int) $v + $w; }, 0) === $keysCount * ($keysCount - 1) / 2)
) { ) {
$output = array(); $output = array();
foreach ($value as $val) { foreach ($value as $val) {
@ -431,7 +432,7 @@ class Inline
case 0 === strpos($scalar, '!str'): case 0 === strpos($scalar, '!str'):
return (string) substr($scalar, 5); return (string) substr($scalar, 5);
case 0 === strpos($scalar, '! '): case 0 === strpos($scalar, '! '):
return intval(self::parseScalar(substr($scalar, 2))); return (int) self::parseScalar(substr($scalar, 2));
case 0 === strpos($scalar, '!!php/object:'): case 0 === strpos($scalar, '!!php/object:'):
if (self::$objectSupport) { if (self::$objectSupport) {
return unserialize(substr($scalar, 13)); return unserialize(substr($scalar, 13));
@ -444,23 +445,23 @@ class Inline
return; return;
case ctype_digit($scalar): case ctype_digit($scalar):
$raw = $scalar; $raw = $scalar;
$cast = intval($scalar); $cast = (int) $scalar;
return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)): case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
$raw = $scalar; $raw = $scalar;
$cast = intval($scalar); $cast = (int) $scalar;
return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw);
case is_numeric($scalar): case is_numeric($scalar):
return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar); return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar;
case '.inf' === $scalarLower: case '.inf' === $scalarLower:
case '.nan' === $scalarLower: case '.nan' === $scalarLower:
return -log(0); return -log(0);
case '-.inf' === $scalarLower: case '-.inf' === $scalarLower:
return log(0); return log(0);
case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
return floatval(str_replace(',', '', $scalar)); return (float) str_replace(',', '', $scalar);
case preg_match(self::getTimestampRegex(), $scalar): case preg_match(self::getTimestampRegex(), $scalar):
return strtotime($scalar); return strtotime($scalar);
} }

View File

@ -423,7 +423,7 @@ class Parser
if (preg_match('/^'.self::FOLDED_SCALAR_PATTERN.'$/', $value, $matches)) { if (preg_match('/^'.self::FOLDED_SCALAR_PATTERN.'$/', $value, $matches)) {
$modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers))); return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
} }
try { try {