diff --git a/framework/BaseYii.php b/framework/BaseYii.php index cc1e6bfbed..6a69773fdb 100644 --- a/framework/BaseYii.php +++ b/framework/BaseYii.php @@ -68,7 +68,7 @@ class BaseYii */ public static $classMap = []; /** - * @var \yii\console\Application|\yii\web\Application the application instance + * @var \yii\console\Application|\yii\web\Application|\yii\base\Application the application instance */ public static $app; /** @@ -124,7 +124,7 @@ class BaseYii * @param string $alias the alias to be translated. * @param bool $throwException whether to throw an exception if the given alias is invalid. * If this is false and an invalid alias is given, false will be returned by this method. - * @return string|bool the path corresponding to the alias, false if the root alias is not previously registered. + * @return string|false the path corresponding to the alias, false if the root alias is not previously registered. * @throws InvalidArgumentException if the alias is invalid while $throwException is true. * @see setAlias() */ @@ -162,7 +162,7 @@ class BaseYii * A root alias is an alias that has been registered via [[setAlias()]] previously. * If a given alias matches multiple root aliases, the longest one will be returned. * @param string $alias the alias - * @return string|bool the root alias, or false if no root alias is found + * @return string|false the root alias, or false if no root alias is found */ public static function getRootAlias($alias) { diff --git a/framework/base/Controller.php b/framework/base/Controller.php index f2d655bac1..0c79060cef 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -514,6 +514,7 @@ class Controller extends Component implements ViewContextInterface public function findLayoutFile($view) { $module = $this->module; + $layout = null; if (is_string($this->layout)) { $layout = $this->layout; } elseif ($this->layout === null) { @@ -525,7 +526,7 @@ class Controller extends Component implements ViewContextInterface } } - if (!isset($layout)) { + if ($layout === null) { return false; } diff --git a/framework/base/Module.php b/framework/base/Module.php index fa84e553c7..2562f0ca1f 100644 --- a/framework/base/Module.php +++ b/framework/base/Module.php @@ -238,7 +238,7 @@ class Module extends ServiceLocator { $path = Yii::getAlias($path); $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath($path); - if ($p !== false && is_dir($p)) { + if (is_string($p) && is_dir($p)) { $this->_basePath = $p; } else { throw new InvalidArgumentException("The directory does not exist: $path"); diff --git a/framework/behaviors/AttributeTypecastBehavior.php b/framework/behaviors/AttributeTypecastBehavior.php index 1a4de29a5b..33520bde3b 100644 --- a/framework/behaviors/AttributeTypecastBehavior.php +++ b/framework/behaviors/AttributeTypecastBehavior.php @@ -132,7 +132,7 @@ class AttributeTypecastBehavior extends Behavior * 'price' => 'float', * 'is_active' => 'boolean', * 'date' => function ($value) { - * return ($value instanceof \DateTime) ? $value->getTimestamp(): (int)$value; + * return ($value instanceof \DateTime) ? $value->getTimestamp(): (int) $value; * }, * ] * ``` diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index 7c0aea4f2b..0d3f0de7d3 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -587,9 +587,7 @@ abstract class BaseMigrateController extends Controller */ public function actionNew($limit = 10) { - if ($limit === 'all') { - $limit = null; - } else { + if ($limit !== 'all') { $limit = (int) $limit; if ($limit < 1) { throw new Exception('The limit must be greater than 0.'); @@ -602,7 +600,7 @@ abstract class BaseMigrateController extends Controller $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN); } else { $n = count($migrations); - if ($limit && $n > $limit) { + if ($limit !== 'all' && $n > $limit) { $migrations = array_slice($migrations, 0, $limit); $this->stdout("Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW); } else { diff --git a/framework/console/controllers/CacheController.php b/framework/console/controllers/CacheController.php index b53fe73d19..8675c53410 100644 --- a/framework/console/controllers/CacheController.php +++ b/framework/console/controllers/CacheController.php @@ -84,11 +84,11 @@ class CacheController extends Controller $foundCaches = array_keys($caches); $notFoundCaches = array_diff($cachesInput, array_keys($caches)); - if ($notFoundCaches) { + if ($notFoundCaches !== []) { $this->notifyNotFoundCaches($notFoundCaches); } - if (!$foundCaches) { + if ($foundCaches === []) { $this->notifyNoCachesFound(); return ExitCode::OK; } diff --git a/framework/console/controllers/FixtureController.php b/framework/console/controllers/FixtureController.php index cce951f800..667c2a56bc 100644 --- a/framework/console/controllers/FixtureController.php +++ b/framework/console/controllers/FixtureController.php @@ -122,7 +122,7 @@ class FixtureController extends Controller $foundFixtures = $this->findFixtures($fixtures); $notFoundFixtures = array_diff($fixtures, $foundFixtures); - if ($notFoundFixtures) { + if ($notFoundFixtures !== []) { $this->notifyNotFound($notFoundFixtures); } } else { @@ -138,7 +138,7 @@ class FixtureController extends Controller ); } - if (!$fixturesToLoad) { + if ($fixturesToLoad === []) { $this->notifyNothingToLoad($foundFixtures, $except); return ExitCode::OK; } @@ -198,23 +198,23 @@ class FixtureController extends Controller $foundFixtures = $this->findFixtures($fixtures); $notFoundFixtures = array_diff($fixtures, $foundFixtures); - if ($notFoundFixtures) { + if ($notFoundFixtures !== []) { $this->notifyNotFound($notFoundFixtures); } } else { $foundFixtures = $this->findFixtures(); } - $fixturesToUnload = array_diff($foundFixtures, $except); - - if (!$foundFixtures) { + if ($foundFixtures === []) { throw new Exception( 'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" . "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".' ); } - if (!$fixturesToUnload) { + $fixturesToUnload = array_diff($foundFixtures, $except); + + if ($fixturesToUnload === []) { $this->notifyNothingToUnload($foundFixtures, $except); return ExitCode::OK; } @@ -225,7 +225,7 @@ class FixtureController extends Controller $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToUnload)); - if (!$fixtures) { + if ($fixtures === []) { throw new Exception('No fixtures were found in namespace: ' . $this->namespace . '".'); } diff --git a/framework/console/controllers/HelpController.php b/framework/console/controllers/HelpController.php index 5185f4e011..712fa76028 100644 --- a/framework/console/controllers/HelpController.php +++ b/framework/console/controllers/HelpController.php @@ -485,7 +485,7 @@ class HelpController extends Controller } if (is_bool($defaultValue)) { // show as integer to avoid confusion - $defaultValue = (int)$defaultValue; + $defaultValue = (int) $defaultValue; } if (is_string($defaultValue)) { $defaultValue = "'" . $defaultValue . "'"; diff --git a/framework/console/controllers/MigrateController.php b/framework/console/controllers/MigrateController.php index aa2625ea06..3f0efeaac1 100644 --- a/framework/console/controllers/MigrateController.php +++ b/framework/console/controllers/MigrateController.php @@ -301,11 +301,9 @@ class MigrateController extends BaseMigrateController // First drop all foreign keys, foreach ($schemas as $schema) { - if ($schema->foreignKeys) { - foreach ($schema->foreignKeys as $name => $foreignKey) { - $db->createCommand()->dropForeignKey($name, $schema->name)->execute(); - $this->stdout("Foreign key $name dropped.\n"); - } + foreach ($schema->foreignKeys as $name => $foreignKey) { + $db->createCommand()->dropForeignKey($name, $schema->name)->execute(); + $this->stdout("Foreign key $name dropped.\n"); } } @@ -580,10 +578,10 @@ class MigrateController extends BaseMigrateController */ protected function splitFieldIntoChunks($field) { - $hasDoubleQuotes = false; + $originalDefaultValue = null; + $defaultValue = null; preg_match_all('/defaultValue\(["\'].*?:?.*?["\']\)/', $field, $matches, PREG_SET_ORDER, 0); if (isset($matches[0][0])) { - $hasDoubleQuotes = true; $originalDefaultValue = $matches[0][0]; $defaultValue = str_replace(':', '{{colon}}', $originalDefaultValue); $field = str_replace($originalDefaultValue, $defaultValue, $field); @@ -591,7 +589,7 @@ class MigrateController extends BaseMigrateController $chunks = preg_split('/\s?:\s?/', $field); - if (is_array($chunks) && $hasDoubleQuotes) { + if (is_array($chunks) && $defaultValue !== null && $originalDefaultValue !== null) { foreach ($chunks as $key => $chunk) { $chunks[$key] = str_replace($defaultValue, $originalDefaultValue, $chunk); } diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php index 7a6d8b950a..d338b0e086 100644 --- a/framework/db/BaseActiveRecord.php +++ b/framework/db/BaseActiveRecord.php @@ -1294,6 +1294,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface */ public function link($name, $model, $extraColumns = []) { + /* @var $relation ActiveQueryInterface|ActiveQuery */ $relation = $this->getRelation($name); if ($relation->via !== null) { @@ -1330,16 +1331,16 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface $record->insert(false); } else { /* @var $viaTable string */ - static::getDb()->createCommand() - ->insert($viaTable, $columns)->execute(); + static::getDb()->createCommand()->insert($viaTable, $columns)->execute(); } } else { $p1 = $model->isPrimaryKey(array_keys($relation->link)); $p2 = static::isPrimaryKey(array_values($relation->link)); if ($p1 && $p2) { - if ($this->getIsNewRecord() && $model->getIsNewRecord()) { - throw new InvalidCallException('Unable to link models: at most one model can be newly created.'); - } elseif ($this->getIsNewRecord()) { + if ($this->getIsNewRecord()) { + if ($model->getIsNewRecord()) { + throw new InvalidCallException('Unable to link models: at most one model can be newly created.'); + } $this->bindModels(array_flip($relation->link), $this, $model); } else { $this->bindModels($relation->link, $model, $this); @@ -1492,6 +1493,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface */ public function unlinkAll($name, $delete = false) { + /* @var $relation ActiveQueryInterface|ActiveQuery */ $relation = $this->getRelation($name); if ($relation->via !== null) { diff --git a/framework/db/Connection.php b/framework/db/Connection.php index 391ef7f7f7..c31a8689f4 100644 --- a/framework/db/Connection.php +++ b/framework/db/Connection.php @@ -694,20 +694,24 @@ class Connection extends Component { $pdoClass = $this->pdoClass; if ($pdoClass === null) { - $pdoClass = 'PDO'; + $driver = null; if ($this->_driverName !== null) { $driver = $this->_driverName; } elseif (($pos = strpos($this->dsn, ':')) !== false) { $driver = strtolower(substr($this->dsn, 0, $pos)); } - if (isset($driver)) { - if ($driver === 'mssql') { + switch ($driver) { + case 'mssql': $pdoClass = 'yii\db\mssql\PDO'; - } elseif ($driver === 'dblib') { + break; + case 'dblib': $pdoClass = 'yii\db\mssql\DBLibPDO'; - } elseif ($driver === 'sqlsrv') { + break; + case 'sqlsrv': $pdoClass = 'yii\db\mssql\SqlsrvPDO'; - } + break; + default: + $pdoClass = 'PDO'; } } diff --git a/framework/db/conditions/InConditionBuilder.php b/framework/db/conditions/InConditionBuilder.php index f685216c11..dd238b7a7c 100644 --- a/framework/db/conditions/InConditionBuilder.php +++ b/framework/db/conditions/InConditionBuilder.php @@ -54,18 +54,16 @@ class InConditionBuilder implements ExpressionBuilderInterface if (is_array($column)) { if (count($column) > 1) { return $this->buildCompositeInCondition($operator, $column, $values, $params); - } else { - $column = reset($column); } + $column = reset($column); } if ($column instanceof \Traversable) { if (iterator_count($column) > 1) { return $this->buildCompositeInCondition($operator, $column, $values, $params); - } else { - $column->rewind(); - $column = $column->current(); } + $column->rewind(); + $column = $column->current(); } if (is_array($values)) { @@ -74,6 +72,8 @@ class InConditionBuilder implements ExpressionBuilderInterface $rawValues = $this->getRawValuesFromTraversableObject($values); } + $nullCondition = null; + $nullConditionOperator = null; if (isset($rawValues) && in_array(null, $rawValues, true)) { $nullCondition = $this->getNullCondition($operator, $column); $nullConditionOperator = $operator === 'IN' ? 'OR' : 'AND'; @@ -81,7 +81,7 @@ class InConditionBuilder implements ExpressionBuilderInterface $sqlValues = $this->buildValues($expression, $values, $params); if (empty($sqlValues)) { - if (!isset($nullCondition)) { + if ($nullCondition === null) { return $operator === 'IN' ? '0=1' : ''; } return $nullCondition; @@ -97,7 +97,9 @@ class InConditionBuilder implements ExpressionBuilderInterface $sql = $column . $operator . reset($sqlValues); } - return isset($nullCondition) ? sprintf('%s %s %s', $sql, $nullConditionOperator, $nullCondition) : $sql; + return $nullCondition !== null && $nullConditionOperator !== null + ? sprintf('%s %s %s', $sql, $nullConditionOperator, $nullCondition) + : $sql; } /** diff --git a/framework/db/mssql/QueryBuilder.php b/framework/db/mssql/QueryBuilder.php index 8e250a5af0..6b6c89c976 100644 --- a/framework/db/mssql/QueryBuilder.php +++ b/framework/db/mssql/QueryBuilder.php @@ -11,6 +11,7 @@ use yii\base\InvalidArgumentException; use yii\base\NotSupportedException; use yii\db\Constraint; use yii\db\Expression; +use yii\db\TableSchema; /** * QueryBuilder is the query builder for MS SQL Server databases (version 2008 and above). @@ -483,10 +484,11 @@ class QueryBuilder extends \yii\db\QueryBuilder $version2005orLater = version_compare($this->db->getSchema()->getServerVersion(), '9', '>='); list($names, $placeholders, $values, $params) = $this->prepareInsertValues($table, $columns, $params); + $cols = []; + $columns = []; if ($version2005orLater) { + /* @var $schema TableSchema */ $schema = $this->db->getTableSchema($table); - $cols = []; - $columns = []; foreach ($schema->columns as $column) { if ($column->isComputed) { continue; diff --git a/framework/db/mssql/Schema.php b/framework/db/mssql/Schema.php index a2ad449c63..cb451e68d1 100644 --- a/framework/db/mssql/Schema.php +++ b/framework/db/mssql/Schema.php @@ -394,9 +394,9 @@ SQL; } if (!empty($matches[2])) { $values = explode(',', $matches[2]); - $column->size = $column->precision = (int)$values[0]; + $column->size = $column->precision = (int) $values[0]; if (isset($values[1])) { - $column->scale = (int)$values[1]; + $column->scale = (int) $values[1]; } if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) { $column->type = 'boolean'; diff --git a/framework/db/pgsql/Schema.php b/framework/db/pgsql/Schema.php index 5959b1bf98..8f0f1e7d42 100644 --- a/framework/db/pgsql/Schema.php +++ b/framework/db/pgsql/Schema.php @@ -607,7 +607,7 @@ SQL; $column->precision = $info['numeric_precision']; $column->scale = $info['numeric_scale']; $column->size = $info['size'] === null ? null : (int) $info['size']; - $column->dimension = (int)$info['dimension']; + $column->dimension = (int) $info['dimension']; // pg_get_serial_sequence() doesn't track DEFAULT value change. GENERATED BY IDENTITY columns always have null default value if (isset($column->defaultValue) && preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $column->defaultValue) === 1) { $column->sequenceName = preg_replace(['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'], '', $column->defaultValue); diff --git a/framework/filters/AccessRule.php b/framework/filters/AccessRule.php index 606c170102..aece5ccf68 100644 --- a/framework/filters/AccessRule.php +++ b/framework/filters/AccessRule.php @@ -66,10 +66,10 @@ class AccessRule extends Component * @see $roleParams */ public $roles; - /** + /** * @var array list of RBAC (Role-Based Access Control) permissions that this rules applies to. * [[User::can()]] will be called to check access. - * + * * If this property is not set or empty, it means this rule applies regardless of permissions. * @since 2.0.12 * @see $roles @@ -264,16 +264,17 @@ class AccessRule extends Component return true; } foreach ($this->ips as $rule) { - if ($rule === '*' || - $rule === $ip || - ( - $ip !== null && - ($pos = strpos($rule, '*')) !== false && - strncmp($ip, $rule, $pos) === 0 - ) || - ( - ($pos = strpos($rule, '/')) !== false && - IpHelper::inRange($ip, $rule) === true + if ( + $rule === '*' + || $rule === $ip + || ( + $ip !== null + && ($pos = strpos($rule, '*')) !== false + && strncmp($ip, $rule, $pos) === 0 + ) + || ( + strpos($rule, '/') !== false + && IpHelper::inRange($ip, $rule) === true ) ) { return true; diff --git a/framework/helpers/BaseFileHelper.php b/framework/helpers/BaseFileHelper.php index 678eff592b..b1bf1c19e5 100644 --- a/framework/helpers/BaseFileHelper.php +++ b/framework/helpers/BaseFileHelper.php @@ -596,19 +596,15 @@ class BaseFileHelper $path = str_replace('\\', '/', $path); - if (!empty($options['except'])) { - if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null) { - return $except['flags'] & self::PATTERN_NEGATIVE; - } + if ( + !empty($options['except']) + && ($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null + ) { + return $except['flags'] & self::PATTERN_NEGATIVE; } if (!empty($options['only']) && !is_dir($path)) { - if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only'])) !== null) { - // don't check PATTERN_NEGATIVE since those entries are not prefixed with ! - return true; - } - - return false; + return self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only']) !== null; } return true; diff --git a/framework/log/Logger.php b/framework/log/Logger.php index 76e993d306..5081164859 100644 --- a/framework/log/Logger.php +++ b/framework/log/Logger.php @@ -218,11 +218,15 @@ class Logger extends Component return $timings; } - foreach ($timings as $i => $timing) { + foreach ($timings as $outerIndex => $outerTimingItem) { + $currentIndex = $outerIndex; $matched = empty($categories); foreach ($categories as $category) { $prefix = rtrim($category, '*'); - if (($timing['category'] === $category || $prefix !== $category) && strpos($timing['category'], $prefix) === 0) { + if ( + ($outerTimingItem['category'] === $category || $prefix !== $category) + && strpos($outerTimingItem['category'], $prefix) === 0 + ) { $matched = true; break; } @@ -231,8 +235,12 @@ class Logger extends Component if ($matched) { foreach ($excludeCategories as $category) { $prefix = rtrim($category, '*'); - foreach ($timings as $i => $timing) { - if (($timing['category'] === $category || $prefix !== $category) && strpos($timing['category'], $prefix) === 0) { + foreach ($timings as $innerIndex => $innerTimingItem) { + $currentIndex = $innerIndex; + if ( + ($innerTimingItem['category'] === $category || $prefix !== $category) + && strpos($innerTimingItem['category'], $prefix) === 0 + ) { $matched = false; break; } @@ -241,7 +249,7 @@ class Logger extends Component } if (!$matched) { - unset($timings[$i]); + unset($timings[$currentIndex]); } } diff --git a/framework/web/MultipartFormDataParser.php b/framework/web/MultipartFormDataParser.php index c6f8c8ccaa..9cfac9b199 100644 --- a/framework/web/MultipartFormDataParser.php +++ b/framework/web/MultipartFormDataParser.php @@ -109,7 +109,7 @@ class MultipartFormDataParser extends BaseObject implements RequestParserInterfa public function getUploadFileMaxCount() { if ($this->_uploadFileMaxCount === null) { - $this->_uploadFileMaxCount = ini_get('max_file_uploads'); + $this->_uploadFileMaxCount = (int)ini_get('max_file_uploads'); } return $this->_uploadFileMaxCount; diff --git a/framework/web/Session.php b/framework/web/Session.php index 03d4ece7c6..a7de39f182 100644 --- a/framework/web/Session.php +++ b/framework/web/Session.php @@ -105,7 +105,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co */ private $_cookieParams = ['httponly' => true]; /** - * @var $frozenSessionData array|null is used for saving session between recreations due to session parameters update. + * @var array|null is used for saving session between recreations due to session parameters update. */ private $frozenSessionData; diff --git a/tests/framework/db/CommandTest.php b/tests/framework/db/CommandTest.php index 526ee5c4c9..ec88e98dcb 100644 --- a/tests/framework/db/CommandTest.php +++ b/tests/framework/db/CommandTest.php @@ -221,7 +221,7 @@ SQL; } $this->assertEquals($numericCol, $row['numeric_col']); if ($this->driverName === 'mysql' || $this->driverName === 'oci' || (\defined('HHVM_VERSION') && \in_array($this->driverName, ['sqlite', 'pgsql']))) { - $this->assertEquals($boolCol, (int)$row['bool_col']); + $this->assertEquals($boolCol, (int) $row['bool_col']); } else { $this->assertEquals($boolCol, $row['bool_col']); } diff --git a/tests/framework/db/QueryTest.php b/tests/framework/db/QueryTest.php index 18179085e4..ac7df07ea3 100644 --- a/tests/framework/db/QueryTest.php +++ b/tests/framework/db/QueryTest.php @@ -606,7 +606,7 @@ abstract class QueryTest extends DatabaseTestCase ->where($whereCondition) ->count('*', $db); if (is_numeric($result)) { - $result = (int)$result; + $result = (int) $result; } return $result;