Browse Source

[minor] SCA with Php Inspections (EA Ultimate) (#15871)

* Php Inspections (EA Ultimate): use type casting where applicable

* Php Inspections (EA Ultimate): use constants where applicable

* Php Inspections (EA Ultimate): CS

* Php Inspections (EA Ultimate): address some of one-time used variables

* Php Inspections (EA Ultimate): address some of performance-related findings

* Php Inspections (EA Ultimate): address some of performance-related findings

* Php Inspections (EA Ultimate): revert a constant usage

* Php Inspections (EA Ultimate): revert sequential assignments

* Php Inspections (EA Ultimate): build is green again

* Php Inspections (EA Ultimate): revert array_merge tweaks

* Php Inspections (EA Ultimate): revert BC-incompatible one-time used variable tweak

* Update description [skip ci]

* Php Inspections (EA Ultimate): CS
tags/2.0.14.2
Vladimir Reznichenko 7 years ago committed by Alexander Makarov
parent
commit
1a74b3d4f8
  1. 2
      framework/base/ErrorHandler.php
  2. 3
      framework/console/UnknownCommandException.php
  3. 2
      framework/console/controllers/AssetController.php
  4. 2
      framework/console/controllers/CacheController.php
  5. 17
      framework/console/controllers/HelpController.php
  6. 2
      framework/console/controllers/MessageController.php
  7. 2
      framework/console/controllers/MigrateController.php
  8. 3
      framework/data/Sort.php
  9. 2
      framework/db/ActiveQuery.php
  10. 2
      framework/db/Query.php
  11. 2
      framework/db/pgsql/JsonExpressionBuilder.php
  12. 5
      framework/db/pgsql/Schema.php
  13. 2
      framework/db/sqlite/Schema.php
  14. 3
      framework/filters/Cors.php
  15. 3
      framework/helpers/BaseArrayHelper.php
  16. 2
      framework/helpers/BaseStringHelper.php
  17. 4
      framework/helpers/BaseVarDumper.php
  18. 2
      framework/i18n/Formatter.php
  19. 6
      framework/log/migrations/m141106_185632_log_init.php
  20. 2
      framework/mutex/OracleMutex.php
  21. 2
      framework/web/ErrorHandler.php
  22. 4
      framework/web/Request.php
  23. 11
      framework/web/Response.php
  24. 4
      framework/web/UrlManager.php
  25. 6
      framework/web/UrlRule.php

2
framework/base/ErrorHandler.php

@ -347,7 +347,7 @@ abstract class ErrorHandler extends Component
if ($exception instanceof Exception) {
$message = "Exception ({$exception->getName()})";
} elseif ($exception instanceof ErrorException) {
$message = "{$exception->getName()}";
$message = (string)$exception->getName();
} else {
$message = 'Exception';
}

3
framework/console/UnknownCommandException.php

@ -74,8 +74,7 @@ class UnknownCommandException extends Exception
list($helpController, $actionID) = $help;
$availableActions = [];
$commands = $helpController->getCommands();
foreach ($commands as $command) {
foreach ($helpController->getCommands() as $command) {
$result = $this->application->createController($command);
if ($result === false) {
continue;

2
framework/console/controllers/AssetController.php

@ -646,7 +646,7 @@ EOD;
$fullMatch = $matches[0];
$inputUrl = $matches[1];
if (strpos($inputUrl, '/') === 0 || strpos($inputUrl, '#') === 0 || preg_match('/^https?:\/\//i', $inputUrl) || preg_match('/^data:/i', $inputUrl)) {
if (strncmp($inputUrl, '/', 1) === 0 || strncmp($inputUrl, '#', 1) === 0 || preg_match('/^https?:\/\//i', $inputUrl) || preg_match('/^data:/i', $inputUrl)) {
return $fullMatch;
}
if ($inputFileRelativePathParts === $outputFileRelativePathParts) {

2
framework/console/controllers/CacheController.php

@ -300,6 +300,6 @@ class CacheController extends Controller
*/
private function canBeFlushed($className)
{
return !is_a($className, ApcCache::className(), true) || php_sapi_name() !== 'cli';
return !is_a($className, ApcCache::className(), true) || PHP_SAPI !== 'cli';
}
}

17
framework/console/controllers/HelpController.php

@ -75,8 +75,7 @@ class HelpController extends Controller
*/
public function actionList()
{
$commands = $this->getCommandDescriptions();
foreach ($commands as $command => $description) {
foreach ($this->getCommandDescriptions() as $command => $description) {
$result = Yii::$app->createController($command);
if ($result === false || !($result[0] instanceof Controller)) {
continue;
@ -116,15 +115,13 @@ class HelpController extends Controller
return;
}
$arguments = $controller->getActionArgsHelp($action);
foreach ($arguments as $argument => $help) {
foreach ($controller->getActionArgsHelp($action) as $argument => $help) {
$description = str_replace("\n", '', addcslashes($help['comment'], ':')) ?: $argument;
$this->stdout($argument . ':' . $description . "\n");
}
$this->stdout("\n");
$options = $controller->getActionOptionsHelp($action);
foreach ($options as $argument => $help) {
foreach ($controller->getActionOptionsHelp($action) as $argument => $help) {
$description = str_replace("\n", '', addcslashes($help['comment'], ':'));
$this->stdout('--' . $argument . ($description ? ':' . $description : '') . "\n");
}
@ -158,8 +155,7 @@ class HelpController extends Controller
$this->stdout($scriptName . ' ' . $this->ansiFormat($action->getUniqueId(), Console::FG_YELLOW));
}
$args = $controller->getActionArgsHelp($action);
foreach ($args as $name => $arg) {
foreach ($controller->getActionArgsHelp($action) as $name => $arg) {
if ($arg['required']) {
$this->stdout(' <' . $name . '>', Console::FG_CYAN);
} else {
@ -215,7 +211,7 @@ class HelpController extends Controller
$class = new \ReflectionClass($controller);
foreach ($class->getMethods() as $method) {
$name = $method->getName();
if ($name !== 'actions' && $method->isPublic() && !$method->isStatic() && strpos($name, 'action') === 0) {
if ($name !== 'actions' && $method->isPublic() && !$method->isStatic() && strncmp($name, 'action', 6) === 0) {
$actions[] = Inflector::camel2id(substr($name, 6), '-', true);
}
}
@ -535,8 +531,7 @@ class HelpController extends Controller
*/
protected function formatOptionAliases($controller, $option)
{
$aliases = $controller->optionAliases();
foreach ($aliases as $name => $value) {
foreach ($controller->optionAliases() as $name => $value) {
if ($value === $option) {
return ', -' . $name;
}

2
framework/console/controllers/MessageController.php

@ -804,7 +804,7 @@ EOD;
// add obsolete unused messages
foreach ($existingMessages as $message => $translation) {
if (!$removeUnused && !isset($merged[$category . chr(4) . $message]) && !isset($todos[$category . chr(4) . $message])) {
if (!$markUnused || (!empty($translation) && ((substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@')))) {
if (!$markUnused || (!empty($translation) && (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@'))) {
$todos[$category . chr(4) . $message] = $translation;
} else {
$todos[$category . chr(4) . $message] = '@@' . $translation . '@@';

2
framework/console/controllers/MigrateController.php

@ -483,7 +483,7 @@ class MigrateController extends BaseMigrateController
$property = array_shift($chunks);
foreach ($chunks as $i => &$chunk) {
if (strpos($chunk, 'foreignKey') === 0) {
if (strncmp($chunk, 'foreignKey', 10) === 0) {
preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
$foreignKeys[$property] = [
'table' => isset($matches[1])

3
framework/data/Sort.php

@ -257,8 +257,7 @@ class Sort extends BaseObject
$params = $request instanceof Request ? $request->getQueryParams() : [];
}
if (isset($params[$this->sortParam])) {
$attributes = $this->parseSortParam($params[$this->sortParam]);
foreach ($attributes as $attribute) {
foreach ($this->parseSortParam($params[$this->sortParam]) as $attribute) {
$descending = false;
if (strncmp($attribute, '-', 1) === 0) {
$descending = true;

2
framework/db/ActiveQuery.php

@ -762,7 +762,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface
*/
public function viaTable($tableName, $link, callable $callable = null)
{
$modelClass = $this->primaryModel !== null ? get_class($this->primaryModel) : get_class();
$modelClass = $this->primaryModel !== null ? get_class($this->primaryModel) : __CLASS__;
$relation = new self($modelClass, [
'from' => [$tableName],

2
framework/db/Query.php

@ -610,6 +610,8 @@ PATTERN;
} elseif (!is_array($columns)) {
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
}
// this sequantial assignment is needed in order to make sure select is being reset
// before using getUniqueColumns() that checks it
$this->select = [];
$this->select = $this->getUniqueColumns($columns);
$this->selectOption = $option;

2
framework/db/pgsql/JsonExpressionBuilder.php

@ -39,7 +39,7 @@ class JsonExpressionBuilder implements ExpressionBuilderInterface
return "($sql)" . $this->getTypecast($expression);
}
if ($value instanceof ArrayExpression) {
$placeholder = "array_to_json(" . $this->queryBuilder->buildExpression($value, $params) . ")";
$placeholder = 'array_to_json(' . $this->queryBuilder->buildExpression($value, $params) . ')';
} else {
$placeholder = $this->queryBuilder->bindParam(Json::encode($value), $params);
}

5
framework/db/pgsql/Schema.php

@ -438,8 +438,7 @@ SQL;
{
$uniqueIndexes = [];
$rows = $this->getUniqueIndexInformation($table);
foreach ($rows as $row) {
foreach ($this->getUniqueIndexInformation($table) as $row) {
if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_UPPER) {
$row = array_change_key_case($row, CASE_LOWER);
}
@ -546,7 +545,7 @@ SQL;
$column->defaultValue = new Expression($column->defaultValue);
} elseif ($column->type === 'boolean') {
$column->defaultValue = ($column->defaultValue === 'true');
} elseif (stripos($column->dbType, 'bit') === 0 || stripos($column->dbType, 'varbit') === 0) {
} elseif (strncasecmp($column->dbType, 'bit', 3) === 0 || strncasecmp($column->dbType, 'varbit', 6) === 0) {
$column->defaultValue = bindec(trim($column->defaultValue, 'B\''));
} elseif (preg_match("/^'(.*?)'::/", $column->defaultValue, $matches)) {
$column->defaultValue = $column->phpTypecast($matches[1]);

2
framework/db/sqlite/Schema.php

@ -451,6 +451,6 @@ class Schema extends \yii\db\Schema implements ConstraintFinderInterface
*/
private function isSystemIdentifier($identifier)
{
return strpos($identifier, 'sqlite_') === 0;
return strncmp($identifier, 'sqlite_', 7) === 0;
}
}

3
framework/filters/Cors.php

@ -139,8 +139,7 @@ class Cors extends ActionFilter
public function extractHeaders()
{
$headers = [];
$requestHeaders = array_keys($this->cors);
foreach ($requestHeaders as $headerField) {
foreach (array_keys($this->cors) as $headerField) {
$serverField = $this->headerizeToPhp($headerField);
$headerData = isset($_SERVER[$serverField]) ? $_SERVER[$serverField] : null;
if ($headerData !== null) {

3
framework/helpers/BaseArrayHelper.php

@ -119,8 +119,7 @@ class BaseArrayHelper
$args = func_get_args();
$res = array_shift($args);
while (!empty($args)) {
$next = array_shift($args);
foreach ($next as $k => $v) {
foreach (array_shift($args) as $k => $v) {
if ($v instanceof UnsetArrayValue) {
unset($res[$k]);
} elseif ($v instanceof ReplaceArrayValue) {

2
framework/helpers/BaseStringHelper.php

@ -310,7 +310,7 @@ class BaseStringHelper
*/
public static function normalizeNumber($value)
{
$value = "$value";
$value = (string)$value;
$localeInfo = localeconv();
$decimalSeparator = isset($localeInfo['decimal_point']) ? $localeInfo['decimal_point'] : null;

4
framework/helpers/BaseVarDumper.php

@ -72,10 +72,10 @@ class BaseVarDumper
self::$_output .= $var ? 'true' : 'false';
break;
case 'integer':
self::$_output .= "$var";
self::$_output .= (string)$var;
break;
case 'double':
self::$_output .= "$var";
self::$_output .= (string)$var;
break;
case 'string':
self::$_output .= "'" . addslashes($var) . "'";

2
framework/i18n/Formatter.php

@ -1005,7 +1005,7 @@ class Formatter extends Component
$zeroDateTime = (new DateTime())->setTimestamp(0);
$valueDateTime = (new DateTime())->setTimestamp(abs($value));
$interval = $valueDateTime->diff($zeroDateTime);
} elseif (strpos($value, 'P-') === 0) {
} elseif (strncmp($value, 'P-', 2) === 0) {
$interval = new DateInterval('P' . substr($value, 2));
$isNegative = true;
} else {

6
framework/log/migrations/m141106_185632_log_init.php

@ -60,8 +60,7 @@ class m141106_185632_log_init extends Migration
public function up()
{
$targets = $this->getDbTargets();
foreach ($targets as $target) {
foreach ($this->getDbTargets() as $target) {
$this->db = $target->db;
$tableOptions = null;
@ -86,8 +85,7 @@ class m141106_185632_log_init extends Migration
public function down()
{
$targets = $this->getDbTargets();
foreach ($targets as $target) {
foreach ($this->getDbTargets() as $target) {
$this->db = $target->db;
$this->dropTable($target->logTable);

2
framework/mutex/OracleMutex.php

@ -67,7 +67,7 @@ class OracleMutex extends DbMutex
public function init()
{
parent::init();
if (strpos($this->db->driverName, 'oci') !== 0 && strpos($this->db->driverName, 'odbc') !== 0) {
if (strncmp($this->db->driverName, 'oci', 3) !== 0 && strncmp($this->db->driverName, 'odbc', 4) !== 0) {
throw new InvalidConfigException('In order to use OracleMutex connection must be configured to use Oracle database.');
}
}

2
framework/web/ErrorHandler.php

@ -232,7 +232,7 @@ class ErrorHandler extends \yii\base\ErrorHandler
*/
protected function getTypeUrl($class, $method)
{
if (strpos($class, 'yii\\') !== 0) {
if (strncmp($class, 'yii\\', 4) !== 0) {
return null;
}

4
framework/web/Request.php

@ -809,7 +809,7 @@ class Request extends \yii\base\Request
} elseif (isset($_SERVER['PHP_SELF']) && ($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
$this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
} elseif (!empty($_SERVER['DOCUMENT_ROOT']) && strpos($scriptFile, $_SERVER['DOCUMENT_ROOT']) === 0) {
$this->_scriptUrl = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $scriptFile));
$this->_scriptUrl = str_replace([$_SERVER['DOCUMENT_ROOT'], '\\'], ['', '/'], $scriptFile);
} else {
throw new InvalidConfigException('Unable to determine the entry script URL.');
}
@ -1196,7 +1196,7 @@ class Request extends \yii\base\Request
* RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
*/
$auth_token = $this->getHeaders()->get('HTTP_AUTHORIZATION') ?: $this->getHeaders()->get('REDIRECT_HTTP_AUTHORIZATION');
if ($auth_token !== null && stripos($auth_token, 'basic') === 0) {
if ($auth_token !== null && strncasecmp($auth_token, 'basic', 5) === 0) {
$parts = array_map(function ($value) {
return strlen($value) === 0 ? null : $value;
}, explode(':', base64_decode(mb_substr($auth_token, 6)), 2));

11
framework/web/Response.php

@ -366,8 +366,7 @@ class Response extends \yii\base\Response
throw new HeadersAlreadySentException($file, $line);
}
if ($this->_headers) {
$headers = $this->getHeaders();
foreach ($headers as $name => $values) {
foreach ($this->getHeaders() as $name => $values) {
$name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
// set replace for first occurrence of header but false afterwards to allow multiple
$replace = true;
@ -767,7 +766,11 @@ class Response extends \yii\base\Response
*/
protected function getDispositionHeaderValue($disposition, $attachmentName)
{
$fallbackName = str_replace('"', '\\"', str_replace(['%', '/', '\\'], '_', Inflector::transliterate($attachmentName, Inflector::TRANSLITERATE_LOOSE)));
$fallbackName = str_replace(
['%', '/', '\\', '"'],
['_', '_', '_', '\\"'],
Inflector::transliterate($attachmentName, Inflector::TRANSLITERATE_LOOSE)
);
$utfName = rawurlencode(str_replace(['%', '/', '\\'], '', $attachmentName));
$dispositionHeader = "{$disposition}; filename=\"{$fallbackName}\"";
@ -841,7 +844,7 @@ class Response extends \yii\base\Response
$url[0] = '/' . ltrim($url[0], '/');
}
$url = Url::to($url);
if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) {
if (strncmp($url, '/', 1) === 0 && strncmp($url, '//', 2) !== 0) {
$url = Yii::$app->getRequest()->getHostInfo() . $url;
}

4
framework/web/UrlManager.php

@ -437,7 +437,7 @@ class UrlManager extends Component
}
return $url . $baseUrl . $anchor;
} elseif (strpos($url, '//') === 0) {
} elseif (strncmp($url, '//', 2) === 0) {
if ($baseUrl !== '' && ($pos = strpos($url, '/', 2)) !== false) {
return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
}
@ -546,7 +546,7 @@ class UrlManager extends Component
$url = $this->createUrl($params);
if (strpos($url, '://') === false) {
$hostInfo = $this->getHostInfo();
if (strpos($url, '//') === 0) {
if (strncmp($url, '//', 2) === 0) {
$url = substr($hostInfo, 0, strpos($hostInfo, '://')) . ':' . $url;
} else {
$url = $hostInfo . $url;

6
framework/web/UrlRule.php

@ -239,7 +239,7 @@ class UrlRule extends BaseObject implements UrlRuleInterface
} else {
$this->host = $this->pattern;
}
} elseif (strpos($this->pattern, '//') === 0) {
} elseif (strncmp($this->pattern, '//', 2) === 0) {
if (($pos2 = strpos($this->pattern, '/', 2)) !== false) {
$this->host = substr($this->pattern, 0, $pos2);
} else {
@ -336,7 +336,7 @@ class UrlRule extends BaseObject implements UrlRuleInterface
$this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
// if host starts with relative scheme, then insert pattern to match any
if (strpos($this->host, '//') === 0) {
if (strncmp($this->host, '//', 2) === 0) {
$this->pattern = substr_replace($this->pattern, '[\w]+://', 2, 0);
}
@ -593,7 +593,7 @@ class UrlRule extends BaseObject implements UrlRuleInterface
*/
private function trimSlashes($string)
{
if (strpos($string, '//') === 0) {
if (strncmp($string, '//', 2) === 0) {
return '//' . trim($string, '/');
}

Loading…
Cancel
Save