Browse Source

Enable `no_useless_else` rule in php-cs-fixer (#14420)

tags/2.0.13
Robert Korulczyk 7 years ago committed by Alexander Makarov
parent
commit
fe8a0a6a2e
  1. 4
      build/controllers/Utf8Controller.php
  2. 2
      cs/src/YiiConfig.php
  3. 4
      framework/base/Action.php
  4. 4
      framework/base/Application.php
  5. 8
      framework/base/DynamicModel.php
  6. 8
      framework/base/Object.php
  7. 8
      framework/base/Theme.php
  8. 6
      framework/base/Widget.php
  9. 4
      framework/caching/Cache.php
  10. 8
      framework/caching/FileCache.php
  11. 4
      framework/caching/MemCache.php
  12. 9
      framework/captcha/CaptchaAction.php
  13. 8
      framework/console/Application.php
  14. 8
      framework/console/controllers/AssetController.php
  15. 12
      framework/console/controllers/BaseMigrateController.php
  16. 4
      framework/console/controllers/HelpController.php
  17. 4
      framework/console/controllers/MigrateController.php
  18. 4
      framework/data/ActiveDataProvider.php
  19. 4
      framework/data/ArrayDataProvider.php
  20. 8
      framework/data/Pagination.php
  21. 4
      framework/data/Sort.php
  22. 11
      framework/db/ActiveQuery.php
  23. 4
      framework/db/ActiveRelationTrait.php
  24. 47
      framework/db/BaseActiveRecord.php
  25. 4
      framework/db/ColumnSchemaBuilder.php
  26. 8
      framework/db/Command.php
  27. 20
      framework/db/Connection.php
  28. 7
      framework/db/Query.php
  29. 30
      framework/db/QueryBuilder.php
  30. 5
      framework/db/QueryTrait.php
  31. 22
      framework/db/Schema.php
  32. 4
      framework/db/cubrid/QueryBuilder.php
  33. 8
      framework/db/mssql/QueryBuilder.php
  34. 4
      framework/db/mysql/QueryBuilder.php
  35. 4
      framework/db/pgsql/QueryBuilder.php
  36. 4
      framework/db/sqlite/QueryBuilder.php
  37. 18
      framework/di/Container.php
  38. 12
      framework/di/Instance.php
  39. 16
      framework/di/ServiceLocator.php
  40. 4
      framework/filters/ContentNegotiator.php
  41. 4
      framework/filters/HttpCache.php
  42. 4
      framework/filters/PageCache.php
  43. 4
      framework/filters/RateLimiter.php
  44. 5
      framework/filters/auth/AuthMethod.php
  45. 8
      framework/grid/ActionColumn.php
  46. 4
      framework/grid/CheckboxColumn.php
  47. 4
      framework/grid/Column.php
  48. 18
      framework/grid/DataColumn.php
  49. 20
      framework/grid/GridView.php
  50. 4
      framework/grid/SerialColumn.php
  51. 27
      framework/helpers/BaseArrayHelper.php
  52. 8
      framework/helpers/BaseFileHelper.php
  53. 28
      framework/helpers/BaseHtml.php
  54. 8
      framework/helpers/BaseInflector.php
  55. 20
      framework/helpers/BaseStringHelper.php
  56. 12
      framework/helpers/BaseUrl.php
  57. 4
      framework/i18n/DbMessageSource.php
  58. 60
      framework/i18n/Formatter.php
  59. 4
      framework/i18n/GettextMessageSource.php
  60. 4
      framework/i18n/GettextMoFile.php
  61. 22
      framework/i18n/I18N.php
  62. 8
      framework/i18n/MessageFormatter.php
  63. 4
      framework/i18n/MessageSource.php
  64. 4
      framework/i18n/PhpMessageSource.php
  65. 4
      framework/mail/BaseMailer.php
  66. 4
      framework/mutex/FileMutex.php
  67. 8
      framework/mutex/Mutex.php
  68. 16
      framework/rbac/BaseManager.php
  69. 4
      framework/rbac/DbManager.php
  70. 37
      framework/rbac/PhpManager.php
  71. 4
      framework/rest/Action.php
  72. 16
      framework/rest/Serializer.php
  73. 4
      framework/test/ActiveFixture.php
  74. 4
      framework/test/ArrayFixture.php
  75. 4
      framework/test/BaseActiveFixture.php
  76. 4
      framework/validators/CompareValidator.php
  77. 9
      framework/validators/DateValidator.php
  78. 8
      framework/validators/EachValidator.php
  79. 4
      framework/validators/ExistValidator.php
  80. 4
      framework/validators/InlineValidator.php
  81. 9
      framework/validators/IpValidator.php
  82. 4
      framework/validators/NumberValidator.php
  83. 4
      framework/validators/RequiredValidator.php
  84. 4
      framework/validators/Validator.php
  85. 10
      framework/web/Application.php
  86. 28
      framework/web/AssetManager.php
  87. 8
      framework/web/ErrorHandler.php
  88. 8
      framework/web/GroupUrlRule.php
  89. 8
      framework/web/HeaderCollection.php
  90. 4
      framework/web/HttpException.php
  91. 4
      framework/web/MultiFieldSession.php
  92. 4
      framework/web/Response.php
  93. 12
      framework/web/Session.php
  94. 20
      framework/web/UrlManager.php
  95. 8
      framework/web/UrlRule.php
  96. 8
      framework/web/User.php
  97. 8
      framework/web/ViewAction.php
  98. 4
      framework/widgets/ActiveForm.php
  99. 4
      framework/widgets/DetailView.php
  100. 4
      framework/widgets/Menu.php
  101. Some files were not shown because too many files have changed in this diff Show More

4
build/controllers/Utf8Controller.php

@ -119,8 +119,8 @@ class Utf8Controller extends Controller
return ($h & 0x0F) << 18 | (ord($c[1]) & 0x3F) << 12 return ($h & 0x0F) << 18 | (ord($c[1]) & 0x3F) << 12
| (ord($c[2]) & 0x3F) << 6 | (ord($c[2]) & 0x3F) << 6
| (ord($c[3]) & 0x3F); | (ord($c[3]) & 0x3F);
} else {
return false;
} }
return false;
} }
} }

2
cs/src/YiiConfig.php

@ -91,7 +91,7 @@ class YiiConfig extends Config
'no_trailing_comma_in_singleline_array' => true, 'no_trailing_comma_in_singleline_array' => true,
'no_unneeded_control_parentheses' => true, 'no_unneeded_control_parentheses' => true,
'no_unused_imports' => true, 'no_unused_imports' => true,
// 'no_useless_else' => true, // needs more discussion 'no_useless_else' => true,
'no_useless_return' => true, 'no_useless_return' => true,
'no_whitespace_before_comma_in_array' => true, 'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true, 'no_whitespace_in_blank_line' => true,

4
framework/base/Action.php

