Browse Source

Merge pull request #3138 from thiagotalma/inspections

Correction of many warnings code inspection.
tags/2.0.0-rc
Qiang Xue 11 years ago
parent
commit
e5f9edbfaf
  1. 2
      framework/base/ArrayAccessTrait.php
  2. 2
      framework/base/ErrorHandler.php
  3. 4
      framework/base/Formatter.php
  4. 1
      framework/base/Theme.php
  5. 23
      framework/caching/MemCache.php
  6. 12
      framework/captcha/CaptchaAction.php
  7. 10
      framework/console/controllers/FixtureController.php
  8. 7
      framework/console/controllers/MessageController.php
  9. 3
      framework/console/controllers/MigrateController.php
  10. 1
      framework/db/ActiveQueryTrait.php
  11. 12
      framework/db/ActiveRelationTrait.php
  12. 4
      framework/db/BaseActiveRecord.php
  13. 7
      framework/db/Connection.php
  14. 2
      framework/di/Container.php
  15. 3
      framework/grid/DataColumn.php
  16. 1
      framework/helpers/BaseConsole.php
  17. 12
      framework/helpers/BaseInflector.php
  18. 3
      framework/i18n/MessageFormatter.php
  19. 4
      framework/log/SyslogTarget.php
  20. 27
      framework/validators/CompareValidator.php
  21. 18
      framework/views/errorHandler/error.php
  22. 24
      framework/web/JsonResponseFormatter.php
  23. 2
      framework/web/ViewAction.php
  24. 4
      framework/yii

2
framework/base/ArrayAccessTrait.php

@ -15,6 +15,8 @@ namespace yii\base;
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*
* @property array $data
*/ */
trait ArrayAccessTrait trait ArrayAccessTrait
{ {

2
framework/base/ErrorHandler.php

@ -176,7 +176,7 @@ abstract class ErrorHandler extends Component
* Renders the exception. * Renders the exception.
* @param \Exception $exception the exception to be rendered. * @param \Exception $exception the exception to be rendered.
*/ */
protected abstract function renderException($exception); abstract protected function renderException($exception);
/** /**
* Logs the given exception * Logs the given exception

4
framework/base/Formatter.php

@ -184,9 +184,7 @@ class Formatter extends Component
return $this->nullDisplay; return $this->nullDisplay;
} }
return str_replace('<p></p>', '', return str_replace('<p></p>', '', '<p>' . preg_replace('/[\r\n]{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>');
'<p>' . preg_replace('/[\r\n]{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>'
);
} }
/** /**

1
framework/base/Theme.php

@ -181,6 +181,7 @@ class Theme extends Component
* Converts a relative file path into an absolute one using [[basePath]]. * Converts a relative file path into an absolute one using [[basePath]].
* @param string $path the relative file path to be converted. * @param string $path the relative file path to be converted.
* @return string the absolute file path * @return string the absolute file path
* @throws InvalidConfigException if [[baseUrl]] is not set
*/ */
public function getPath($path) public function getPath($path)
{ {

23
framework/caching/MemCache.php

@ -107,15 +107,26 @@ class MemCache extends Cache
$timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0); $timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0);
if ($paramCount === 9) { if ($paramCount === 9) {
$cache->addServer( $cache->addServer(
$server->host, $server->port, $server->persistent, $server->host,
$server->weight, $timeout, $server->retryInterval, $server->port,
$server->status, $server->failureCallback, $server->timeout $server->persistent,
$server->weight,
$timeout,
$server->retryInterval,
$server->status,
$server->failureCallback,
$server->timeout
); );
} else { } else {
$cache->addServer( $cache->addServer(
$server->host, $server->port, $server->persistent, $server->host,
$server->weight, $timeout, $server->retryInterval, $server->port,
$server->status, $server->failureCallback $server->persistent,
$server->weight,
$timeout,
$server->retryInterval,
$server->status,
$server->failureCallback
); );
} }
} }

12
framework/captcha/CaptchaAction.php

