yii2 icon indicating copy to clipboard operation
yii2 copied to clipboard

RequiredValidator with typed properties

Open DplusG opened this issue 9 months ago • 4 comments

Q A
Yii version 2.0.49
PHP version 7.4
Is bugfix Yes
Breaks BC? No (not sure)

What steps will reproduce the problem?

$model = SomeModelWithTypedProperties();
$model->setAttributes([]);
$model->validate();

What is the expected result?

Validation error, Prop1 cannot be blank.

What do you get instead?

Typed property prop1 must not be accessed before initialization

Solution

Change RequiredValidator. See @DplusG/yii2-required-validator

DplusG avatar May 15 '24 06:05 DplusG

I'm not sure if we should get back to this old thing already mentioned in https://github.com/yiisoft/yii2/issues/17954 What exactly is your use-case? I mean, how does your SomeModelWithTypedProperties look like?

bizley avatar May 15 '24 11:05 bizley

class SomeModelWithTypedProperties extends Model 
{
    public string $prop1;
    public ?string $optionalProp2 = null;

    public function rules(): array 
    {
        return [
            [['prop1'], 'required'],
        ];
    }
}

// I don't know current data like in https://github.com/yiisoft/yii2/issues/17954
// and I want to see which properties are really required at the language level 
// (not like: public ?string $prop1 = null)
$model->setAttributes($post);

Thank you, I see in https://github.com/yiisoft/yii2/issues/17954 'prefer not handing it' from samdark

In this issue I suggest to change the programm error to the validation error. I can suggest an internal validator initialized, But it's no so clear.

return [
    [['prop1'], 'initialized'],
    [['prop1'], 'required'],
];

Validation error is what we received in php <=7.3. I show it in my repo

DplusG avatar May 15 '24 13:05 DplusG

Fixing typed properties in validation seems like a lost cause to me, due to how Yii handles validation in models: it first assigns value to property, and then validates it. So if you type property as string and someone pass array as value for it, it will throw fatal error before even validation begins.

rob006 avatar May 15 '24 18:05 rob006

Yes, likely that isn't fixable in Yii2.

samdark avatar May 15 '24 19:05 samdark

Ok, thanks! In my case, I did not try to solve typecasting. Only initialization.

Can I add packages from Yii3 to solve this problem? Validator, hydrator, form-model?

DplusG avatar May 16 '24 06:05 DplusG

True, but this is another case here. Yii is checking the attribute first before assigning it hence the error for not initializing. DplusG has a model with invalid state for $prop1 here. The thing with incompatible types and this problem both are developer issues.

bizley avatar May 16 '24 06:05 bizley

DplusG - for your case this is simple, you must initialize the property.

bizley avatar May 16 '24 06:05 bizley