@ -95,9 +95,9 @@ class Action extends Component
$this->afterRun(); $this->afterRun();
return $result; return $result;
} else {
return null;
} }
return null;
} }
/** /**

4
framework/base/Application.php

@ -651,9 +651,9 @@ abstract class Application extends Module
if (YII_ENV_TEST) { if (YII_ENV_TEST) {
throw new ExitException($status); throw new ExitException($status);
} else {
exit($status);
} }
exit($status);
} }
/** /**

8
framework/base/DynamicModel.php

@ -82,9 +82,9 @@ class DynamicModel extends Model
{ {
if (array_key_exists($name, $this->_attributes)) { if (array_key_exists($name, $this->_attributes)) {
return $this->_attributes[$name]; return $this->_attributes[$name];
} else {
return parent::__get($name);
} }
return parent::__get($name);
} }
/** /**
@ -106,9 +106,9 @@ class DynamicModel extends Model
{ {
if (array_key_exists($name, $this->_attributes)) { if (array_key_exists($name, $this->_attributes)) {
return isset($this->_attributes[$name]); return isset($this->_attributes[$name]);
} else {
return parent::__isset($name);
} }
return parent::__isset($name);
} }
/** /**

8
framework/base/Object.php

@ -134,9 +134,9 @@ class Object implements Configurable
return $this->$getter(); return $this->$getter();
} elseif (method_exists($this, 'set' . $name)) { } elseif (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name); throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
} }
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
} }
/** /**
@ -178,9 +178,9 @@ class Object implements Configurable
$getter = 'get' . $name; $getter = 'get' . $name;
if (method_exists($this, $getter)) { if (method_exists($this, $getter)) {
return $this->$getter() !== null; return $this->$getter() !== null;
} else {
return false;
} }
return false;
} }
/** /**

8
framework/base/Theme.php

@ -166,9 +166,9 @@ class Theme extends Component
{ {
if (($baseUrl = $this->getBaseUrl()) !== null) { if (($baseUrl = $this->getBaseUrl()) !== null) {
return $baseUrl . '/' . ltrim($url, '/'); return $baseUrl . '/' . ltrim($url, '/');
} else {
throw new InvalidConfigException('The "baseUrl" property must be set.');
} }
throw new InvalidConfigException('The "baseUrl" property must be set.');
} }
/** /**
@ -181,8 +181,8 @@ class Theme extends Component
{ {
if (($basePath = $this->getBasePath()) !== null) { if (($basePath = $this->getBasePath()) !== null) {
return $basePath . DIRECTORY_SEPARATOR . ltrim($path, '/\\'); return $basePath . DIRECTORY_SEPARATOR . ltrim($path, '/\\');
} else {
throw new InvalidConfigException('The "basePath" property must be set.');
} }
throw new InvalidConfigException('The "basePath" property must be set.');
} }
} }

6
framework/base/Widget.php

@ -111,13 +111,13 @@ class Widget extends Component implements ViewContextInterface
echo $result; echo $result;
} }
return $widget; return $widget;
} else { }
throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class()); throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());
} }
} else {
throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.'); throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');
} }
}
/** /**
* Creates a widget instance and runs it. * Creates a widget instance and runs it.

4
framework/caching/Cache.php

@ -121,9 +121,9 @@ abstract class Cache extends Component implements CacheInterface
} }
if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) { if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
return $value[0]; return $value[0];
} else {
return false;
} }
return false;
} }
/** /**

8
framework/caching/FileCache.php

@ -150,12 +150,12 @@ class FileCache extends Cache
} }
return @touch($cacheFile, $duration + time()); return @touch($cacheFile, $duration + time());
} else { }
$error = error_get_last(); $error = error_get_last();
Yii::warning("Unable to write cache file '{$cacheFile}': {$error['message']}", __METHOD__); Yii::warning("Unable to write cache file '{$cacheFile}': {$error['message']}", __METHOD__);
return false; return false;
} }
}
/** /**
* Stores a value identified by a key into cache if the cache does not contain this key. * Stores a value identified by a key into cache if the cache does not contain this key.
@ -206,9 +206,9 @@ class FileCache extends Cache
} }
return $base . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix; return $base . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
} else {
return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
} }
return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
} }
/** /**

4
framework/caching/MemCache.php

@ -317,9 +317,9 @@ class MemCache extends Cache
// Memcached::setMulti() returns boolean // Memcached::setMulti() returns boolean
// @see http://php.net/manual/en/memcached.setmulti.php // @see http://php.net/manual/en/memcached.setmulti.php
return $this->_cache->setMulti($data, $expire) ? [] : array_keys($data); return $this->_cache->setMulti($data, $expire) ? [] : array_keys($data);
} else {
return parent::setValues($data, $duration);
} }
return parent::setValues($data, $duration);
} }
/** /**

9
framework/captcha/CaptchaAction.php

@ -134,12 +134,13 @@ class CaptchaAction extends Action
// when src attribute of image tag is changed // when src attribute of image tag is changed
'url' => Url::to([$this->id, 'v' => uniqid()]), 'url' => Url::to([$this->id, 'v' => uniqid()]),
]; ];
} else { }
$this->setHttpHeaders(); $this->setHttpHeaders();
Yii::$app->response->format = Response::FORMAT_RAW; Yii::$app->response->format = Response::FORMAT_RAW;
return $this->renderImage($this->getVerifyCode()); return $this->renderImage($this->getVerifyCode());
} }
}
/** /**
* Generates a hash code that can be used for client-side validation. * Generates a hash code that can be used for client-side validation.
@ -255,9 +256,9 @@ class CaptchaAction extends Action
return $this->renderImageByGD($code); return $this->renderImageByGD($code);
} elseif ($imageLibrary === 'imagick') { } elseif ($imageLibrary === 'imagick') {
return $this->renderImageByImagick($code); return $this->renderImageByImagick($code);
} else {
throw new InvalidConfigException("Defined library '{$imageLibrary}' is not supported");
} }
throw new InvalidConfigException("Defined library '{$imageLibrary}' is not supported");
} }
/** /**

8
framework/console/Application.php

@ -106,9 +106,9 @@ class Application extends \yii\base\Application
$path = substr($param, strlen($option)); $path = substr($param, strlen($option));
if (!empty($path) && is_file($file = Yii::getAlias($path))) { if (!empty($path) && is_file($file = Yii::getAlias($path))) {
return require($file); return require($file);
} else {
exit("The configuration file does not exist: $path\n");
} }
exit("The configuration file does not exist: $path\n");
} }
} }
} }
@ -147,13 +147,13 @@ class Application extends \yii\base\Application
$result = $this->runAction($route, $params); $result = $this->runAction($route, $params);
if ($result instanceof Response) { if ($result instanceof Response) {
return $result; return $result;
} else { }
$response = $this->getResponse(); $response = $this->getResponse();
$response->exitStatus = $result; $response->exitStatus = $result;
return $response; return $response;
} }
}
/** /**
* Runs a controller action specified by a route. * Runs a controller action specified by a route.

8
framework/console/controllers/AssetController.php

@ -320,9 +320,9 @@ class AssetController extends Controller
usort($target['depends'], function ($a, $b) use ($bundleOrders) { usort($target['depends'], function ($a, $b) use ($bundleOrders) {
if ($bundleOrders[$a] == $bundleOrders[$b]) { if ($bundleOrders[$a] == $bundleOrders[$b]) {
return 0; return 0;
} else {
return $bundleOrders[$a] > $bundleOrders[$b] ? 1 : -1;
} }
return $bundleOrders[$a] > $bundleOrders[$b] ? 1 : -1;
}); });
if (!isset($target['class'])) { if (!isset($target['class'])) {
$target['class'] = $name; $target['class'] = $name;
@ -732,11 +732,11 @@ EOD;
} }
if (!file_put_contents($configFile, $template)) { if (!file_put_contents($configFile, $template)) {
throw new Exception("Unable to write template file '{$configFile}'."); throw new Exception("Unable to write template file '{$configFile}'.");
} else { }
$this->stdout("Configuration file template created at '{$configFile}'.\n\n", Console::FG_GREEN); $this->stdout("Configuration file template created at '{$configFile}'.\n\n", Console::FG_GREEN);
return self::EXIT_CODE_NORMAL; return self::EXIT_CODE_NORMAL;
} }
}
/** /**
* Returns canonicalized absolute pathname. * Returns canonicalized absolute pathname.

12
framework/console/controllers/BaseMigrateController.php

@ -130,9 +130,9 @@ abstract class BaseMigrateController extends Controller
$this->stdout("Yii Migration Tool (based on Yii v{$version})\n\n"); $this->stdout("Yii Migration Tool (based on Yii v{$version})\n\n");
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@ -673,13 +673,13 @@ abstract class BaseMigrateController extends Controller
$this->stdout("*** applied $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN); $this->stdout("*** applied $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
return true; return true;
} else { }
$time = microtime(true) - $start; $time = microtime(true) - $start;
$this->stdout("*** failed to apply $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED); $this->stdout("*** failed to apply $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
return false; return false;
} }
}
/** /**
* Downgrades with the specified migration class. * Downgrades with the specified migration class.
@ -701,13 +701,13 @@ abstract class BaseMigrateController extends Controller
$this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN); $this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
return true; return true;
} else { }
$time = microtime(true) - $start; $time = microtime(true) - $start;
$this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED); $this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
return false; return false;
} }
}
/** /**
* Creates a new migration instance. * Creates a new migration instance.

4
framework/console/controllers/HelpController.php

@ -273,9 +273,9 @@ class HelpController extends Controller
if (class_exists($controllerClass)) { if (class_exists($controllerClass)) {
$class = new \ReflectionClass($controllerClass); $class = new \ReflectionClass($controllerClass);
return !$class->isAbstract() && $class->isSubclassOf('yii\console\Controller'); return !$class->isAbstract() && $class->isSubclassOf('yii\console\Controller');
} else {
return false;
} }
return false;
} }
/** /**

4
framework/console/controllers/MigrateController.php

@ -170,9 +170,9 @@ class MigrateController extends BaseMigrateController
$this->db = Instance::ensure($this->db, Connection::className()); $this->db = Instance::ensure($this->db, Connection::className());
} }
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**

4
framework/data/ActiveDataProvider.php

@ -152,9 +152,9 @@ class ActiveDataProvider extends BaseDataProvider
} }
return $keys; return $keys;
} else {
return array_keys($models);
} }
return array_keys($models);
} }
/** /**

4
framework/data/ArrayDataProvider.php

@ -113,9 +113,9 @@ class ArrayDataProvider extends BaseDataProvider
} }
return $keys; return $keys;
} else {
return array_keys($models);
} }
return array_keys($models);
} }
/** /**

8
framework/data/Pagination.php

@ -153,12 +153,12 @@ class Pagination extends Object implements Linkable
$pageSize = $this->getPageSize(); $pageSize = $this->getPageSize();
if ($pageSize < 1) { if ($pageSize < 1) {
return $this->totalCount > 0 ? 1 : 0; return $this->totalCount > 0 ? 1 : 0;
} else { }
$totalCount = $this->totalCount < 0 ? 0 : (int) $this->totalCount; $totalCount = $this->totalCount < 0 ? 0 : (int) $this->totalCount;
return (int) (($totalCount + $pageSize - 1) / $pageSize); return (int) (($totalCount + $pageSize - 1) / $pageSize);
} }
}
private $_page; private $_page;
@ -281,9 +281,9 @@ class Pagination extends Object implements Linkable
$urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager; $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
if ($absolute) { if ($absolute) {
return $urlManager->createAbsoluteUrl($params); return $urlManager->createAbsoluteUrl($params);
} else {
return $urlManager->createUrl($params);
} }
return $urlManager->createUrl($params);
} }
/** /**

4
framework/data/Sort.php

@ -412,9 +412,9 @@ class Sort extends Object
$urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager; $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
if ($absolute) { if ($absolute) {
return $urlManager->createAbsoluteUrl($params); return $urlManager->createAbsoluteUrl($params);
} else {
return $urlManager->createUrl($params);
} }
return $urlManager->createUrl($params);
} }
/** /**

11
framework/db/ActiveQuery.php

@ -295,9 +295,9 @@ class ActiveQuery extends Query implements ActiveQueryInterface
if ($row !== false) { if ($row !== false) {
$models = $this->populate([$row]); $models = $this->populate([$row]);
return reset($models) ?: null; return reset($models) ?: null;
} else {
return null;
} }
return null;
} }
/** /**
@ -545,9 +545,9 @@ class ActiveQuery extends Query implements ActiveQueryInterface
{ {
if (is_array($joinType) && isset($joinType[$name])) { if (is_array($joinType) && isset($joinType[$name])) {
return $joinType[$name]; return $joinType[$name];
} else {
return is_string($joinType) ? $joinType : 'INNER JOIN';
} }
return is_string($joinType) ? $joinType : 'INNER JOIN';
} }
/** /**
@ -564,9 +564,8 @@ class ActiveQuery extends Query implements ActiveQueryInterface
foreach ($this->from as $alias => $tableName) { foreach ($this->from as $alias => $tableName) {
if (is_string($alias)) { if (is_string($alias)) {
return [$tableName, $alias]; return [$tableName, $alias];
} else {
break;
} }
break;
} }
} }

4
framework/db/ActiveRelationTrait.php

@ -232,7 +232,8 @@ trait ActiveRelationTrait
} }
return [$model]; return [$model];
} else { }
// https://github.com/yiisoft/yii2/issues/3197 // https://github.com/yiisoft/yii2/issues/3197
// delay indexing related models after buckets are built // delay indexing related models after buckets are built
$indexBy = $this->indexBy; $indexBy = $this->indexBy;
@ -283,7 +284,6 @@ trait ActiveRelationTrait
return $models; return $models;
} }
}
/** /**
* @param ActiveRecordInterface[] $primaryModels primary models * @param ActiveRecordInterface[] $primaryModels primary models

47
framework/db/BaseActiveRecord.php

@ -278,17 +278,17 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
return $this->_attributes[$name]; return $this->_attributes[$name];
} elseif ($this->hasAttribute($name)) { } elseif ($this->hasAttribute($name)) {
return null; return null;
} else { }
if (isset($this->_related[$name]) || array_key_exists($name, $this->_related)) { if (isset($this->_related[$name]) || array_key_exists($name, $this->_related)) {
return $this->_related[$name]; return $this->_related[$name];
} }
$value = parent::__get($name); $value = parent::__get($name);
if ($value instanceof ActiveQueryInterface) { if ($value instanceof ActiveQueryInterface) {
return $this->_related[$name] = $value->findFor($name, $this); return $this->_related[$name] = $value->findFor($name, $this);
} else {
return $value;
}
} }
return $value;
} }
/** /**
@ -575,13 +575,13 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) { if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
if ($identical) { if ($identical) {
return $this->_attributes[$name] !== $this->_oldAttributes[$name]; return $this->_attributes[$name] !== $this->_oldAttributes[$name];
} else { }
return $this->_attributes[$name] != $this->_oldAttributes[$name]; return $this->_attributes[$name] != $this->_oldAttributes[$name];
} }
} else {
return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]); return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
} }
}
/** /**
* Returns the attribute values that have been modified since they are loaded or saved most recently. * Returns the attribute values that have been modified since they are loaded or saved most recently.
@ -641,9 +641,9 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
{ {
if ($this->getIsNewRecord()) { if ($this->getIsNewRecord()) {
return $this->insert($runValidation, $attributeNames); return $this->insert($runValidation, $attributeNames);
} else {
return $this->update($runValidation, $attributeNames) !== false;
} }
return $this->update($runValidation, $attributeNames) !== false;
} }
/** /**
@ -819,10 +819,11 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
} }
$this->_oldAttributes[$name] = $this->_attributes[$name]; $this->_oldAttributes[$name] = $this->_attributes[$name];
} }
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@ -1074,7 +1075,8 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
$keys = $this->primaryKey(); $keys = $this->primaryKey();
if (!$asArray && count($keys) === 1) { if (!$asArray && count($keys) === 1) {
return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null; return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
} else { }
$values = []; $values = [];
foreach ($keys as $name) { foreach ($keys as $name) {
$values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null; $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
@ -1082,7 +1084,6 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
return $values; return $values;
} }
}
/** /**
* Returns the old primary key value(s). * Returns the old primary key value(s).
@ -1108,7 +1109,8 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
} }
if (!$asArray && count($keys) === 1) { if (!$asArray && count($keys) === 1) {
return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null; return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
} else { }
$values = []; $values = [];
foreach ($keys as $name) { foreach ($keys as $name) {
$values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null; $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
@ -1116,7 +1118,6 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
return $values; return $values;
} }
}
/** /**
* Populates an active record object using a row of data from the database/storage. * Populates an active record object using a row of data from the database/storage.
@ -1193,16 +1194,16 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
} catch (UnknownMethodException $e) { } catch (UnknownMethodException $e) {
if ($throwException) { if ($throwException) {
throw new InvalidParamException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e); throw new InvalidParamException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
} else {
return null;
} }
return null;
} }
if (!$relation instanceof ActiveQueryInterface) { if (!$relation instanceof ActiveQueryInterface) {
if ($throwException) { if ($throwException) {
throw new InvalidParamException(get_class($this) . ' has no relation named "' . $name . '".'); throw new InvalidParamException(get_class($this) . ' has no relation named "' . $name . '".');
} else {
return null;
} }
return null;
} }
if (method_exists($this, $getter)) { if (method_exists($this, $getter)) {
@ -1212,9 +1213,9 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
if ($realName !== $name) { if ($realName !== $name) {
if ($throwException) { if ($throwException) {
throw new InvalidParamException('Relation names are case sensitive. ' . get_class($this) . " has a relation named \"$realName\" instead of \"$name\"."); throw new InvalidParamException('Relation names are case sensitive. ' . get_class($this) . " has a relation named \"$realName\" instead of \"$name\".");
} else {
return null;
} }
return null;
} }
} }
@ -1538,9 +1539,9 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
$pks = static::primaryKey(); $pks = static::primaryKey();
if (count($keys) === count($pks)) { if (count($keys) === count($pks)) {
return count(array_intersect($keys, $pks)) === count($pks); return count(array_intersect($keys, $pks)) === count($pks);
} else {
return false;
} }
return false;
} }
/** /**

4
framework/db/ColumnSchemaBuilder.php

@ -312,9 +312,9 @@ class ColumnSchemaBuilder extends Object
return ' NOT NULL'; return ' NOT NULL';
} elseif ($this->isNotNull === false) { } elseif ($this->isNotNull === false) {
return ' NULL'; return ' NULL';
} else {
return '';
} }
return '';
} }
/** /**

8
framework/db/Command.php

@ -388,9 +388,9 @@ class Command extends Component
$result = $this->queryInternal('fetchColumn', 0); $result = $this->queryInternal('fetchColumn', 0);
if (is_resource($result) && get_resource_type($result) === 'stream') { if (is_resource($result) && get_resource_type($result) === 'stream') {
return stream_get_contents($result); return stream_get_contents($result);
} else {
return $result;
} }
return $result;
} }
/** /**
@ -985,9 +985,9 @@ class Command extends Component
} }
if (!$this->db->enableProfiling) { if (!$this->db->enableProfiling) {
return [false, isset($rawSql) ? $rawSql : null]; return [false, isset($rawSql) ? $rawSql : null];
} else {
return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
} }
return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
} }
/** /**

20
framework/db/Connection.php

@ -564,9 +564,9 @@ class Connection extends Component
if ($db !== null) { if ($db !== null) {
$this->pdo = $db->pdo; $this->pdo = $db->pdo;
return; return;
} else {
throw new InvalidConfigException('None of the master DB servers is available.');
} }
throw new InvalidConfigException('None of the master DB servers is available.');
} }
if (empty($this->dsn)) { if (empty($this->dsn)) {
@ -768,17 +768,17 @@ class Connection extends Component
{ {
if ($this->_schema !== null) { if ($this->_schema !== null) {
return $this->_schema; return $this->_schema;
} else { }
$driver = $this->getDriverName(); $driver = $this->getDriverName();
if (isset($this->schemaMap[$driver])) { if (isset($this->schemaMap[$driver])) {
$config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver]; $config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
$config['db'] = $this; $config['db'] = $this;
return $this->_schema = Yii::createObject($config); return $this->_schema = Yii::createObject($config);
} else {
throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
}
} }
throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
} }
/** /**
@ -866,9 +866,9 @@ class Connection extends Component
function ($matches) { function ($matches) {
if (isset($matches[3])) { if (isset($matches[3])) {
return $this->quoteColumnName($matches[3]); return $this->quoteColumnName($matches[3]);
} else {
return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
} }
return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
}, },
$sql $sql
); );
@ -913,9 +913,9 @@ class Connection extends Component
$db = $this->getSlave(false); $db = $this->getSlave(false);
if ($db === null) { if ($db === null) {
return $fallbackToMaster ? $this->getMasterPdo() : null; return $fallbackToMaster ? $this->getMasterPdo() : null;
} else {
return $db->pdo;
} }
return $db->pdo;
} }
/** /**

7
framework/db/Query.php

@ -431,13 +431,14 @@ class Query extends Component implements QueryInterface
$this->offset = $offset; $this->offset = $offset;
return $command->queryScalar(); return $command->queryScalar();
} else { }
return (new self())->select([$selectExpression])
return (new self())
->select([$selectExpression])
->from(['c' => $this]) ->from(['c' => $this])
->createCommand($db) ->createCommand($db)
->queryScalar(); ->queryScalar();
} }
}
/** /**
* Sets the SELECT part of the query. * Sets the SELECT part of the query.

30
framework/db/QueryBuilder.php

@ -1135,9 +1135,9 @@ class QueryBuilder extends \yii\base\Object
if (!is_array($columns)) { if (!is_array($columns)) {
if (strpos($columns, '(') !== false) { if (strpos($columns, '(') !== false) {
return $columns; return $columns;
} else {
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
} }
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
} }
foreach ($columns as $i => $column) { foreach ($columns as $i => $column) {
if ($column instanceof Expression) { if ($column instanceof Expression) {
@ -1179,9 +1179,10 @@ class QueryBuilder extends \yii\base\Object
} }
array_shift($condition); array_shift($condition);
return $this->$method($operator, $condition, $params); return $this->$method($operator, $condition, $params);
} else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
return $this->buildHashCondition($condition, $params);
} }
// hash format: 'column1' => 'value1', 'column2' => 'value2', ...
return $this->buildHashCondition($condition, $params);
} }
/** /**
@ -1244,9 +1245,9 @@ class QueryBuilder extends \yii\base\Object
} }
if (!empty($parts)) { if (!empty($parts)) {
return '(' . implode(") $operator (", $parts) . ')'; return '(' . implode(") $operator (", $parts) . ')';
} else {
return '';
} }
return '';
} }
/** /**
@ -1384,11 +1385,11 @@ class QueryBuilder extends \yii\base\Object
if (count($sqlValues) > 1) { if (count($sqlValues) > 1) {
return "$column $operator (" . implode(', ', $sqlValues) . ')'; return "$column $operator (" . implode(', ', $sqlValues) . ')';
} else { }
$operator = $operator === 'IN' ? '=' : '<>'; $operator = $operator === 'IN' ? '=' : '<>';
return $column . $operator . reset($sqlValues); return $column . $operator . reset($sqlValues);
} }
}
/** /**
* Builds SQL for IN condition * Builds SQL for IN condition
@ -1409,13 +1410,14 @@ class QueryBuilder extends \yii\base\Object
} }
} }
return '(' . implode(', ', $columns) . ") $operator ($sql)"; return '(' . implode(', ', $columns) . ") $operator ($sql)";
} else { }
if (strpos($columns, '(') === false) { if (strpos($columns, '(') === false) {
$columns = $this->db->quoteColumnName($columns); $columns = $this->db->quoteColumnName($columns);
} }
return "$columns $operator ($sql)"; return "$columns $operator ($sql)";
} }
}
/** /**
* Builds SQL for IN condition * Builds SQL for IN condition
@ -1539,9 +1541,9 @@ class QueryBuilder extends \yii\base\Object
if ($operands[0] instanceof Query) { if ($operands[0] instanceof Query) {
list($sql, $params) = $this->build($operands[0], $params); list($sql, $params) = $this->build($operands[0], $params);
return "$operator ($sql)"; return "$operator ($sql)";
} else {
throw new InvalidParamException('Subquery for EXISTS operator must be a Query object.');
} }
throw new InvalidParamException('Subquery for EXISTS operator must be a Query object.');
} }
/** /**
@ -1574,12 +1576,12 @@ class QueryBuilder extends \yii\base\Object
} elseif ($value instanceof Query) { } elseif ($value instanceof Query) {
list($sql, $params) = $this->build($value, $params); list($sql, $params) = $this->build($value, $params);
return "$column $operator ($sql)"; return "$column $operator ($sql)";
} else { }
$phName = self::PARAM_PREFIX . count($params); $phName = self::PARAM_PREFIX . count($params);
$params[$phName] = $value; $params[$phName] = $value;
return "$column $operator $phName"; return "$column $operator $phName";
} }
}
/** /**
* Creates a SELECT EXISTS() SQL statement. * Creates a SELECT EXISTS() SQL statement.

5
framework/db/QueryTrait.php

@ -360,7 +360,8 @@ trait QueryTrait
return [$columns]; return [$columns];
} elseif (is_array($columns)) { } elseif (is_array($columns)) {
return $columns; return $columns;
} else { }
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY); $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
$result = []; $result = [];
foreach ($columns as $column) { foreach ($columns as $column) {
@ -370,9 +371,9 @@ trait QueryTrait
$result[$column] = SORT_ASC; $result[$column] = SORT_ASC;
} }
} }
return $result; return $result;
} }
}
/** /**
* Sets the LIMIT part of the query. * Sets the LIMIT part of the query.

22
framework/db/Schema.php

@ -345,9 +345,9 @@ abstract class Schema extends Object
{ {
if ($this->db->isActive) { if ($this->db->isActive) {
return $this->db->pdo->lastInsertId($sequenceName === '' ? null : $this->quoteTableName($sequenceName)); return $this->db->pdo->lastInsertId($sequenceName === '' ? null : $this->quoteTableName($sequenceName));
} else {
throw new InvalidCallException('DB Connection is not active.');
} }
throw new InvalidCallException('DB Connection is not active.');
} }
/** /**
@ -417,9 +417,9 @@ abstract class Schema extends Object
if ($tableSchema->columns[$name]->autoIncrement) { if ($tableSchema->columns[$name]->autoIncrement) {
$result[$name] = $this->getLastInsertID($tableSchema->sequenceName); $result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
break; break;
} else {
$result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue;
} }
$result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue;
} }
return $result; return $result;
} }
@ -439,11 +439,11 @@ abstract class Schema extends Object
if (($value = $this->db->getSlavePdo()->quote($str)) !== false) { if (($value = $this->db->getSlavePdo()->quote($str)) !== false) {
return $value; return $value;
} else { }
// the driver doesn't support quote (e.g. oci) // the driver doesn't support quote (e.g. oci)
return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'"; return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
} }
}
/** /**
* Quotes a table name for use in a query. * Quotes a table name for use in a query.
@ -533,9 +533,9 @@ abstract class Schema extends Object
$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name); $name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
return str_replace('%', $this->db->tablePrefix, $name); return str_replace('%', $this->db->tablePrefix, $name);
} else {
return $name;
} }
return $name;
} }
/** /**
@ -560,13 +560,13 @@ abstract class Schema extends Object
return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string'; return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string';
} elseif ($column->type === 'integer') { } elseif ($column->type === 'integer') {
return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer'; return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer';
} else { }
return $typeMap[$column->type]; return $typeMap[$column->type];
} }
} else {
return 'string'; return 'string';
} }
}
/** /**
* Converts a DB exception to a more concrete one if possible. * Converts a DB exception to a more concrete one if possible.

4
framework/db/cubrid/QueryBuilder.php

@ -84,9 +84,9 @@ class QueryBuilder extends \yii\db\QueryBuilder
return 'ALTER TABLE ' . $this->db->schema->quoteTableName($tableName) . " AUTO_INCREMENT=$value;"; return 'ALTER TABLE ' . $this->db->schema->quoteTableName($tableName) . " AUTO_INCREMENT=$value;";
} elseif ($table === null) { } elseif ($table === null) {
throw new InvalidParamException("Table not found: $tableName"); throw new InvalidParamException("Table not found: $tableName");
} else {
throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
} }
throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
} }
/** /**

8
framework/db/mssql/QueryBuilder.php

@ -69,9 +69,9 @@ class QueryBuilder extends \yii\db\QueryBuilder
if ($this->isOldMssql()) { if ($this->isOldMssql()) {
return $this->oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset); return $this->oldBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
} else {
return $this->newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
} }
return $this->newBuildOrderByAndLimit($sql, $orderBy, $limit, $offset);
} }
/** /**
@ -220,9 +220,9 @@ class QueryBuilder extends \yii\db\QueryBuilder
return "DBCC CHECKIDENT ('{$tableName}', RESEED, {$value})"; return "DBCC CHECKIDENT ('{$tableName}', RESEED, {$value})";
} elseif ($table === null) { } elseif ($table === null) {
throw new InvalidParamException("Table not found: $tableName"); throw new InvalidParamException("Table not found: $tableName");
} else {
throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
} }
throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
} }
/** /**

4
framework/db/mysql/QueryBuilder.php

@ -171,9 +171,9 @@ class QueryBuilder extends \yii\db\QueryBuilder
return "ALTER TABLE $tableName AUTO_INCREMENT=$value"; return "ALTER TABLE $tableName AUTO_INCREMENT=$value";
} elseif ($table === null) { } elseif ($table === null) {
throw new InvalidParamException("Table not found: $tableName"); throw new InvalidParamException("Table not found: $tableName");
} else {
throw new InvalidParamException("There is no sequence associated with table '$tableName'.");
} }
throw new InvalidParamException("There is no sequence associated with table '$tableName'.");
} }
/** /**

4
framework/db/pgsql/QueryBuilder.php

@ -173,9 +173,9 @@ class QueryBuilder extends \yii\db\QueryBuilder
return "SELECT SETVAL('$sequence',$value,false)"; return "SELECT SETVAL('$sequence',$value,false)";
} elseif ($table === null) { } elseif ($table === null) {
throw new InvalidParamException("Table not found: $tableName"); throw new InvalidParamException("Table not found: $tableName");
} else {
throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
} }
throw new InvalidParamException("There is not sequence associated with table '$tableName'.");
} }
/** /**

4
framework/db/sqlite/QueryBuilder.php

@ -150,9 +150,9 @@ class QueryBuilder extends \yii\db\QueryBuilder
return "UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'"; return "UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'";
} elseif ($table === null) { } elseif ($table === null) {
throw new InvalidParamException("Table not found: $tableName"); throw new InvalidParamException("Table not found: $tableName");
} else {
throw new InvalidParamException("There is not sequence associated with table '$tableName'.'");
} }
throw new InvalidParamException("There is not sequence associated with table '$tableName'.'");
} }
/** /**

18
framework/di/Container.php

@ -334,9 +334,9 @@ class Container extends Component
} }
} }
return $definition; return $definition;
} else {
throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition));
} }
throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition));
} }
/** /**
@ -379,14 +379,15 @@ class Container extends Component
// set $config as the last parameter (existing one will be overwritten) // set $config as the last parameter (existing one will be overwritten)
$dependencies[count($dependencies) - 1] = $config; $dependencies[count($dependencies) - 1] = $config;
return $reflection->newInstanceArgs($dependencies); return $reflection->newInstanceArgs($dependencies);
} else { }
$object = $reflection->newInstanceArgs($dependencies); $object = $reflection->newInstanceArgs($dependencies);
foreach ($config as $name => $value) { foreach ($config as $name => $value) {
$object->$name = $value; $object->$name = $value;
} }
return $object; return $object;
} }
}
/** /**
* Merges the user-specified constructor parameters with the ones registered via [[set()]]. * Merges the user-specified constructor parameters with the ones registered via [[set()]].
@ -400,14 +401,15 @@ class Container extends Component
return $params; return $params;
} elseif (empty($params)) { } elseif (empty($params)) {
return $this->_params[$class]; return $this->_params[$class];
} else { }
$ps = $this->_params[$class]; $ps = $this->_params[$class];
foreach ($params as $index => $value) { foreach ($params as $index => $value) {
$ps[$index] = $value; $ps[$index] = $value;
} }
return $ps; return $ps;
} }
}
/** /**
* Returns the dependencies of the specified class. * Returns the dependencies of the specified class.
@ -494,9 +496,9 @@ class Container extends Component
{ {
if (is_callable($callback)) { if (is_callable($callback)) {
return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params)); return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params));
} else {
return call_user_func_array($callback, $params);
} }
return call_user_func_array($callback, $params);
} }
/** /**

12
framework/di/Instance.php

@ -119,9 +119,9 @@ class Instance
$component = $container->get($class, [], $reference); $component = $container->get($class, [], $reference);
if ($type === null || $component instanceof $type) { if ($type === null || $component instanceof $type) {
return $component; return $component;
} else {
throw new InvalidConfigException('Invalid data type: ' . $class . '. ' . $type . ' is expected.');
} }
throw new InvalidConfigException('Invalid data type: ' . $class . '. ' . $type . ' is expected.');
} elseif (empty($reference)) { } elseif (empty($reference)) {
throw new InvalidConfigException('The required component is not specified.'); throw new InvalidConfigException('The required component is not specified.');
} }
@ -140,9 +140,9 @@ class Instance
} }
if ($type === null || $component instanceof $type) { if ($type === null || $component instanceof $type) {
return $component; return $component;
} else {
throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
} }
throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
} }
$valueType = is_object($reference) ? get_class($reference) : gettype($reference); $valueType = is_object($reference) ? get_class($reference) : gettype($reference);
@ -162,9 +162,9 @@ class Instance
} }
if (Yii::$app && Yii::$app->has($this->id)) { if (Yii::$app && Yii::$app->has($this->id)) {
return Yii::$app->get($this->id); return Yii::$app->get($this->id);
} else {
return Yii::$container->get($this->id);
} }
return Yii::$container->get($this->id);
} }
/** /**

16
framework/di/ServiceLocator.php

@ -71,9 +71,9 @@ class ServiceLocator extends Component
{ {
if ($this->has($name)) { if ($this->has($name)) {
return $this->get($name); return $this->get($name);
} else {
return parent::__get($name);
} }
return parent::__get($name);
} }
/** /**
@ -86,9 +86,9 @@ class ServiceLocator extends Component
{ {
if ($this->has($name)) { if ($this->has($name)) {
return true; return true;
} else {
return parent::__isset($name);
} }
return parent::__isset($name);
} }
/** /**
@ -131,14 +131,14 @@ class ServiceLocator extends Component
$definition = $this->_definitions[$id]; $definition = $this->_definitions[$id];
if (is_object($definition) && !$definition instanceof Closure) { if (is_object($definition) && !$definition instanceof Closure) {
return $this->_components[$id] = $definition; return $this->_components[$id] = $definition;
} else {
return $this->_components[$id] = Yii::createObject($definition);
} }
return $this->_components[$id] = Yii::createObject($definition);
} elseif ($throwException) { } elseif ($throwException) {
throw new InvalidConfigException("Unknown component ID: $id"); throw new InvalidConfigException("Unknown component ID: $id");
} else {
return null;
} }
return null;
} }
/** /**

4
framework/filters/ContentNegotiator.php

@ -176,9 +176,9 @@ class ContentNegotiator extends ActionFilter implements BootstrapInterface
$response->acceptMimeType = null; $response->acceptMimeType = null;
$response->acceptParams = []; $response->acceptParams = [];
return; return;
} else {
throw new UnsupportedMediaTypeHttpException('The requested response format is not supported: ' . $format);
} }
throw new UnsupportedMediaTypeHttpException('The requested response format is not supported: ' . $format);
} }
$types = $request->getAcceptableContentTypes(); $types = $request->getAcceptableContentTypes();

4
framework/filters/HttpCache.php

@ -171,9 +171,9 @@ class HttpCache extends ActionFilter
return $etag !== null && in_array($etag, Yii::$app->request->getETags(), true); return $etag !== null && in_array($etag, Yii::$app->request->getETags(), true);
} elseif (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { } elseif (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
return $lastModified !== null && @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified; return $lastModified !== null && @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified;
} else {
return false;
} }
return false;
} }
/** /**

4
framework/filters/PageCache.php

@ -171,12 +171,12 @@ class PageCache extends ActionFilter
$response->on(Response::EVENT_AFTER_SEND, [$this, 'cacheResponse']); $response->on(Response::EVENT_AFTER_SEND, [$this, 'cacheResponse']);
Yii::trace('Valid page content is not found in the cache.', __METHOD__); Yii::trace('Valid page content is not found in the cache.', __METHOD__);
return true; return true;
} else { }
$this->restoreResponse($response, $data); $this->restoreResponse($response, $data);
Yii::trace('Valid page content is found in the cache.', __METHOD__); Yii::trace('Valid page content is found in the cache.', __METHOD__);
return false; return false;
} }
}
/** /**
* This method is invoked right before the response caching is to be started. * This method is invoked right before the response caching is to be started.

4
framework/filters/RateLimiter.php

@ -120,11 +120,11 @@ class RateLimiter extends ActionFilter
$user->saveAllowance($request, $action, 0, $current); $user->saveAllowance($request, $action, 0, $current);
$this->addRateLimitHeaders($response, $limit, 0, $window); $this->addRateLimitHeaders($response, $limit, 0, $window);
throw new TooManyRequestsHttpException($this->errorMessage); throw new TooManyRequestsHttpException($this->errorMessage);
} else { }
$user->saveAllowance($request, $action, $allowance - 1, $current); $user->saveAllowance($request, $action, $allowance - 1, $current);
$this->addRateLimitHeaders($response, $limit, $allowance - 1, (int) (($limit - $allowance) * $window / $limit)); $this->addRateLimitHeaders($response, $limit, $allowance - 1, (int) (($limit - $allowance) * $window / $limit));
} }
}
/** /**
* Adds the rate limit headers to the response * Adds the rate limit headers to the response

5
framework/filters/auth/AuthMethod.php

@ -69,12 +69,13 @@ abstract class AuthMethod extends ActionFilter implements AuthInterface
if ($identity !== null || $this->isOptional($action)) { if ($identity !== null || $this->isOptional($action)) {
return true; return true;
} else { }
$this->challenge($response); $this->challenge($response);
$this->handleFailure($response); $this->handleFailure($response);
return false; return false;
} }
}
/** /**
* @inheritdoc * @inheritdoc

8
framework/grid/ActionColumn.php

@ -198,13 +198,13 @@ class ActionColumn extends Column
{ {
if (is_callable($this->urlCreator)) { if (is_callable($this->urlCreator)) {
return call_user_func($this->urlCreator, $action, $model, $key, $index, $this); return call_user_func($this->urlCreator, $action, $model, $key, $index, $this);
} else { }
$params = is_array($key) ? $key : ['id' => (string) $key]; $params = is_array($key) ? $key : ['id' => (string) $key];
$params[0] = $this->controller ? $this->controller . '/' . $action : $action; $params[0] = $this->controller ? $this->controller . '/' . $action : $action;
return Url::toRoute($params); return Url::toRoute($params);
} }
}
/** /**
* @inheritdoc * @inheritdoc
@ -225,9 +225,9 @@ class ActionColumn extends Column
if ($isVisible && isset($this->buttons[$name])) { if ($isVisible && isset($this->buttons[$name])) {
$url = $this->createUrl($name, $model, $key, $index); $url = $this->createUrl($name, $model, $key, $index);
return call_user_func($this->buttons[$name], $url, $model, $key); return call_user_func($this->buttons[$name], $url, $model, $key);
} else {
return '';
} }
return '';
}, $this->template); }, $this->template);
} }
} }

4
framework/grid/CheckboxColumn.php

@ -103,9 +103,9 @@ class CheckboxColumn extends Column
{ {
if ($this->header !== null || !$this->multiple) { if ($this->header !== null || !$this->multiple) {
return parent::renderHeaderCellContent(); return parent::renderHeaderCellContent();
} else {
return Html::checkbox($this->getHeaderCheckBoxName(), false, ['class' => 'select-on-check-all']);
} }
return Html::checkbox($this->getHeaderCheckBoxName(), false, ['class' => 'select-on-check-all']);
} }
/** /**

4
framework/grid/Column.php

@ -162,9 +162,9 @@ class Column extends Object
{ {
if ($this->content !== null) { if ($this->content !== null) {
return call_user_func($this->content, $model, $key, $index, $this); return call_user_func($this->content, $model, $key, $index, $this);
} else {
return $this->grid->emptyCell;
} }
return $this->grid->emptyCell;
} }
/** /**

18
framework/grid/DataColumn.php

@ -130,9 +130,9 @@ class DataColumn extends Column
if ($this->attribute !== null && $this->enableSorting && if ($this->attribute !== null && $this->enableSorting &&
($sort = $this->grid->dataProvider->getSort()) !== false && $sort->hasAttribute($this->attribute)) { ($sort = $this->grid->dataProvider->getSort()) !== false && $sort->hasAttribute($this->attribute)) {
return $sort->link($this->attribute, array_merge($this->sortLinkOptions, ['label' => $label])); return $sort->link($this->attribute, array_merge($this->sortLinkOptions, ['label' => $label]));
} else {
return $label;
} }
return $label;
} }
/** /**
@ -197,13 +197,13 @@ class DataColumn extends Column
$this->grid->formatter->booleanFormat[0], $this->grid->formatter->booleanFormat[0],
$this->grid->formatter->booleanFormat[1], $this->grid->formatter->booleanFormat[1],
], $options) . $error; ], $options) . $error;
} else { }
return Html::activeTextInput($model, $this->attribute, $this->filterInputOptions) . $error; return Html::activeTextInput($model, $this->attribute, $this->filterInputOptions) . $error;
} }
} else {
return parent::renderFilterCellContent(); return parent::renderFilterCellContent();
} }
}
/** /**
* Returns the data cell value. * Returns the data cell value.
@ -217,9 +217,9 @@ class DataColumn extends Column
if ($this->value !== null) { if ($this->value !== null) {
if (is_string($this->value)) { if (is_string($this->value)) {
return ArrayHelper::getValue($model, $this->value); return ArrayHelper::getValue($model, $this->value);
} else {
return call_user_func($this->value, $model, $key, $index, $this);
} }
return call_user_func($this->value, $model, $key, $index, $this);
} elseif ($this->attribute !== null) { } elseif ($this->attribute !== null) {
return ArrayHelper::getValue($model, $this->attribute); return ArrayHelper::getValue($model, $this->attribute);
} }
@ -233,8 +233,8 @@ class DataColumn extends Column
{ {
if ($this->content === null) { if ($this->content === null) {
return $this->grid->formatter->format($this->getDataCellValue($model, $key, $index), $this->format); return $this->grid->formatter->format($this->getDataCellValue($model, $key, $index), $this->format);
} else {
return parent::renderDataCellContent($model, $key, $index);
} }
return parent::renderDataCellContent($model, $key, $index);
} }
} }

20
framework/grid/GridView.php

@ -299,9 +299,9 @@ class GridView extends BaseListView
{ {
if ($this->filterModel instanceof Model && $this->filterModel->hasErrors()) { if ($this->filterModel instanceof Model && $this->filterModel->hasErrors()) {
return Html::errorSummary($this->filterModel, $this->filterErrorSummaryOptions); return Html::errorSummary($this->filterModel, $this->filterErrorSummaryOptions);
} else {
return '';
} }
return '';
} }
/** /**
@ -365,9 +365,9 @@ class GridView extends BaseListView
{ {
if (!empty($this->caption)) { if (!empty($this->caption)) {
return Html::tag('caption', $this->caption, $this->captionOptions); return Html::tag('caption', $this->caption, $this->captionOptions);
} else {
return false;
} }
return false;
} }
/** /**
@ -391,9 +391,9 @@ class GridView extends BaseListView
} }
return Html::tag('colgroup', implode("\n", $cols)); return Html::tag('colgroup', implode("\n", $cols));
} else {
return false;
} }
return false;
} }
/** /**
@ -450,9 +450,9 @@ class GridView extends BaseListView
} }
return Html::tag('tr', implode('', $cells), $this->filterRowOptions); return Html::tag('tr', implode('', $cells), $this->filterRowOptions);
} else {
return '';
} }
return '';
} }
/** /**
@ -487,9 +487,9 @@ class GridView extends BaseListView
$colspan = count($this->columns); $colspan = count($this->columns);
return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>"; return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>";
} else {
return "<tbody>\n" . implode("\n", $rows) . "\n</tbody>";
} }
return "<tbody>\n" . implode("\n", $rows) . "\n</tbody>";
} }
/** /**

4
framework/grid/SerialColumn.php

@ -43,8 +43,8 @@ class SerialColumn extends Column
$pagination = $this->grid->dataProvider->getPagination(); $pagination = $this->grid->dataProvider->getPagination();
if ($pagination !== false) { if ($pagination !== false) {
return $pagination->getOffset() + $index + 1; return $pagination->getOffset() + $index + 1;
} else {
return $index + 1;
} }
return $index + 1;
} }
} }

27
framework/helpers/BaseArrayHelper.php

@ -94,9 +94,9 @@ class BaseArrayHelper
} }
return $recursive ? static::toArray($result, $properties) : $result; return $recursive ? static::toArray($result, $properties) : $result;
} else {
return [$object];
} }
return [$object];
} }
/** /**
@ -209,9 +209,9 @@ class BaseArrayHelper
return $array->$key; return $array->$key;
} elseif (is_array($array)) { } elseif (is_array($array)) {
return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default; return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default;
} else {
return $default;
} }
return $default;
} }
/** /**
@ -526,7 +526,8 @@ class BaseArrayHelper
// Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case // Function `isset` checks key faster but skips `null`, `array_key_exists` handles this case
// http://php.net/manual/en/function.array-key-exists.php#107786 // http://php.net/manual/en/function.array-key-exists.php#107786
return isset($array[$key]) || array_key_exists($key, $array); return isset($array[$key]) || array_key_exists($key, $array);
} else { }
foreach (array_keys($array) as $k) { foreach (array_keys($array) as $k) {
if (strcasecmp($key, $k) === 0) { if (strcasecmp($key, $k) === 0) {
return true; return true;
@ -535,7 +536,6 @@ class BaseArrayHelper
return false; return false;
} }
}
/** /**
* Sorts an array of objects or arrays (with the same structure) by one or several keys. * Sorts an array of objects or arrays (with the same structure) by one or several keys.
@ -679,15 +679,16 @@ class BaseArrayHelper
} }
} }
return true; return true;
} else { }
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
if (is_string($key)) { if (is_string($key)) {
return true; return true;
} }
} }
return false; return false;
} }
}
/** /**
* Returns a value indicating whether the given array is an indexed array. * Returns a value indicating whether the given array is an indexed array.
@ -714,15 +715,16 @@ class BaseArrayHelper
if ($consecutive) { if ($consecutive) {
return array_keys($array) === range(0, count($array) - 1); return array_keys($array) === range(0, count($array) - 1);
} else { }
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
if (!is_int($key)) { if (!is_int($key)) {
return false; return false;
} }
} }
return true; return true;
} }
}
/** /**
* Check whether an array or [[\Traversable]] contains an element. * Check whether an array or [[\Traversable]] contains an element.
@ -789,10 +791,11 @@ class BaseArrayHelper
return false; return false;
} }
} }
return true; return true;
} else {
throw new InvalidParamException('Argument $needles must be an array or implement Traversable');
} }
throw new InvalidParamException('Argument $needles must be an array or implement Traversable');
} }
/** /**

8
framework/helpers/BaseFileHelper.php

@ -104,7 +104,8 @@ class BaseFileHelper
$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file); $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
if (is_file($desiredFile)) { if (is_file($desiredFile)) {
return $desiredFile; return $desiredFile;
} else { }
$language = substr($language, 0, 2); $language = substr($language, 0, 2);
if ($language === $sourceLanguage) { if ($language === $sourceLanguage) {
return $file; return $file;
@ -113,7 +114,6 @@ class BaseFileHelper
return is_file($desiredFile) ? $desiredFile : $file; return is_file($desiredFile) ? $desiredFile : $file;
} }
}
/** /**
* Determines the MIME type of the specified file. * Determines the MIME type of the specified file.
@ -138,9 +138,9 @@ class BaseFileHelper
if (!extension_loaded('fileinfo')) { if (!extension_loaded('fileinfo')) {
if ($checkExtension) { if ($checkExtension) {
return static::getMimeTypeByExtension($file, $magicFile); return static::getMimeTypeByExtension($file, $magicFile);
} else {
throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
} }
throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
} }
$info = finfo_open(FILEINFO_MIME_TYPE, $magicFile); $info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);

28
framework/helpers/BaseHtml.php

@ -243,9 +243,9 @@ class BaseHtml
} elseif (isset($options['noscript']) && $options['noscript'] === true) { } elseif (isset($options['noscript']) && $options['noscript'] === true) {
unset($options['noscript']); unset($options['noscript']);
return '<noscript>' . static::tag('link', '', $options) . '</noscript>'; return '<noscript>' . static::tag('link', '', $options) . '</noscript>';
} else {
return static::tag('link', '', $options);
} }
return static::tag('link', '', $options);
} }
/** /**
@ -270,9 +270,9 @@ class BaseHtml
$condition = $options['condition']; $condition = $options['condition'];
unset($options['condition']); unset($options['condition']);
return self::wrapIntoCondition(static::tag('script', '', $options), $condition); return self::wrapIntoCondition(static::tag('script', '', $options), $condition);
} else {
return static::tag('script', '', $options);
} }
return static::tag('script', '', $options);
} }
/** /**
@ -300,9 +300,9 @@ class BaseHtml
if ($request instanceof Request && $request->enableCsrfValidation) { if ($request instanceof Request && $request->enableCsrfValidation) {
return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n " return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n "
. static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n"; . static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n";
} else {
return '';
} }
return '';
} }
/** /**
@ -764,9 +764,9 @@ class BaseHtml
unset($options['label'], $options['labelOptions']); unset($options['label'], $options['labelOptions']);
$content = static::label(static::input($type, $name, $value, $options) . ' ' . $label, null, $labelOptions); $content = static::label(static::input($type, $name, $value, $options) . ' ' . $label, null, $labelOptions);
return $hidden . $content; return $hidden . $content;
} else {
return $hidden . static::input($type, $name, $value, $options);
} }
return $hidden . static::input($type, $name, $value, $options);
} }
/** /**
@ -1556,9 +1556,9 @@ class BaseHtml
{ {
if (empty($options['multiple'])) { if (empty($options['multiple'])) {
return static::activeListInput('dropDownList', $model, $attribute, $items, $options); return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
} else {
return static::activeListBox($model, $attribute, $items, $options);
} }
return static::activeListBox($model, $attribute, $items, $options);
} }
/** /**
@ -2080,9 +2080,9 @@ class BaseHtml
{ {
if (preg_match(static::$attributeRegex, $attribute, $matches)) { if (preg_match(static::$attributeRegex, $attribute, $matches)) {
return $matches[2]; return $matches[2];
} else {
throw new InvalidParamException('Attribute name must contain word characters only.');
} }
throw new InvalidParamException('Attribute name must contain word characters only.');
} }
/** /**
@ -2161,9 +2161,9 @@ class BaseHtml
return $attribute . $suffix; return $attribute . $suffix;
} elseif ($formName !== '') { } elseif ($formName !== '') {
return $formName . $prefix . "[$attribute]" . $suffix; return $formName . $prefix . "[$attribute]" . $suffix;
} else {
throw new InvalidParamException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
} }
throw new InvalidParamException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
} }
/** /**

8
framework/helpers/BaseInflector.php

@ -385,9 +385,9 @@ class BaseInflector
$regex = $strict ? '/[A-Z]/' : '/(?<![A-Z])[A-Z]/'; $regex = $strict ? '/[A-Z]/' : '/(?<![A-Z])[A-Z]/';
if ($separator === '_') { if ($separator === '_') {
return strtolower(trim(preg_replace($regex, '_\0', $name), '_')); return strtolower(trim(preg_replace($regex, '_\0', $name), '_'));
} else {
return strtolower(trim(str_replace('_', $separator, preg_replace($regex, $separator . '\0', $name)), $separator));
} }
return strtolower(trim(str_replace('_', $separator, preg_replace($regex, $separator . '\0', $name)), $separator));
} }
/** /**
@ -496,9 +496,9 @@ class BaseInflector
} }
return transliterator_transliterate($transliterator, $string); return transliterator_transliterate($transliterator, $string);
} else {
return strtr($string, static::$transliteration);
} }
return strtr($string, static::$transliteration);
} }
/** /**

20
framework/helpers/BaseStringHelper.php

@ -86,9 +86,9 @@ class BaseStringHelper
$pos = mb_strrpos(str_replace('\\', '/', $path), '/'); $pos = mb_strrpos(str_replace('\\', '/', $path), '/');
if ($pos !== false) { if ($pos !== false) {
return mb_substr($path, 0, $pos); return mb_substr($path, 0, $pos);
} else {
return '';
} }
return '';
} }
/** /**
@ -110,9 +110,9 @@ class BaseStringHelper
if (mb_strlen($string, $encoding ?: Yii::$app->charset) > $length) { if (mb_strlen($string, $encoding ?: Yii::$app->charset) > $length) {
return rtrim(mb_substr($string, 0, $length, $encoding ?: Yii::$app->charset)) . $suffix; return rtrim(mb_substr($string, 0, $length, $encoding ?: Yii::$app->charset)) . $suffix;
} else {
return $string;
} }
return $string;
} }
/** /**
@ -134,9 +134,9 @@ class BaseStringHelper
$words = preg_split('/(\s+)/u', trim($string), null, PREG_SPLIT_DELIM_CAPTURE); $words = preg_split('/(\s+)/u', trim($string), null, PREG_SPLIT_DELIM_CAPTURE);
if (count($words) / 2 > $count) { if (count($words) / 2 > $count) {
return implode('', array_slice($words, 0, ($count * 2) - 1)) . $suffix; return implode('', array_slice($words, 0, ($count * 2) - 1)) . $suffix;
} else {
return $string;
} }
return $string;
} }
/** /**
@ -215,9 +215,9 @@ class BaseStringHelper
} }
if ($caseSensitive) { if ($caseSensitive) {
return strncmp($string, $with, $bytes) === 0; return strncmp($string, $with, $bytes) === 0;
} else {
return mb_strtolower(mb_substr($string, 0, $bytes, '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
} }
return mb_strtolower(mb_substr($string, 0, $bytes, '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
} }
/** /**
@ -240,9 +240,9 @@ class BaseStringHelper
return false; return false;
} }
return substr_compare($string, $with, -$bytes, $bytes) === 0; return substr_compare($string, $with, -$bytes, $bytes) === 0;
} else {
return mb_strtolower(mb_substr($string, -$bytes, mb_strlen($string, '8bit'), '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
} }
return mb_strtolower(mb_substr($string, -$bytes, mb_strlen($string, '8bit'), '8bit'), Yii::$app->charset) === mb_strtolower($with, Yii::$app->charset);
} }
/** /**

12
framework/helpers/BaseUrl.php

@ -100,9 +100,9 @@ class BaseUrl
if ($scheme !== false) { if ($scheme !== false) {
return static::getUrlManager()->createAbsoluteUrl($route, is_string($scheme) ? $scheme : null); return static::getUrlManager()->createAbsoluteUrl($route, is_string($scheme) ? $scheme : null);
} else {
return static::getUrlManager()->createUrl($route);
} }
return static::getUrlManager()->createUrl($route);
} }
/** /**
@ -140,11 +140,11 @@ class BaseUrl
if (strpos($route, '/') === false) { if (strpos($route, '/') === false) {
// empty or an action ID // empty or an action ID
return $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route; return $route === '' ? Yii::$app->controller->getRoute() : Yii::$app->controller->getUniqueId() . '/' . $route;
} else { }
// relative to module // relative to module
return ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/'); return ltrim(Yii::$app->controller->module->getUniqueId() . '/' . $route, '/');
} }
}
/** /**
* Creates a URL based on the given parameters. * Creates a URL based on the given parameters.
@ -320,9 +320,9 @@ class BaseUrl
{ {
if ($name === null) { if ($name === null) {
return Yii::$app->getUser()->getReturnUrl(); return Yii::$app->getUser()->getReturnUrl();
} else {
return Yii::$app->getSession()->get($name);
} }
return Yii::$app->getSession()->get($name);
} }
/** /**

4
framework/i18n/DbMessageSource.php

@ -127,9 +127,9 @@ class DbMessageSource extends MessageSource
} }
return $messages; return $messages;
} else {
return $this->loadMessagesFromDb($category, $language);
} }
return $this->loadMessagesFromDb($category, $language);
} }
/** /**

60
framework/i18n/Formatter.php

@ -328,9 +328,9 @@ class Formatter extends Component
$method = 'as' . $format; $method = 'as' . $format;
if ($this->hasMethod($method)) { if ($this->hasMethod($method)) {
return call_user_func_array([$this, $method], $params); return call_user_func_array([$this, $method], $params);
} else {
throw new InvalidParamException("Unknown format type: $format");
} }
throw new InvalidParamException("Unknown format type: $format");
} }
@ -649,7 +649,8 @@ class Formatter extends Component
$timestamp = new DateTime($timestamp->format(DateTime::ISO8601), $timestamp->getTimezone()); $timestamp = new DateTime($timestamp->format(DateTime::ISO8601), $timestamp->getTimezone());
} }
return $formatter->format($timestamp); return $formatter->format($timestamp);
} else { }
if (strncmp($format, 'php:', 4) === 0) { if (strncmp($format, 'php:', 4) === 0) {
$format = substr($format, 4); $format = substr($format, 4);
} else { } else {
@ -662,9 +663,9 @@ class Formatter extends Component
$timestamp->setTimezone(new DateTimeZone($timeZone)); $timestamp->setTimezone(new DateTimeZone($timeZone));
} }
} }
return $timestamp->format($format); return $timestamp->format($format);
} }
}
/** /**
* Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods. * Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods.
@ -718,9 +719,9 @@ class Formatter extends Component
!($info['hour'] === false && $info['minute'] === false && $info['second'] === false), !($info['hour'] === false && $info['minute'] === false && $info['second'] === false),
!($info['year'] === false && $info['month'] === false && $info['day'] === false), !($info['year'] === false && $info['month'] === false && $info['day'] === false),
]; ];
} else {
return new DateTime($value, new DateTimeZone($this->defaultTimeZone));
} }
return new DateTime($value, new DateTimeZone($this->defaultTimeZone));
} catch (\Exception $e) { } catch (\Exception $e) {
throw new InvalidParamException("'$value' is not a valid date time value: " . $e->getMessage() throw new InvalidParamException("'$value' is not a valid date time value: " . $e->getMessage()
. "\n" . print_r(DateTime::getLastErrors(), true), $e->getCode(), $e); . "\n" . print_r(DateTime::getLastErrors(), true), $e->getCode(), $e);
@ -826,8 +827,10 @@ class Formatter extends Component
if ($interval->s == 0) { if ($interval->s == 0) {
return Yii::t('yii', 'just now', [], $this->locale); return Yii::t('yii', 'just now', [], $this->locale);
} }
return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->locale); return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->locale);
} else { }
if ($interval->y >= 1) { if ($interval->y >= 1) {
return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->locale); return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->locale);
} }
@ -846,9 +849,9 @@ class Formatter extends Component
if ($interval->s == 0) { if ($interval->s == 0) {
return Yii::t('yii', 'just now', [], $this->locale); return Yii::t('yii', 'just now', [], $this->locale);
} }
return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->locale); return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->locale);
} }
}
/** /**
* Represents the value as duration in human readable format. * Represents the value as duration in human readable format.
@ -941,10 +944,11 @@ class Formatter extends Component
if (($result = $f->format($value, NumberFormatter::TYPE_INT64)) === false) { if (($result = $f->format($value, NumberFormatter::TYPE_INT64)) === false) {
throw new InvalidParamException('Formatting integer value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage()); throw new InvalidParamException('Formatting integer value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
} }
return $result; return $result;
} else {
return number_format((int) $value, 0, $this->decimalSeparator, $this->thousandSeparator);
} }
return number_format((int) $value, 0, $this->decimalSeparator, $this->thousandSeparator);
} }
/** /**
@ -980,14 +984,16 @@ class Formatter extends Component
if (($result = $f->format($value)) === false) { if (($result = $f->format($value)) === false) {
throw new InvalidParamException('Formatting decimal value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage()); throw new InvalidParamException('Formatting decimal value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
} }
return $result; return $result;
} else { }
if ($decimals === null) { if ($decimals === null) {
$decimals = 2; $decimals = 2;
} }
return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator); return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator);
} }
}
/** /**
@ -1019,14 +1025,15 @@ class Formatter extends Component
throw new InvalidParamException('Formatting percent value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage()); throw new InvalidParamException('Formatting percent value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
} }
return $result; return $result;
} else { }
if ($decimals === null) { if ($decimals === null) {
$decimals = 0; $decimals = 0;
} }
$value *= 100; $value *= 100;
return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%'; return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
} }
}
/** /**
* Formats the value as a scientific number. * Formats the value as a scientific number.
@ -1056,14 +1063,15 @@ class Formatter extends Component
if (($result = $f->format($value)) === false) { if (($result = $f->format($value)) === false) {
throw new InvalidParamException('Formatting scientific number value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage()); throw new InvalidParamException('Formatting scientific number value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
} }
return $result; return $result;
} else { }
if ($decimals !== null) { if ($decimals !== null) {
return sprintf("%.{$decimals}E", $value); return sprintf("%.{$decimals}E", $value);
} else {
return sprintf('%.E', $value);
}
} }
return sprintf('%.E', $value);
} }
/** /**
@ -1104,17 +1112,19 @@ class Formatter extends Component
if ($result === false) { if ($result === false) {
throw new InvalidParamException('Formatting currency value failed: ' . $formatter->getErrorCode() . ' ' . $formatter->getErrorMessage()); throw new InvalidParamException('Formatting currency value failed: ' . $formatter->getErrorCode() . ' ' . $formatter->getErrorMessage());
} }
return $result; return $result;
} else { }
if ($currency === null) { if ($currency === null) {
if ($this->currencyCode === null) { if ($this->currencyCode === null) {
throw new InvalidConfigException('The default currency code for the formatter is not defined and the php intl extension is not installed which could take the default currency from the locale.'); throw new InvalidConfigException('The default currency code for the formatter is not defined and the php intl extension is not installed which could take the default currency from the locale.');
} }
$currency = $this->currencyCode; $currency = $this->currencyCode;
} }
return $currency . ' ' . $this->asDecimal($value, 2, $options, $textOptions); return $currency . ' ' . $this->asDecimal($value, 2, $options, $textOptions);
} }
}
/** /**
* Formats the value as a number spellout. * Formats the value as a number spellout.
@ -1137,10 +1147,11 @@ class Formatter extends Component
if (($result = $f->format($value)) === false) { if (($result = $f->format($value)) === false) {
throw new InvalidParamException('Formatting number as spellout failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage()); throw new InvalidParamException('Formatting number as spellout failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
} }
return $result; return $result;
} else {
throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
} }
throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
} }
/** /**
@ -1164,10 +1175,11 @@ class Formatter extends Component
if (($result = $f->format($value)) === false) { if (($result = $f->format($value)) === false) {
throw new InvalidParamException('Formatting number as ordinal failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage()); throw new InvalidParamException('Formatting number as ordinal failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
} }
return $result; return $result;
} else {
throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
} }
throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
} }
/** /**

4
framework/i18n/GettextMessageSource.php

@ -162,8 +162,8 @@ class GettextMessageSource extends MessageSource
} }
return $messages; return $messages;
} else {
return null;
} }
return null;
} }
} }

4
framework/i18n/GettextMoFile.php

@ -207,9 +207,9 @@ class GettextMoFile extends GettextFile
{ {
if ($byteCount > 0) { if ($byteCount > 0) {
return fread($fileHandle, $byteCount); return fread($fileHandle, $byteCount);
} else {
return null;
} }
return null;
} }
/** /**

22
framework/i18n/I18N.php

@ -89,9 +89,9 @@ class I18N extends Component
$translation = $messageSource->translate($category, $message, $language); $translation = $messageSource->translate($category, $message, $language);
if ($translation === false) { if ($translation === false) {
return $this->format($message, $params, $messageSource->sourceLanguage); return $this->format($message, $params, $messageSource->sourceLanguage);
} else {
return $this->format($translation, $params, $language);
} }
return $this->format($translation, $params, $language);
} }
/** /**
@ -117,9 +117,9 @@ class I18N extends Component
Yii::warning("Formatting message for language '$language' failed with error: $errorMessage. The message being formatted was: $message.", __METHOD__); Yii::warning("Formatting message for language '$language' failed with error: $errorMessage. The message being formatted was: $message.", __METHOD__);
return $message; return $message;
} else {
return $result;
} }
return $result;
} }
$p = []; $p = [];
@ -172,29 +172,29 @@ class I18N extends Component
$source = $this->translations[$category]; $source = $this->translations[$category];
if ($source instanceof MessageSource) { if ($source instanceof MessageSource) {
return $source; return $source;
} else { }
return $this->translations[$category] = Yii::createObject($source); return $this->translations[$category] = Yii::createObject($source);
} }
} else {
// try wildcard matching // try wildcard matching
foreach ($this->translations as $pattern => $source) { foreach ($this->translations as $pattern => $source) {
if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) { if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
if ($source instanceof MessageSource) { if ($source instanceof MessageSource) {
return $source; return $source;
} else {
return $this->translations[$category] = $this->translations[$pattern] = Yii::createObject($source);
} }
return $this->translations[$category] = $this->translations[$pattern] = Yii::createObject($source);
} }
} }
// match '*' in the last // match '*' in the last
if (isset($this->translations['*'])) { if (isset($this->translations['*'])) {
$source = $this->translations['*']; $source = $this->translations['*'];
if ($source instanceof MessageSource) { if ($source instanceof MessageSource) {
return $source; return $source;
} else {
return $this->translations[$category] = $this->translations['*'] = Yii::createObject($source);
}
} }
return $this->translations[$category] = $this->translations['*'] = Yii::createObject($source);
} }
throw new InvalidConfigException("Unable to locate message source for category '$category'."); throw new InvalidConfigException("Unable to locate message source for category '$category'.");

8
framework/i18n/MessageFormatter.php

@ -126,9 +126,9 @@ class MessageFormatter extends Component
$this->_errorCode = $formatter->getErrorCode(); $this->_errorCode = $formatter->getErrorCode();
$this->_errorMessage = $formatter->getErrorMessage(); $this->_errorMessage = $formatter->getErrorMessage();
return false; return false;
} else {
return $result;
} }
return $result;
} }
/** /**
@ -187,7 +187,8 @@ class MessageFormatter extends Component
$this->_errorMessage = $formatter->getErrorMessage(); $this->_errorMessage = $formatter->getErrorMessage();
return false; return false;
} else { }
$values = []; $values = [];
foreach ($result as $key => $value) { foreach ($result as $key => $value) {
$values[$map[$key]] = $value; $values[$map[$key]] = $value;
@ -195,7 +196,6 @@ class MessageFormatter extends Component
return $values; return $values;
} }
}
/** /**
* Replace named placeholders with numeric placeholders and quote unused. * Replace named placeholders with numeric placeholders and quote unused.

4
framework/i18n/MessageSource.php

@ -85,9 +85,9 @@ class MessageSource extends Component
{ {
if ($this->forceTranslation || $language !== $this->sourceLanguage) { if ($this->forceTranslation || $language !== $this->sourceLanguage) {
return $this->translateMessage($category, $message, $language); return $this->translateMessage($category, $message, $language);
} else {
return false;
} }
return false;
} }
/** /**

4
framework/i18n/PhpMessageSource.php

@ -159,8 +159,8 @@ class PhpMessageSource extends MessageSource
} }
return $messages; return $messages;
} else {
return null;
} }
return null;
} }
} }

4
framework/mail/BaseMailer.php

@ -301,9 +301,9 @@ abstract class BaseMailer extends Component implements MailerInterface, ViewCont
$output = $this->getView()->render($view, $params, $this); $output = $this->getView()->render($view, $params, $this);
if ($layout !== false) { if ($layout !== false) {
return $this->getView()->render($layout, ['content' => $output, 'message' => $this->_message], $this); return $this->getView()->render($layout, ['content' => $output, 'message' => $this->_message], $this);
} else {
return $output;
} }
return $output;
} }
/** /**

4
framework/mutex/FileMutex.php

@ -117,14 +117,14 @@ class FileMutex extends Mutex
{ {
if (!isset($this->_files[$name]) || !flock($this->_files[$name], LOCK_UN)) { if (!isset($this->_files[$name]) || !flock($this->_files[$name], LOCK_UN)) {
return false; return false;
} else { }
fclose($this->_files[$name]); fclose($this->_files[$name]);
unlink($this->getLockFilePath($name)); unlink($this->getLockFilePath($name));
unset($this->_files[$name]); unset($this->_files[$name]);
return true; return true;
} }
}
/** /**
* Generate path for lock file. * Generate path for lock file.

8
framework/mutex/Mutex.php

@ -72,9 +72,9 @@ abstract class Mutex extends Component
$this->_locks[] = $name; $this->_locks[] = $name;
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@ -91,9 +91,9 @@ abstract class Mutex extends Component
} }
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**

16
framework/rbac/BaseManager.php

@ -128,9 +128,9 @@ abstract class BaseManager extends Component implements ManagerInterface
return $this->addItem($object); return $this->addItem($object);
} elseif ($object instanceof Rule) { } elseif ($object instanceof Rule) {
return $this->addRule($object); return $this->addRule($object);
} else {
throw new InvalidParamException('Adding unsupported object type.');
} }
throw new InvalidParamException('Adding unsupported object type.');
} }
/** /**
@ -142,9 +142,9 @@ abstract class BaseManager extends Component implements ManagerInterface
return $this->removeItem($object); return $this->removeItem($object);
} elseif ($object instanceof Rule) { } elseif ($object instanceof Rule) {
return $this->removeRule($object); return $this->removeRule($object);
} else {
throw new InvalidParamException('Removing unsupported object type.');
} }
throw new InvalidParamException('Removing unsupported object type.');
} }
/** /**
@ -161,9 +161,9 @@ abstract class BaseManager extends Component implements ManagerInterface
return $this->updateItem($name, $object); return $this->updateItem($name, $object);
} elseif ($object instanceof Rule) { } elseif ($object instanceof Rule) {
return $this->updateRule($name, $object); return $this->updateRule($name, $object);
} else {
throw new InvalidParamException('Updating unsupported object type.');
} }
throw new InvalidParamException('Updating unsupported object type.');
} }
/** /**
@ -235,9 +235,9 @@ abstract class BaseManager extends Component implements ManagerInterface
$rule = $this->getRule($item->ruleName); $rule = $this->getRule($item->ruleName);
if ($rule instanceof Rule) { if ($rule instanceof Rule) {
return $rule->execute($user, $item, $params); return $rule->execute($user, $item, $params);
} else {
throw new InvalidConfigException("Rule not found: {$item->ruleName}");
} }
throw new InvalidConfigException("Rule not found: {$item->ruleName}");
} }
/** /**

4
framework/rbac/DbManager.php

@ -129,9 +129,9 @@ class DbManager extends BaseManager
$this->loadFromCache(); $this->loadFromCache();
if ($this->items !== null) { if ($this->items !== null) {
return $this->checkAccessFromCache($userId, $permissionName, $params, $assignments); return $this->checkAccessFromCache($userId, $permissionName, $params, $assignments);
} else {
return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
} }
return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
} }
/** /**

37
framework/rbac/PhpManager.php

@ -226,9 +226,9 @@ class PhpManager extends BaseManager
unset($this->children[$parent->name][$child->name]); unset($this->children[$parent->name][$child->name]);
$this->saveItems(); $this->saveItems();
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@ -240,9 +240,9 @@ class PhpManager extends BaseManager
unset($this->children[$parent->name]); unset($this->children[$parent->name]);
$this->saveItems(); $this->saveItems();
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@ -262,16 +262,17 @@ class PhpManager extends BaseManager
throw new InvalidParamException("Unknown role '{$role->name}'."); throw new InvalidParamException("Unknown role '{$role->name}'.");
} elseif (isset($this->assignments[$userId][$role->name])) { } elseif (isset($this->assignments[$userId][$role->name])) {
throw new InvalidParamException("Authorization item '{$role->name}' has already been assigned to user '$userId'."); throw new InvalidParamException("Authorization item '{$role->name}' has already been assigned to user '$userId'.");
} else { }
$this->assignments[$userId][$role->name] = new Assignment([ $this->assignments[$userId][$role->name] = new Assignment([
'userId' => $userId, 'userId' => $userId,
'roleName' => $role->name, 'roleName' => $role->name,
'createdAt' => time(), 'createdAt' => time(),
]); ]);
$this->saveAssignments(); $this->saveAssignments();
return $this->assignments[$userId][$role->name]; return $this->assignments[$userId][$role->name];
} }
}
/** /**
* @inheritdoc * @inheritdoc
@ -282,9 +283,9 @@ class PhpManager extends BaseManager
unset($this->assignments[$userId][$role->name]); unset($this->assignments[$userId][$role->name]);
$this->saveAssignments(); $this->saveAssignments();
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@ -298,9 +299,9 @@ class PhpManager extends BaseManager
} }
$this->saveAssignments(); $this->saveAssignments();
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@ -345,9 +346,9 @@ class PhpManager extends BaseManager
$this->saveItems(); $this->saveItems();
$this->saveAssignments(); $this->saveAssignments();
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@ -630,9 +631,9 @@ class PhpManager extends BaseManager
} }
$this->saveRules(); $this->saveRules();
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@ -653,7 +654,8 @@ class PhpManager extends BaseManager
if ($name !== $item->name) { if ($name !== $item->name) {
if (isset($this->items[$item->name])) { if (isset($this->items[$item->name])) {
throw new InvalidParamException("Unable to change the item name. The name '{$item->name}' is already used by another item."); throw new InvalidParamException("Unable to change the item name. The name '{$item->name}' is already used by another item.");
} else { }
// Remove old item in case of renaming // Remove old item in case of renaming
unset($this->items[$name]); unset($this->items[$name]);
@ -676,7 +678,6 @@ class PhpManager extends BaseManager
} }
$this->saveAssignments(); $this->saveAssignments();
} }
}
$this->items[$item->name] = $item; $this->items[$item->name] = $item;
@ -779,9 +780,9 @@ class PhpManager extends BaseManager
{ {
if (is_file($file)) { if (is_file($file)) {
return require($file); return require($file);
} else {
return [];
} }
return [];
} }
/** /**

4
framework/rest/Action.php

@ -99,8 +99,8 @@ class Action extends \yii\base\Action
if (isset($model)) { if (isset($model)) {
return $model; return $model;
} else {
throw new NotFoundHttpException("Object not found: $id");
} }
throw new NotFoundHttpException("Object not found: $id");
} }
} }

16
framework/rest/Serializer.php

@ -150,9 +150,9 @@ class Serializer extends Component
return $this->serializeModel($data); return $this->serializeModel($data);
} elseif ($data instanceof DataProviderInterface) { } elseif ($data instanceof DataProviderInterface) {
return $this->serializeDataProvider($data); return $this->serializeDataProvider($data);
} else {
return $data;
} }
return $data;
} }
/** /**
@ -195,16 +195,16 @@ class Serializer extends Component
return null; return null;
} elseif ($this->collectionEnvelope === null) { } elseif ($this->collectionEnvelope === null) {
return $models; return $models;
} else { }
$result = [ $result = [
$this->collectionEnvelope => $models, $this->collectionEnvelope => $models,
]; ];
if ($pagination !== false) { if ($pagination !== false) {
return array_merge($result, $this->serializePagination($pagination)); return array_merge($result, $this->serializePagination($pagination));
} else {
return $result;
}
} }
return $result;
} }
/** /**
@ -254,11 +254,11 @@ class Serializer extends Component
{ {
if ($this->request->getIsHead()) { if ($this->request->getIsHead()) {
return null; return null;
} else { }
list($fields, $expand) = $this->getRequestedFields(); list($fields, $expand) = $this->getRequestedFields();
return $model->toArray($fields, $expand); return $model->toArray($fields, $expand);
} }
}
/** /**
* Serializes the validation errors in a model. * Serializes the validation errors in a model.

4
framework/test/ActiveFixture.php

@ -99,9 +99,9 @@ class ActiveFixture extends BaseActiveFixture
$dataFile = dirname($class->getFileName()) . '/data/' . $this->getTableSchema()->fullName . '.php'; $dataFile = dirname($class->getFileName()) . '/data/' . $this->getTableSchema()->fullName . '.php';
return is_file($dataFile) ? require($dataFile) : []; return is_file($dataFile) ? require($dataFile) : [];
} else {
return parent::getData();
} }
return parent::getData();
} }
/** /**

4
framework/test/ArrayFixture.php

@ -62,9 +62,9 @@ class ArrayFixture extends Fixture implements \IteratorAggregate, \ArrayAccess,
$dataFile = Yii::getAlias($this->dataFile); $dataFile = Yii::getAlias($this->dataFile);
if (is_file($dataFile)) { if (is_file($dataFile)) {
return require($dataFile); return require($dataFile);
} else {
throw new InvalidConfigException("Fixture data file does not exist: {$this->dataFile}");
} }
throw new InvalidConfigException("Fixture data file does not exist: {$this->dataFile}");
} }
/** /**

4
framework/test/BaseActiveFixture.php

@ -101,9 +101,9 @@ abstract class BaseActiveFixture extends DbFixture implements \IteratorAggregate
$dataFile = Yii::getAlias($this->dataFile); $dataFile = Yii::getAlias($this->dataFile);
if (is_file($dataFile)) { if (is_file($dataFile)) {
return require($dataFile); return require($dataFile);
} else {
throw new InvalidConfigException("Fixture data file does not exist: {$this->dataFile}");
} }
throw new InvalidConfigException("Fixture data file does not exist: {$this->dataFile}");
} }
/** /**

4
framework/validators/CompareValidator.php

@ -176,9 +176,9 @@ class CompareValidator extends Validator
'compareValue' => $this->compareValue, 'compareValue' => $this->compareValue,
'compareValueOrAttribute' => $this->compareValue, 'compareValueOrAttribute' => $this->compareValue,
]]; ]];
} else {
return null;
} }
return null;
} }
/** /**

9
framework/validators/DateValidator.php

@ -312,9 +312,9 @@ class DateValidator extends Validator
return [$this->tooSmall, ['min' => $this->minString]]; return [$this->tooSmall, ['min' => $this->minString]];
} elseif ($this->max !== null && $timestamp > $this->max) { } elseif ($this->max !== null && $timestamp > $this->max) {
return [$this->tooBig, ['max' => $this->maxString]]; return [$this->tooBig, ['max' => $this->maxString]];
} else {
return null;
} }
return null;
} }
/** /**
@ -346,11 +346,12 @@ class DateValidator extends Validator
} else { } else {
if (extension_loaded('intl')) { if (extension_loaded('intl')) {
return $this->parseDateValueIntl($value, $format); return $this->parseDateValueIntl($value, $format);
} else { }
// fallback to PHP if intl is not installed // fallback to PHP if intl is not installed
$format = FormatConverter::convertDateIcuToPhp($format, 'date'); $format = FormatConverter::convertDateIcuToPhp($format, 'date');
} }
}
return $this->parseDateValuePHP($value, $format); return $this->parseDateValuePHP($value, $format);
} }

8
framework/validators/EachValidator.php

@ -116,9 +116,9 @@ class EachValidator extends Validator
$model = new Model(); // mock up context model $model = new Model(); // mock up context model
} }
return Validator::createValidator($rule[0], $model, $this->attributes, array_slice($rule, 1)); return Validator::createValidator($rule[0], $model, $this->attributes, array_slice($rule, 1));
} else {
throw new InvalidConfigException('Invalid validation rule: a rule must be an array specifying validator type.');
} }
throw new InvalidConfigException('Invalid validation rule: a rule must be an array specifying validator type.');
} }
/** /**
@ -184,9 +184,9 @@ class EachValidator extends Validator
if ($this->allowMessageFromRule) { if ($this->allowMessageFromRule) {
$result[1]['value'] = $v; $result[1]['value'] = $v;
return $result; return $result;
} else {
return [$this->message, ['value' => $v]];
} }
return [$this->message, ['value' => $v]];
} }
} }

4
framework/validators/ExistValidator.php

@ -183,9 +183,9 @@ class ExistValidator extends Validator
return [$this->message, []]; return [$this->message, []];
} }
return $query->count("DISTINCT [[$this->targetAttribute]]") == count($value) ? null : [$this->message, []]; return $query->count("DISTINCT [[$this->targetAttribute]]") == count($value) ? null : [$this->message, []];
} else {
return $query->exists() ? null : [$this->message, []];
} }
return $query->exists() ? null : [$this->message, []];
} }
/** /**

4
framework/validators/InlineValidator.php

@ -84,8 +84,8 @@ class InlineValidator extends Validator
} }
return call_user_func($method, $attribute, $this->params, $this); return call_user_func($method, $attribute, $this->params, $this);
} else {
return null;
} }
return null;
} }
} }

9
framework/validators/IpValidator.php

@ -297,9 +297,9 @@ class IpValidator extends Validator
if (is_array($result)) { if (is_array($result)) {
$result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]); $result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
return $result; return $result;
} else {
return null;
} }
return null;
} }
/** /**
@ -564,7 +564,8 @@ class IpValidator extends Validator
{ {
if ($this->getIpVersion($ip) === 4) { if ($this->getIpVersion($ip) === 4) {
return str_pad(base_convert(ip2long($ip), 10, 2), static::IPV4_ADDRESS_LENGTH, '0', STR_PAD_LEFT); return str_pad(base_convert(ip2long($ip), 10, 2), static::IPV4_ADDRESS_LENGTH, '0', STR_PAD_LEFT);
} else { }
$unpack = unpack('A16', inet_pton($ip)); $unpack = unpack('A16', inet_pton($ip));
$binStr = array_shift($unpack); $binStr = array_shift($unpack);
$bytes = static::IPV6_ADDRESS_LENGTH / 8; // 128 bit / 8 = 16 bytes $bytes = static::IPV6_ADDRESS_LENGTH / 8; // 128 bit / 8 = 16 bytes
@ -572,9 +573,9 @@ class IpValidator extends Validator
while ($bytes-- > 0) { while ($bytes-- > 0) {
$result = sprintf('%08b', isset($binStr[$bytes]) ? ord($binStr[$bytes]) : '0') . $result; $result = sprintf('%08b', isset($binStr[$bytes]) ? ord($binStr[$bytes]) : '0') . $result;
} }
return $result; return $result;
} }
}
/** /**
* @inheritdoc * @inheritdoc

4
framework/validators/NumberValidator.php

@ -113,9 +113,9 @@ class NumberValidator extends Validator
return [$this->tooSmall, ['min' => $this->min]]; return [$this->tooSmall, ['min' => $this->min]];
} elseif ($this->max !== null && $value > $this->max) { } elseif ($this->max !== null && $value > $this->max) {
return [$this->tooBig, ['max' => $this->max]]; return [$this->tooBig, ['max' => $this->max]];
} else {
return null;
} }
return null;
} }
/** /**

4
framework/validators/RequiredValidator.php

@ -76,12 +76,12 @@ class RequiredValidator extends Validator
} }
if ($this->requiredValue === null) { if ($this->requiredValue === null) {
return [$this->message, []]; return [$this->message, []];
} else { }
return [$this->message, [ return [$this->message, [
'requiredValue' => $this->requiredValue, 'requiredValue' => $this->requiredValue,
]]; ]];
} }
}
/** /**
* @inheritdoc * @inheritdoc

4
framework/validators/Validator.php

@ -428,9 +428,9 @@ class Validator extends Component
{ {
if ($this->isEmpty !== null) { if ($this->isEmpty !== null) {
return call_user_func($this->isEmpty, $value); return call_user_func($this->isEmpty, $value);
} else {
return $value === null || $value === [] || $value === '';
} }
return $value === null || $value === [] || $value === '';
} }
/** /**

10
framework/web/Application.php

@ -102,14 +102,14 @@ class Application extends \yii\base\Application
$result = $this->runAction($route, $params); $result = $this->runAction($route, $params);
if ($result instanceof Response) { if ($result instanceof Response) {
return $result; return $result;
} else { }
$response = $this->getResponse(); $response = $this->getResponse();
if ($result !== null) { if ($result !== null) {
$response->data = $result; $response->data = $result;
} }
return $response; return $response;
}
} catch (InvalidRouteException $e) { } catch (InvalidRouteException $e) {
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'), $e->getCode(), $e); throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'), $e->getCode(), $e);
} }
@ -125,13 +125,13 @@ class Application extends \yii\base\Application
if ($this->_homeUrl === null) { if ($this->_homeUrl === null) {
if ($this->getUrlManager()->showScriptName) { if ($this->getUrlManager()->showScriptName) {
return $this->getRequest()->getScriptUrl(); return $this->getRequest()->getScriptUrl();
} else { }
return $this->getRequest()->getBaseUrl() . '/'; return $this->getRequest()->getBaseUrl() . '/';
} }
} else {
return $this->_homeUrl; return $this->_homeUrl;
} }
}
/** /**
* @param string $value the homepage URL * @param string $value the homepage URL

28
framework/web/AssetManager.php

@ -213,9 +213,9 @@ class AssetManager extends Component
throw new InvalidConfigException("The directory does not exist: {$this->basePath}"); throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
} elseif (!is_writable($this->basePath)) { } elseif (!is_writable($this->basePath)) {
throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}"); throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
} else {
$this->basePath = realpath($this->basePath);
} }
$this->basePath = realpath($this->basePath);
$this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/'); $this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
} }
@ -243,9 +243,9 @@ class AssetManager extends Component
return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish); return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish);
} elseif ($this->bundles[$name] === false) { } elseif ($this->bundles[$name] === false) {
return $this->loadDummyBundle($name); return $this->loadDummyBundle($name);
} else {
throw new InvalidConfigException("Invalid asset bundle configuration: $name");
} }
throw new InvalidConfigException("Invalid asset bundle configuration: $name");
} }
/** /**
@ -319,9 +319,9 @@ class AssetManager extends Component
if ($this->appendTimestamp && ($timestamp = @filemtime("$basePath/$asset")) > 0) { if ($this->appendTimestamp && ($timestamp = @filemtime("$basePath/$asset")) > 0) {
return "$baseUrl/$asset?v=$timestamp"; return "$baseUrl/$asset?v=$timestamp";
} else {
return "$baseUrl/$asset";
} }
return "$baseUrl/$asset";
} }
/** /**
@ -334,9 +334,9 @@ class AssetManager extends Component
{ {
if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) { if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
return Url::isRelative($actualAsset) ? $this->basePath . '/' . $actualAsset : false; return Url::isRelative($actualAsset) ? $this->basePath . '/' . $actualAsset : false;
} else {
return Url::isRelative($asset) ? $bundle->basePath . '/' . $asset : false;
} }
return Url::isRelative($asset) ? $bundle->basePath . '/' . $asset : false;
} }
/** /**
@ -456,9 +456,9 @@ class AssetManager extends Component
if (is_file($src)) { if (is_file($src)) {
return $this->_published[$path] = $this->publishFile($src); return $this->_published[$path] = $this->publishFile($src);
} else {
return $this->_published[$path] = $this->publishDirectory($src, $options);
} }
return $this->_published[$path] = $this->publishDirectory($src, $options);
} }
/** /**
@ -564,9 +564,9 @@ class AssetManager extends Component
} }
if (is_string($path) && ($path = realpath($path)) !== false) { if (is_string($path) && ($path = realpath($path)) !== false) {
return $this->basePath . DIRECTORY_SEPARATOR . $this->hash($path) . (is_file($path) ? DIRECTORY_SEPARATOR . basename($path) : ''); return $this->basePath . DIRECTORY_SEPARATOR . $this->hash($path) . (is_file($path) ? DIRECTORY_SEPARATOR . basename($path) : '');
} else {
return false;
} }
return false;
} }
/** /**
@ -585,9 +585,9 @@ class AssetManager extends Component
} }
if (is_string($path) && ($path = realpath($path)) !== false) { if (is_string($path) && ($path = realpath($path)) !== false) {
return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : ''); return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : '');
} else {
return false;
} }
return false;
} }
/** /**

8
framework/web/ErrorHandler.php

@ -250,9 +250,9 @@ class ErrorHandler extends \yii\base\ErrorHandler
require(Yii::getAlias($_file_)); require(Yii::getAlias($_file_));
return ob_get_clean(); return ob_get_clean();
} else {
return Yii::$app->getView()->renderFile($_file_, $_params_, $this);
} }
return Yii::$app->getView()->renderFile($_file_, $_params_, $this);
} }
/** /**
@ -265,9 +265,9 @@ class ErrorHandler extends \yii\base\ErrorHandler
{ {
if (($previous = $exception->getPrevious()) !== null) { if (($previous = $exception->getPrevious()) !== null) {
return $this->renderFile($this->previousExceptionView, ['exception' => $previous]); return $this->renderFile($this->previousExceptionView, ['exception' => $previous]);
} else {
return '';
} }
return '';
} }
/** /**

8
framework/web/GroupUrlRule.php

@ -116,9 +116,9 @@ class GroupUrlRule extends CompositeUrlRule
$pathInfo = $request->getPathInfo(); $pathInfo = $request->getPathInfo();
if ($this->prefix === '' || strpos($pathInfo . '/', $this->prefix . '/') === 0) { if ($this->prefix === '' || strpos($pathInfo . '/', $this->prefix . '/') === 0) {
return parent::parseRequest($manager, $request); return parent::parseRequest($manager, $request);
} else {
return false;
} }
return false;
} }
/** /**
@ -128,9 +128,9 @@ class GroupUrlRule extends CompositeUrlRule
{ {
if ($this->routePrefix === '' || strpos($route, $this->routePrefix . '/') === 0) { if ($this->routePrefix === '' || strpos($route, $this->routePrefix . '/') === 0) {
return parent::createUrl($manager, $route, $params); return parent::createUrl($manager, $route, $params);
} else { }
$this->createStatus = UrlRule::CREATE_STATUS_ROUTE_MISMATCH; $this->createStatus = UrlRule::CREATE_STATUS_ROUTE_MISMATCH;
return false; return false;
} }
} }
}

8
framework/web/HeaderCollection.php

@ -74,9 +74,9 @@ class HeaderCollection extends Object implements \IteratorAggregate, \ArrayAcces
$name = strtolower($name); $name = strtolower($name);
if (isset($this->_headers[$name])) { if (isset($this->_headers[$name])) {
return $first ? reset($this->_headers[$name]) : $this->_headers[$name]; return $first ? reset($this->_headers[$name]) : $this->_headers[$name];
} else {
return $default;
} }
return $default;
} }
/** /**
@ -151,9 +151,9 @@ class HeaderCollection extends Object implements \IteratorAggregate, \ArrayAcces
$value = $this->_headers[$name]; $value = $this->_headers[$name];
unset($this->_headers[$name]); unset($this->_headers[$name]);
return $value; return $value;
} else {
return null;
} }
return null;
} }
/** /**

4
framework/web/HttpException.php

@ -55,8 +55,8 @@ class HttpException extends UserException
{ {
if (isset(Response::$httpStatuses[$this->statusCode])) { if (isset(Response::$httpStatuses[$this->statusCode])) {
return Response::$httpStatuses[$this->statusCode]; return Response::$httpStatuses[$this->statusCode];
} else {
return 'Error';
} }
return 'Error';
} }
} }

4
framework/web/MultiFieldSession.php

@ -134,8 +134,8 @@ abstract class MultiFieldSession extends Session
return session_encode(); return session_encode();
} }
return $fields['data']; return $fields['data'];
} else {
return isset($fields['data']) ? $fields['data'] : '';
} }
return isset($fields['data']) ? $fields['data'] : '';
} }
} }

4
framework/web/Response.php

@ -647,9 +647,9 @@ class Response extends \yii\base\Response
} }
if ($start < 0 || $start > $end) { if ($start < 0 || $start > $end) {
return false; return false;
} else {
return [$start, $end];
} }
return [$start, $end];
} }
/** /**

12
framework/web/Session.php

@ -395,9 +395,9 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
return false; return false;
} elseif (ini_get('session.use_only_cookies') === '1') { } elseif (ini_get('session.use_only_cookies') === '1') {
return true; return true;
} else {
return null;
} }
return null;
} }
/** /**
@ -622,9 +622,9 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
unset($_SESSION[$key]); unset($_SESSION[$key]);
return $value; return $value;
} else {
return null;
} }
return null;
} }
/** /**
@ -697,9 +697,9 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
} }
return $value; return $value;
} else {
return $defaultValue;
} }
return $defaultValue;
} }
/** /**

20
framework/web/UrlManager.php

@ -308,10 +308,11 @@ class UrlManager extends Component
if ($normalized) { if ($normalized) {
// pathInfo was changed by normalizer - we need also normalize route // pathInfo was changed by normalizer - we need also normalize route
return $this->normalizer->normalizeRoute([$pathInfo, []]); return $this->normalizer->normalizeRoute([$pathInfo, []]);
} else { }
return [$pathInfo, []]; return [$pathInfo, []];
} }
} else {
Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__); Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
$route = $request->getQueryParam($this->routeParam, ''); $route = $request->getQueryParam($this->routeParam, '');
if (is_array($route)) { if (is_array($route)) {
@ -320,7 +321,6 @@ class UrlManager extends Component
return [(string) $route, []]; return [(string) $route, []];
} }
}
/** /**
* Creates a URL using the given route and query parameters. * Creates a URL using the given route and query parameters.
@ -393,20 +393,20 @@ class UrlManager extends Component
if (strpos($url, '://') !== false) { if (strpos($url, '://') !== false) {
if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) { if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor; return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
} else {
return $url . $baseUrl . $anchor;
} }
return $url . $baseUrl . $anchor;
} elseif (strpos($url, '//') === 0) { } elseif (strpos($url, '//') === 0) {
if ($baseUrl !== '' && ($pos = strpos($url, '/', 2)) !== false) { if ($baseUrl !== '' && ($pos = strpos($url, '/', 2)) !== false) {
return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor; return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
} else { }
return $url . $baseUrl . $anchor; return $url . $baseUrl . $anchor;
} }
} else {
$url = ltrim($url, '/'); $url = ltrim($url, '/');
return "$baseUrl/{$url}{$anchor}"; return "$baseUrl/{$url}{$anchor}";
} }
}
if ($this->suffix !== null) { if ($this->suffix !== null) {
$route .= $this->suffix; $route .= $this->suffix;
@ -417,7 +417,8 @@ class UrlManager extends Component
$route = ltrim($route, '/'); $route = ltrim($route, '/');
return "$baseUrl/{$route}{$anchor}"; return "$baseUrl/{$route}{$anchor}";
} else { }
$url = "$baseUrl?{$this->routeParam}=" . urlencode($route); $url = "$baseUrl?{$this->routeParam}=" . urlencode($route);
if (!empty($params) && ($query = http_build_query($params)) !== '') { if (!empty($params) && ($query = http_build_query($params)) !== '') {
$url .= '&' . $query; $url .= '&' . $query;
@ -425,7 +426,6 @@ class UrlManager extends Component
return $url . $anchor; return $url . $anchor;
} }
}
/** /**
* Returns the value indicating whether result of [[createUrl()]] of rule should be cached in internal cache. * Returns the value indicating whether result of [[createUrl()]] of rule should be cached in internal cache.

8
framework/web/UrlRule.php

@ -353,9 +353,9 @@ class UrlRule extends Object implements UrlRuleInterface
{ {
if ($this->normalizer === null) { if ($this->normalizer === null) {
return $manager->normalizer; return $manager->normalizer;
} else {
return $this->normalizer;
} }
return $this->normalizer;
} }
/** /**
@ -439,9 +439,9 @@ class UrlRule extends Object implements UrlRuleInterface
if ($normalized) { if ($normalized) {
// pathInfo was changed by normalizer - we need also normalize route // pathInfo was changed by normalizer - we need also normalize route
return $this->getNormalizer($manager)->normalizeRoute([$route, $params]); return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
} else {
return [$route, $params];
} }
return [$route, $params];
} }
/** /**

8
framework/web/User.php

@ -271,9 +271,9 @@ class User extends Component
$identity = $class::findIdentityByAccessToken($token, $type); $identity = $class::findIdentityByAccessToken($token, $type);
if ($identity && $this->login($identity)) { if ($identity && $this->login($identity)) {
return $identity; return $identity;
} else {
return null;
} }
return null;
} }
/** /**
@ -363,9 +363,9 @@ class User extends Component
if (is_array($url)) { if (is_array($url)) {
if (isset($url[0])) { if (isset($url[0])) {
return Yii::$app->getUrlManager()->createUrl($url); return Yii::$app->getUrlManager()->createUrl($url);
} else {
$url = null;
} }
$url = null;
} }
return $url === null ? Yii::$app->getHomeUrl() : $url; return $url === null ? Yii::$app->getHomeUrl() : $url;

8
framework/web/ViewAction.php

@ -87,12 +87,12 @@ class ViewAction extends Action
if (YII_DEBUG) { if (YII_DEBUG) {
throw new NotFoundHttpException($e->getMessage()); throw new NotFoundHttpException($e->getMessage());
} else { }
throw new NotFoundHttpException( throw new NotFoundHttpException(
Yii::t('yii', 'The requested view "{name}" was not found.', ['name' => $viewName]) Yii::t('yii', 'The requested view "{name}" was not found.', ['name' => $viewName])
); );
} }
}
return $output; return $output;
} }
@ -121,9 +121,9 @@ class ViewAction extends Action
if (!is_string($viewName) || !preg_match('~^\w(?:(?!\/\.{0,2}\/)[\w\/\-\.])*$~', $viewName)) { if (!is_string($viewName) || !preg_match('~^\w(?:(?!\/\.{0,2}\/)[\w\/\-\.])*$~', $viewName)) {
if (YII_DEBUG) { if (YII_DEBUG) {
throw new NotFoundHttpException("The requested view \"$viewName\" must start with a word character, must not contain /../ or /./, can contain only word characters, forward slashes, dots and dashes."); throw new NotFoundHttpException("The requested view \"$viewName\" must start with a word character, must not contain /../ or /./, can contain only word characters, forward slashes, dots and dashes.");
} else {
throw new NotFoundHttpException(Yii::t('yii', 'The requested view "{name}" was not found.', ['name' => $viewName]));
} }
throw new NotFoundHttpException(Yii::t('yii', 'The requested view "{name}" was not found.', ['name' => $viewName]));
} }
return empty($this->viewPrefix) ? $viewName : $this->viewPrefix . '/' . $viewName; return empty($this->viewPrefix) ? $viewName : $this->viewPrefix . '/' . $viewName;

4
framework/widgets/ActiveForm.php

@ -342,9 +342,9 @@ class ActiveForm extends Widget
$field = array_pop($this->_fields); $field = array_pop($this->_fields);
if ($field instanceof ActiveField) { if ($field instanceof ActiveField) {
return $field->end(); return $field->end();
} else {
throw new InvalidCallException('Mismatching endField() call.');
} }
throw new InvalidCallException('Mismatching endField() call.');
} }
/** /**

4
framework/widgets/DetailView.php

@ -179,9 +179,9 @@ class DetailView extends Widget
'{captionOptions}' => $captionOptions, '{captionOptions}' => $captionOptions,
'{contentOptions}' => $contentOptions, '{contentOptions}' => $contentOptions,
]); ]);
} else {
return call_user_func($this->template, $attribute, $index, $this);
} }
return call_user_func($this->template, $attribute, $index, $this);
} }
/** /**

4
framework/widgets/Menu.php

@ -238,14 +238,14 @@ class Menu extends Widget
'{url}' => Html::encode(Url::to($item['url'])), '{url}' => Html::encode(Url::to($item['url'])),
'{label}' => $item['label'], '{label}' => $item['label'],
]); ]);
} else { }
$template = ArrayHelper::getValue($item, 'template', $this->labelTemplate); $template = ArrayHelper::getValue($item, 'template', $this->labelTemplate);
return strtr($template, [ return strtr($template, [
'{label}' => $item['label'], '{label}' => $item['label'],
]); ]);
} }
}
/** /**
* Normalizes the [[items]] property to remove invisible items and activate certain items. * Normalizes the [[items]] property to remove invisible items and activate certain items.

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save