@ -252,10 +252,12 @@ class CaptchaAction extends Action
{ {
$image = imagecreatetruecolor($this->width, $this->height); $image = imagecreatetruecolor($this->width, $this->height);
$backColor = imagecolorallocate($image, $backColor = imagecolorallocate(
$image,
(int) ($this->backColor % 0x1000000 / 0x10000), (int) ($this->backColor % 0x1000000 / 0x10000),
(int) ($this->backColor % 0x10000 / 0x100), (int) ($this->backColor % 0x10000 / 0x100),
$this->backColor % 0x100); $this->backColor % 0x100
);
imagefilledrectangle($image, 0, 0, $this->width, $this->height, $backColor); imagefilledrectangle($image, 0, 0, $this->width, $this->height, $backColor);
imagecolordeallocate($image, $backColor); imagecolordeallocate($image, $backColor);
@ -263,10 +265,12 @@ class CaptchaAction extends Action
imagecolortransparent($image, $backColor); imagecolortransparent($image, $backColor);
} }
$foreColor = imagecolorallocate($image, $foreColor = imagecolorallocate(
$image,
(int) ($this->foreColor % 0x1000000 / 0x10000), (int) ($this->foreColor % 0x1000000 / 0x10000),
(int) ($this->foreColor % 0x10000 / 0x100), (int) ($this->foreColor % 0x10000 / 0x100),
$this->foreColor % 0x100); $this->foreColor % 0x100
);
$length = strlen($code); $length = strlen($code);
$box = imagettfbbox(30, 0, $this->fontFile, $code); $box = imagettfbbox(30, 0, $this->fontFile, $code);

10
framework/console/controllers/FixtureController.php

@ -89,8 +89,9 @@ class FixtureController extends Controller
} }
if (!$foundFixtures) { if (!$foundFixtures) {
throw new Exception("No files were found by name: \"" . implode(', ', $fixtures) . "\".\n" throw new Exception(
. "Check that files with these name exists, under fixtures path: \n\"" . $this->getFixturePath() . "\"." "No files were found by name: \"" . implode(', ', $fixtures) . "\".\n" .
"Check that files with these name exists, under fixtures path: \n\"" . $this->getFixturePath() . "\"."
); );
} }
@ -131,8 +132,9 @@ class FixtureController extends Controller
} }
if (!$foundFixtures) { if (!$foundFixtures) {
throw new Exception("No files were found by name: \"" . implode(', ', $fixtures) . "\".\n" throw new Exception(
. "Check that fixtures with these name exists, under fixtures path: \n\"" . $this->getFixturePath() . "\"." "No files were found by name: \"" . implode(', ', $fixtures) . "\".\n" .
"Check that fixtures with these name exists, under fixtures path: \n\"" . $this->getFixturePath() . "\"."
); );
} }

7
framework/console/controllers/MessageController.php

