Skip to content

Commit

Permalink
PHP type casting
Browse files Browse the repository at this point in the history
  • Loading branch information
mohorev committed Oct 25, 2014
1 parent bfb6216 commit bb85508
Show file tree
Hide file tree
Showing 27 changed files with 43 additions and 43 deletions.
6 changes: 3 additions & 3 deletions docs/internals/core-code-style.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,14 +269,14 @@ Use the following formatting for switch:
```php
switch ($this->phpType) {
case 'string':
$a = (string)$value;
$a = (string) $value;
break;
case 'integer':
case 'int':
$a = (integer)$value;
$a = (int) $value;
break;
case 'boolean':
$a = (boolean)$value;
$a = (bool) $value;
break;
default:
$a = null;
Expand Down
2 changes: 1 addition & 1 deletion extensions/bootstrap/ActiveField.php
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ public function label($label = null, $options = [])
*/
public function inline($value = true)
{
$this->inline = (bool)$value;
$this->inline = (bool) $value;
return $this;
}

Expand Down
2 changes: 1 addition & 1 deletion extensions/debug/LogTarget.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ protected function collectSummary()
$summary = [
'tag' => $this->tag,
'url' => $request->getAbsoluteUrl(),
'ajax' => (int)$request->getIsAjax(),
'ajax' => (int) $request->getIsAjax(),
'method' => $request->getMethod(),
'ip' => $request->getUserIP(),
'time' => time(),
Expand Down
2 changes: 1 addition & 1 deletion extensions/gii/console/GenerateAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ protected function generateCode()
return;
}

if ($this->generator->save($files, (array)$answers, $results)) {
if ($this->generator->save($files, (array) $answers, $results)) {
$this->controller->stdout("\nFiles were generated successfully!\n", Console::FG_GREEN);
} else {
$this->controller->stdout("\nSome errors occurred while generating the files.", Console::FG_RED);
Expand Down
4 changes: 2 additions & 2 deletions extensions/mongodb/Migration.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public function dropCollection($collection)
*/
public function createIndex($collection, $columns, $options = [])
{
echo " > create index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array)$columns) . empty($options) ? "" : ", " . Json::encode($options) . ") ...";
echo " > create index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array) $columns) . empty($options) ? "" : ", " . Json::encode($options) . ") ...";
$time = microtime(true);
$this->db->getCollection($collection)->createIndex($columns, $options);
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
Expand All @@ -102,7 +102,7 @@ public function createIndex($collection, $columns, $options = [])
*/
public function dropIndex($collection, $columns)
{
echo " > drop index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array)$columns) . ") ...";
echo " > drop index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array) $columns) . ") ...";
$time = microtime(true);
$this->db->getCollection($collection)->dropIndex($columns);
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
Expand Down
4 changes: 2 additions & 2 deletions extensions/mongodb/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ To get actual Mongo ID string your should typecast [[\MongoId]] instance to stri
$query = new Query;
$row = $query->from('customer')->one();
var_dump($row['_id']); // outputs: "object(MongoId)"
var_dump((string)$row['_id']); // outputs "string 'acdfgdacdhcbdafa'"
var_dump((string) $row['_id']); // outputs "string 'acdfgdacdhcbdafa'"
```

Although this fact is very useful sometimes, it often produces some problems.
Expand All @@ -90,7 +90,7 @@ In these cases, ensure you have converted [[\MongoId]] into the string:

```php
/* @var $this yii\web\View */
echo $this->createUrl(['item/update', 'id' => (string)$row['_id']]);
echo $this->createUrl(['item/update', 'id' => (string) $row['_id']]);
```

