From 281564e5e064ec9f35b1ccfb97aed9c954cd1596 Mon Sep 17 00:00:00 2001 From: Paul Klimov Date: Fri, 22 Dec 2023 15:38:47 +0200 Subject: [PATCH] fix attribute types detected from validation rules --- src/AttributeTypecastBehavior.php | 2 +- tests/AttributeTypecastBehaviorTest.php | 19 +++++++++++ tests/data/FormWithTypecast.php | 43 +++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 tests/data/FormWithTypecast.php diff --git a/src/AttributeTypecastBehavior.php b/src/AttributeTypecastBehavior.php index 9319a92..4685b8b 100644 --- a/src/AttributeTypecastBehavior.php +++ b/src/AttributeTypecastBehavior.php @@ -233,7 +233,7 @@ protected function detectAttributeTypesFromRules(): array } if ($type !== null) { - $attributeTypes += array_fill_keys($validator->getAttributeNames(), $type); + $attributeTypes += array_fill_keys($validator->attributes, $type); } } diff --git a/tests/AttributeTypecastBehaviorTest.php b/tests/AttributeTypecastBehaviorTest.php index 3b91b5b..a2018aa 100644 --- a/tests/AttributeTypecastBehaviorTest.php +++ b/tests/AttributeTypecastBehaviorTest.php @@ -5,6 +5,7 @@ use ArrayObject; use DateTime; use yii1tech\model\typecast\AttributeTypecastBehavior; +use yii1tech\model\typecast\test\data\FormWithTypecast; use yii1tech\model\typecast\test\data\Item; use yii1tech\model\typecast\test\data\ItemWithTypecast; @@ -225,4 +226,22 @@ public function testArrayObject(): void $model = ItemWithTypecast::model()->findByPk($model->id); $this->assertSame($array, $model->data_array_object->getArrayCopy()); } + + /** + * @depends testTypecast + */ + public function testDetectedAttributeTypesFromRules(): void + { + $model = new FormWithTypecast(); + $model->name = 123; + $model->amount = '100'; + $model->price = '5.5'; + $model->isAccepted = '1'; + + $this->assertTrue($model->validate()); + $this->assertSame('123', $model->name); + $this->assertSame(100, $model->amount); + $this->assertSame(5.5, $model->price); + $this->assertSame(true, $model->isAccepted); + } } \ No newline at end of file diff --git a/tests/data/FormWithTypecast.php b/tests/data/FormWithTypecast.php new file mode 100644 index 0000000..0e5e8bf --- /dev/null +++ b/tests/data/FormWithTypecast.php @@ -0,0 +1,43 @@ + 2], + ['amount', 'numerical', 'integerOnly' => true], + ['price', 'numerical', 'integerOnly' => false], + ['isAccepted', 'boolean'], + ]; + } + + /** + * {@inheritdoc} + */ + public function behaviors(): array + { + return [ + 'typecastBehavior' => [ + 'class' => AttributeTypecastBehavior::class, + 'attributeTypes' => null, + ], + ]; + } +} \ No newline at end of file