Yii2: Unable to check if ActiveRecord own properties isset or empty using array access notation

Created on 6 Dec 2019  路  3Comments  路  Source: yiisoft/yii2

What steps will reproduce the problem?

Created a ActiveRecord model class, for example:

class FinancialTransaction extends \yii\db\ActiveRecord
{
    /**
     * Custom property to be set manually
     */
    public $annotation;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%account}}';
    }

    // ... 
}

And run code like this:

$model = new FinancialTransaction();
$model->annotation = 'Some annotation';

var_dump($model['annotation']);
var_dump(isset($model['annotation']));
var_dump(empty($model['annotation']));

What is the expected result?

string(15) "Some annotation"
bool(true)
bool(false)

What do you get instead?

string(15) "Some annotation"
bool(false)
bool(true)

Suggestion:

Change implementation of BaseActiveRecor::offsetExists from:

public function offsetExists($offset)
{
    return $this->__isset($offset);
}

to:

public function offsetExists($offset)
{
    return isset($this->$offset);
}

So it will cover own ActiveRecord properties and fallback to __isset when needed.

Additional info

| Q | A
| ---------------- | ---
| Yii version | 2.0.28, 2.0.30
| PHP version | 7.3, 7.4
| Operating system | Mac OSX 10.15.1

under discussion bug

All 3 comments

BaseActiveRecord extends yii\base\Model which implements the suggestion above. We can remove offsetExists method from the BaseActiveRecord class and rely on the Model classes implementation.

yii\base\Model::offsetExists

public function offsetExists($offset)
    {
        return isset($this->$offset);
    }

Potentially that may break things. @yiisoft/core-developers, @yiisoft/reviewers what do you think? Any breaks that may happen?

If you need to check properties, please check from $model->attributes ($model->attributes['name'].
You can't check any indexes from object. By default it will throw an exception.


The fact that ActiveRecord "hides" this exception is very frustrating.
It would be nice to remove this strange behavior.

Was this page helpful?
0 / 5 - 0 ratings