While building condition, values for the key '_id' will be automatically cast to [[\MongoId]] instance,
Expand Down
4 changes: 2 additions & 2 deletions extensions/redis/ActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public function insert($runValidation = true, $attributes = null)
// only insert attributes that are not null
if ($value !== null) {
if (is_bool($value)) {
$value = (int)$value;
$value = (int) $value;
}
$setArgs[] = $attribute;
$setArgs[] = $value;
Expand Down Expand Up @@ -175,7 +175,7 @@ public static function updateAll($attributes, $condition = null)
}
if ($value !== null) {
if (is_bool($value)) {
$value = (int)$value;
$value = (int) $value;
}
$setArgs[] = $attribute;
$setArgs[] = $value;
Expand Down
2 changes: 1 addition & 1 deletion extensions/redis/LuaScriptBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ private function buildHashCondition($condition, &$columns)
$parts[] = $this->buildInCondition('in', [$column, $value], $columns);
} else {
if (is_bool($value)) {
$value = (int)$value;
$value = (int) $value;
}
if ($value === null) {
$parts[] = "redis.call('HEXISTS',key .. ':a:' .. pk, ".$this->quoteValue($column).")==0";
Expand Down
4 changes: 2 additions & 2 deletions extensions/sphinx/ColumnSchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ public function phpTypecast($value)
case 'string':
return is_resource($value) ? $value : (string) $value;
case 'integer':
return (integer) $value;
return (int) $value;
case 'boolean':
return (boolean) $value;
return (bool) $value;
case 'double':
return (double) $value;
}
Expand Down
2 changes: 1 addition & 1 deletion extensions/sphinx/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -822,7 +822,7 @@ public function buildInCondition($indexes, $operator, $operands, &$params)
if ($values instanceof Query) {
// sub-query
list($sql, $params) = $this->build($values, $params);
$column = (array)$column;
$column = (array) $column;
if (is_array($column)) {
foreach ($column as $i => $col) {
if (strpos($col, '(') === false) {
Expand Down
2 changes: 1 addition & 1 deletion extensions/twig/Extension.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public function resolveClassName($className)

public function addUses($args)
{
foreach ((array)$args as $key => $value) {
foreach ((array) $args as $key => $value) {
$value = str_replace('/', '\\', $value);
if (is_int($key)) {
// namespace or class import
Expand Down
2 changes: 1 addition & 1 deletion framework/base/Security.php
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ public function validatePassword($password, $hash)
*/
protected function generateSalt($cost = 13)
{
$cost = (int)$cost;
$cost = (int) $cost;
if ($cost < 4 || $cost > 31) {
throw new InvalidParamException('Cost must be between 4 and 31.');
}
Expand Down
2 changes: 1 addition & 1 deletion framework/behaviors/SluggableBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ protected function getValue($event)
$isNewSlug = true;

if ($this->attribute !== null) {
$attributes = (array)$this->attribute;
$attributes = (array) $this->attribute;
/* @var $owner BaseActiveRecord */
$owner = $this->owner;
if (!$owner->getIsNewRecord() && !empty($owner->{$this->slugAttribute})) {
Expand Down
2 changes: 1 addition & 1 deletion framework/caching/TagDependency.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public function getHasChanged($cache)
public static function invalidate($cache, $tags)
{
$keys = [];
foreach ((array)$tags as $tag) {
foreach ((array) $tags as $tag) {
$keys[] = $cache->buildKey([__CLASS__, $tag]);
}
static::touchKeys($cache, $keys);
Expand Down
2 changes: 1 addition & 1 deletion framework/db/ActiveQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public function prepare($builder)
}

if (empty($this->select) && !empty($this->join)) {
foreach ((array)$this->from as $alias => $table) {
foreach ((array) $this->from as $alias => $table) {
if (is_string($alias)) {
$this->select = ["$alias.*"];
} elseif (is_string($table)) {
Expand Down
4 changes: 2 additions & 2 deletions framework/db/ColumnSchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@ public function phpTypecast($value)
case 'string':
return is_resource($value) ? $value : (string) $value;
case 'integer':
return (integer) $value;
return (int) $value;
case 'boolean':
return (boolean) $value;
return (bool) $value;
case 'double':
return (double) $value;
}
Expand Down
2 changes: 1 addition & 1 deletion framework/db/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ public function open()
Yii::endProfile($token, __METHOD__);
} catch (\PDOException $e) {
Yii::endProfile($token, __METHOD__);
throw new Exception($e->getMessage(), $e->errorInfo, (int)$e->getCode(), $e);
throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
}
}

Expand Down
4 changes: 2 additions & 2 deletions framework/db/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ public function buildJoin($joins, &$params)
}
// 0:join type, 1:join table, 2:on-condition (optional)
list ($joinType, $table) = $join;
$tables = $this->quoteTableNames((array)$table, $params);
$tables = $this->quoteTableNames((array) $table, $params);
$table = reset($tables);
$joins[$i] = "$joinType $table";
if (isset($join[2])) {
Expand Down Expand Up @@ -1055,7 +1055,7 @@ public function buildInCondition($operator, $operands, &$params)
if ($values instanceof Query) {
// sub-query
list($sql, $params) = $this->build($values, $params);
$column = (array)$column;
$column = (array) $column;
if (is_array($column)) {
foreach ($column as $i => $col) {
if (strpos($col, '(') === false) {
Expand Down
2 changes: 1 addition & 1 deletion framework/db/pgsql/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ protected function loadColumnSchema($info)
$column->name = $info['column_name'];
$column->precision = $info['numeric_precision'];
$column->scale = $info['numeric_scale'];
$column->size = $info['size'] === null ? null : (int)$info['size'];
$column->size = $info['size'] === null ? null : (int) $info['size'];
if (isset($this->typeMap[$column->dbType])) {
$column->type = $this->typeMap[$column->dbType];
} else {
Expand Down
2 changes: 1 addition & 1 deletion framework/db/sqlite/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public function resetSequence($tableName, $value = null)
*/
public function checkIntegrity($check = true, $schema = '', $table = '')
{
return 'PRAGMA foreign_keys='.(int)$check;
return 'PRAGMA foreign_keys='.(int) $check;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion framework/grid/GridView.php
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ public function renderTableRow($model, $key, $index)
} else {
$options = $this->rowOptions;
}
$options['data-key'] = is_array($key) ? json_encode($key) : (string)$key;
$options['data-key'] = is_array($key) ? json_encode($key) : (string) $key;

return Html::tag('tr', implode('', $cells), $options);
}
Expand Down
4 changes: 2 additions & 2 deletions framework/helpers/BaseHtml.php
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ public static function textarea($name, $value = '', $options = [])
*/
public static function radio($name, $checked = false, $options = [])
{
$options['checked'] = (boolean) $checked;
$options['checked'] = (bool) $checked;
$value = array_key_exists('value', $options) ? $options['value'] : '1';
if (isset($options['uncheck'])) {
// add a hidden field so that if the radio button is not selected, it still submits a value
Expand Down Expand Up @@ -678,7 +678,7 @@ public static function radio($name, $checked = false, $options = [])
*/
public static function checkbox($name, $checked = false, $options = [])
{
$options['checked'] = (boolean) $checked;
$options['checked'] = (bool) $checked;
$value = array_key_exists('value', $options) ? $options['value'] : '1';
if (isset($options['uncheck'])) {
// add a hidden field so that if the checkbox is not selected, it still submits a value
Expand Down
2 changes: 1 addition & 1 deletion framework/helpers/BaseUrl.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class BaseUrl
*/
public static function toRoute($route, $scheme = false)
{
$route = (array)$route;
$route = (array) $route;
$route[0] = static::normalizeRoute($route[0]);

if ($scheme) {
Expand Down
4 changes: 2 additions & 2 deletions framework/mutex/MysqlMutex.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public function init()
*/
protected function acquireLock($name, $timeout = 0)
{
return (boolean) $this->db
return (bool) $this->db
->createCommand('SELECT GET_LOCK(:name, :timeout)', [':name' => $name, ':timeout' => $timeout])
->queryScalar();
}
Expand All @@ -70,7 +70,7 @@ protected function acquireLock($name, $timeout = 0)
*/
protected function releaseLock($name)
{
return (boolean) $this->db
return (bool) $this->db
->createCommand('SELECT RELEASE_LOCK(:name)', [':name' => $name])
->queryScalar();
}
Expand Down
12 changes: 6 additions & 6 deletions framework/rbac/DbManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ public function getRolesByUser($userId)
$query = (new Query)->select('b.*')
->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
->where('a.item_name=b.name')
->andWhere(['a.user_id' => (string)$userId]);
->andWhere(['a.user_id' => (string) $userId]);

$roles = [];
foreach ($query->all($this->db) as $row) {
Expand Down Expand Up @@ -391,7 +391,7 @@ public function getPermissionsByUser($userId)

$query = (new Query)->select('item_name')
->from($this->assignmentTable)
->where(['user_id' => (string)$userId]);
->where(['user_id' => (string) $userId]);

$childrenList = $this->getChildrenList();
$result = [];
Expand Down Expand Up @@ -482,7 +482,7 @@ public function getAssignment($roleName, $userId)
}

$row = (new Query)->from($this->assignmentTable)
->where(['user_id' => (string)$userId, 'item_name' => $roleName])
->where(['user_id' => (string) $userId, 'item_name' => $roleName])
->one($this->db);

if ($row === false) {
Expand All @@ -507,7 +507,7 @@ public function getAssignments($userId)

$query = (new Query)
->from($this->assignmentTable)
->where(['user_id' => (string)$userId]);
->where(['user_id' => (string) $userId]);

$assignments = [];
foreach ($query->all($this->db) as $row) {
Expand Down Expand Up @@ -644,7 +644,7 @@ public function revoke($role, $userId)
}

return $this->db->createCommand()
->delete($this->assignmentTable, ['user_id' => (string)$userId, 'item_name' => $role->name])
->delete($this->assignmentTable, ['user_id' => (string) $userId, 'item_name' => $role->name])
->execute() > 0;
}

Expand All @@ -658,7 +658,7 @@ public function revokeAll($userId)
}

return $this->db->createCommand()
->delete($this->assignmentTable, ['user_id' => (string)$userId])
->delete($this->assignmentTable, ['user_id' => (string) $userId])
->execute() > 0;
}

Expand Down
4 changes: 2 additions & 2 deletions framework/requirements/YiiRequirementChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ function checkPhpIniOn($name)
return false;
}

return ((integer) $value == 1 || strtolower($value) == 'on');
return ((int) $value == 1 || strtolower($value) == 'on');
}

/**
Expand Down Expand Up @@ -244,7 +244,7 @@ function getByteSize($verboseSize)
return 0;
}
if (is_numeric($verboseSize)) {
return (integer) $verboseSize;
return (int) $verboseSize;
}
$sizeUnit = trim($verboseSize, '0123456789');
$size = str_replace($sizeUnit, '', $verboseSize);
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/framework/db/CommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public function testBindParamValue()
}
$this->assertEquals($numericCol, $row['numeric_col']);
if ($this->driverName === 'mysql' || defined('HHVM_VERSION') && $this->driverName === 'sqlite') {
$this->assertEquals($boolCol, (int)$row['bool_col']);
$this->assertEquals($boolCol, (int) $row['bool_col']);
} else {
$this->assertEquals($boolCol, $row['bool_col']);
}
Expand Down

0 comments on commit bb85508

Please sign in to comment.