@ -221,7 +221,7 @@ class MessageController extends Controller
} else { } else {
$last_id = $db->getLastInsertID(); $last_id = $db->getLastInsertID();
$db->createCommand() $db->createCommand()
->update( ->update(
$sourceMessageTable, $sourceMessageTable,
['message' => new \yii\db\Expression("CONCAT('@@',message,'@@')")], ['message' => new \yii\db\Expression("CONCAT('@@',message,'@@')")],
['in', 'id', $obsolete] ['in', 'id', $obsolete]
@ -253,7 +253,10 @@ class MessageController extends Controller
foreach ($translator as $currentTranslator) { foreach ($translator as $currentTranslator) {
$n = preg_match_all( $n = preg_match_all(
'/\b' . $currentTranslator . '\s*\(\s*(\'.*?(?<!\\\\)\'|".*?(?<!\\\\)")\s*,\s*(\'.*?(?<!\\\\)\'|".*?(?<!\\\\)")\s*[,\)]/s', '/\b' . $currentTranslator . '\s*\(\s*(\'.*?(?<!\\\\)\'|".*?(?<!\\\\)")\s*,\s*(\'.*?(?<!\\\\)\'|".*?(?<!\\\\)")\s*[,\)]/s',
$subject, $matches, PREG_SET_ORDER); $subject,
$matches,
PREG_SET_ORDER
);
for ($i = 0; $i < $n; ++$i) { for ($i = 0; $i < $n; ++$i) {
if (($pos = strpos($matches[$i][1], '.')) !== false) { if (($pos = strpos($matches[$i][1], '.')) !== false) {
$category = substr($matches[$i][1], $pos + 1, -1); $category = substr($matches[$i][1], $pos + 1, -1);

3
framework/console/controllers/MigrateController.php

@ -95,7 +95,8 @@ class MigrateController extends Controller
*/ */
public function options($actionId) public function options($actionId)
{ {
return array_merge(parent::options($actionId), return array_merge(
parent::options($actionId),
['migrationPath', 'migrationTable', 'db'], // global for all actions ['migrationPath', 'migrationTable', 'db'], // global for all actions
($actionId == 'create') ? ['templateFile'] : [] // action create ($actionId == 'create') ? ['templateFile'] : [] // action create
); );

1
framework/db/ActiveQueryTrait.php

@ -159,6 +159,7 @@ trait ActiveQueryTrait
{ {
$primaryModel = new $this->modelClass; $primaryModel = new $this->modelClass;
$relations = $this->normalizeRelations($primaryModel, $with); $relations = $this->normalizeRelations($primaryModel, $with);
/** @var ActiveQuery $relation */
foreach ($relations as $name => $relation) { foreach ($relations as $name => $relation) {
if ($relation->asArray === null) { if ($relation->asArray === null) {
// inherit asArray from primary query // inherit asArray from primary query

12
framework/db/ActiveRelationTrait.php

@ -16,6 +16,10 @@ use yii\base\InvalidParamException;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @author Carsten Brandt <mail@cebe.cc> * @author Carsten Brandt <mail@cebe.cc>
* @since 2.0 * @since 2.0
*
* @method ActiveRelationTrait one()
* @method ActiveRelationTrait[] all()
* @property ActiveRecord $modelClass
*/ */
trait ActiveRelationTrait trait ActiveRelationTrait
{ {
@ -248,12 +252,20 @@ trait ActiveRelationTrait
} }
} }
/**
* @param ActiveRecordInterface[] $primaryModels primary models
* @param ActiveRecordInterface[] $models models
* @param string $primaryName the primary relation name
* @param string $name the relation name
* @return null
*/
private function populateInverseRelation(&$primaryModels, $models, $primaryName, $name) private function populateInverseRelation(&$primaryModels, $models, $primaryName, $name)
{ {
if (empty($models) || empty($primaryModels)) { if (empty($models) || empty($primaryModels)) {
return; return;
} }
$model = reset($models); $model = reset($models);
/** @var ActiveQueryInterface|ActiveQuery $relation */
$relation = $model instanceof ActiveRecordInterface ? $model->getRelation($name) : (new $this->modelClass)->getRelation($name); $relation = $model instanceof ActiveRecordInterface ? $model->getRelation($name) : (new $this->modelClass)->getRelation($name);
if ($relation->multiple) { if ($relation->multiple) {

4
framework/db/BaseActiveRecord.php

@ -145,6 +145,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL. * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter. * Please refer to [[Query::where()]] on how to specify this parameter.
* @return integer the number of rows updated * @return integer the number of rows updated
* @throws NotSupportedException if not overrided
*/ */
public static function updateAll($attributes, $condition = '') public static function updateAll($attributes, $condition = '')
{ {
@ -164,6 +165,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL. * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter. * Please refer to [[Query::where()]] on how to specify this parameter.
* @return integer the number of rows updated * @return integer the number of rows updated
* @throws NotSupportedException if not overrided
*/ */
public static function updateAllCounters($counters, $condition = '') public static function updateAllCounters($counters, $condition = '')
{ {
@ -184,6 +186,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
* Please refer to [[Query::where()]] on how to specify this parameter. * Please refer to [[Query::where()]] on how to specify this parameter.
* @param array $params the parameters (name => value) to be bound to the query. * @param array $params the parameters (name => value) to be bound to the query.
* @return integer the number of rows deleted * @return integer the number of rows deleted
* @throws NotSupportedException if not overrided
*/ */
public static function deleteAll($condition = '', $params = []) public static function deleteAll($condition = '', $params = [])
{ {
@ -908,6 +911,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
*/ */
public function refresh() public function refresh()
{ {
/** @var ActiveQuery $record */
$record = $this->findOne($this->getPrimaryKey(true)); $record = $this->findOne($this->getPrimaryKey(true));
if ($record === null) { if ($record === null) {
return false; return false;

7
framework/db/Connection.php

@ -528,14 +528,17 @@ class Connection extends Component
*/ */
public function quoteSql($sql) public function quoteSql($sql)
{ {
return preg_replace_callback('/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/', return preg_replace_callback(
'/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
function ($matches) { function ($matches) {
if (isset($matches[3])) { if (isset($matches[3])) {
return $this->quoteColumnName($matches[3]); return $this->quoteColumnName($matches[3]);
} else { } else {
return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2])); return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
} }
}, $sql); },
$sql
);
} }
/** /**

2
framework/di/Container.php

@ -263,7 +263,7 @@ class Container extends Component
*/ */
public function setSingleton($class, $definition = [], array $params = []) public function setSingleton($class, $definition = [], array $params = [])
{ {
$this->_definitions[$class] = $this->normalizeDefinition($class, $definition);; $this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
$this->_params[$class] = $params; $this->_params[$class] = $params;
$this->_singletons[$class] = null; $this->_singletons[$class] = null;
return $this; return $this;

3
framework/grid/DataColumn.php

@ -142,8 +142,7 @@ class DataColumn extends Column
if (is_string($this->filter)) { if (is_string($this->filter)) {
return $this->filter; return $this->filter;
} elseif ($this->filter !== false && $this->grid->filterModel instanceof Model && } elseif ($this->filter !== false && $this->grid->filterModel instanceof Model &&
$this->attribute !== null && $this->grid->filterModel->isAttributeActive($this->attribute)) $this->attribute !== null && $this->grid->filterModel->isAttributeActive($this->attribute)) {
{
if (is_array($this->filter)) { if (is_array($this->filter)) {
$options = array_merge(['prompt' => ''], $this->filterInputOptions); $options = array_merge(['prompt' => ''], $this->filterInputOptions);
return Html::activeDropDownList($this->grid->filterModel, $this->attribute, $this->filter, $options); return Html::activeDropDownList($this->grid->filterModel, $this->attribute, $this->filter, $options);

1
framework/helpers/BaseConsole.php

@ -341,6 +341,7 @@ class BaseConsole
function ($ansi) use (&$tags) { function ($ansi) use (&$tags) {
$styleA = []; $styleA = [];
foreach (explode(';', $ansi) as $controlCode) { foreach (explode(';', $ansi) as $controlCode) {
$style = [];
switch ($controlCode) { switch ($controlCode) {
case self::FG_BLACK: case self::FG_BLACK:
$style = ['color' => '#000000']; $style = ['color' => '#000000'];

12
framework/helpers/BaseInflector.php

@ -500,10 +500,14 @@ class BaseInflector
return $number . 'th'; return $number . 'th';
} }
switch ($number % 10) { switch ($number % 10) {
case 1: return $number . 'st'; case 1:
case 2: return $number . 'nd'; return $number . 'st';
case 3: return $number . 'rd'; case 2:
default: return $number . 'th'; return $number . 'nd';
case 3:
return $number . 'rd';
default:
return $number . 'th';
} }
} }
} }

3
framework/i18n/MessageFormatter.php

@ -344,7 +344,8 @@ class MessageFormatter extends Component
return $arg; return $arg;
} }
throw new NotSupportedException("Message format 'number' is only supported for integer values. You have to install PHP intl extension to use this feature."); throw new NotSupportedException("Message format 'number' is only supported for integer values. You have to install PHP intl extension to use this feature.");
case 'none': return $arg; case 'none':
return $arg;
case 'select': case 'select':
/* http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html /* http://icu-project.org/apiref/icu4c/classicu_1_1SelectFormat.html
selectStyle = (selector '{' message '}')+ selectStyle = (selector '{' message '}')+

4
framework/log/SyslogTarget.php

@ -29,7 +29,7 @@ class SyslogTarget extends Target
/** /**
* @var array syslog levels * @var array syslog levels
*/ */
private $syslogLevels = [ private $_syslogLevels = [
Logger::LEVEL_TRACE => LOG_DEBUG, Logger::LEVEL_TRACE => LOG_DEBUG,
Logger::LEVEL_PROFILE_BEGIN => LOG_DEBUG, Logger::LEVEL_PROFILE_BEGIN => LOG_DEBUG,
Logger::LEVEL_PROFILE_END => LOG_DEBUG, Logger::LEVEL_PROFILE_END => LOG_DEBUG,
@ -45,7 +45,7 @@ class SyslogTarget extends Target
{ {
openlog($this->identity, LOG_ODELAY | LOG_PID, $this->facility); openlog($this->identity, LOG_ODELAY | LOG_PID, $this->facility);
foreach ($this->messages as $message) { foreach ($this->messages as $message) {
syslog($this->syslogLevels[$message[1]], $this->formatMessage($message)); syslog($this->_syslogLevels[$message[1]], $this->formatMessage($message));
} }
closelog(); closelog();
} }

27
framework/validators/CompareValidator.php

@ -161,15 +161,24 @@ class CompareValidator extends Validator
protected function compareValues($operator, $value, $compareValue) protected function compareValues($operator, $value, $compareValue)
{ {
switch ($operator) { switch ($operator) {
case '==': return $value == $compareValue; case '==':
case '===': return $value === $compareValue; return $value == $compareValue;
case '!=': return $value != $compareValue; case '===':
case '!==': return $value !== $compareValue; return $value === $compareValue;
case '>': return $value > $compareValue; case '!=':
case '>=': return $value >= $compareValue; return $value != $compareValue;
case '<': return $value < $compareValue; case '!==':
case '<=': return $value <= $compareValue; return $value !== $compareValue;
default: return false; case '>':
return $value > $compareValue;
case '>=':
return $value >= $compareValue;
case '<':
return $value < $compareValue;
case '<=':
return $value <= $compareValue;
default:
return false;
} }
} }

18
framework/views/errorHandler/error.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* @var \Exception $exception * @var \yii\web\HttpException|\Exception $exception
* @var \yii\web\ErrorHandler $handler * @var \yii\web\ErrorHandler $handler
*/ */
if ($exception instanceof \yii\web\HttpException) { if ($exception instanceof \yii\web\HttpException) {
@ -22,8 +22,11 @@ if ($exception instanceof \yii\base\UserException) {
} else { } else {
$message = 'An internal server error occurred.'; $message = 'An internal server error occurred.';
} }
if (method_exists($this, 'beginPage')) {
$this->beginPage();
}
?> ?>
<?php if (method_exists($this, 'beginPage')) $this->beginPage(); ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
@ -80,7 +83,14 @@ if ($exception instanceof \yii\base\UserException) {
<div class="version"> <div class="version">
<?= date('Y-m-d H:i:s', time()) ?> <?= date('Y-m-d H:i:s', time()) ?>
</div> </div>
<?php if (method_exists($this, 'endBody')) $this->endBody(); // to allow injecting code into body (mostly by Yii Debug Toolbar) ?> <?php
if (method_exists($this, 'endBody')) {
$this->endBody(); // to allow injecting code into body (mostly by Yii Debug Toolbar)
}
?>
</body> </body>
</html> </html>
<?php if (method_exists($this, 'endPage')) $this->endPage(); ?> <?php
if (method_exists($this, 'endPage')) {
$this->endPage();
}

24
framework/web/JsonResponseFormatter.php

@ -28,18 +28,18 @@ class JsonResponseFormatter extends Component implements ResponseFormatterInterf
*/ */
public $useJsonp = false; public $useJsonp = false;
/** /**
* Formats the specified response. * Formats the specified response.
* @param Response $response the response to be formatted. * @param Response $response the response to be formatted.
*/ */
public function format($response) public function format($response)
{ {
if ($this->useJsonp) { if ($this->useJsonp) {
$this->formatJsonp($response); $this->formatJsonp($response);
} else { } else {
$this->formatJson($response); $this->formatJson($response);
} }
} }
/** /**
* Formats response data in JSON format. * Formats response data in JSON format.

2
framework/web/ViewAction.php

@ -70,7 +70,7 @@ class ViewAction extends Action
$viewName = $this->resolveViewName(); $viewName = $this->resolveViewName();
$controllerLayout = null; $controllerLayout = null;
if($this->layout !== null) { if ($this->layout !== null) {
$controllerLayout = $this->controller->layout; $controllerLayout = $this->controller->layout;
$this->controller->layout = $this->layout; $this->controller->layout = $this->layout;
} }

4
framework/yii

@ -17,8 +17,8 @@ defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
require(__DIR__ . '/Yii.php'); require(__DIR__ . '/Yii.php');
$application = new yii\console\Application([ $application = new yii\console\Application([
'id' => 'yii-console', 'id' => 'yii-console',
'basePath' => __DIR__ . '/console', 'basePath' => __DIR__ . '/console',
]); ]);
$exitCode = $application->run(); $exitCode = $application->run();
exit($exitCode); exit($exitCode);

Loading…
Cancel
Save