Skip to content

Commit

Permalink
fix attribute types detected from validation rules
Browse files Browse the repository at this point in the history
  • Loading branch information
klimov-paul committed Dec 22, 2023
1 parent 129fe90 commit 281564e
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/AttributeTypecastBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
19 changes: 19 additions & 0 deletions tests/AttributeTypecastBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
}
}
43 changes: 43 additions & 0 deletions tests/data/FormWithTypecast.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace yii1tech\model\typecast\test\data;

use CFormModel;
use yii1tech\model\typecast\AttributeTypecastBehavior;

class FormWithTypecast extends CFormModel
{
public $name;

public $amount;

public $price;

public $isAccepted;

/**
* {@inheritdoc}
*/
public function rules(): array
{
return [
['name', 'length', 'min' => 2],
['amount', 'numerical', 'integerOnly' => true],
['price', 'numerical', 'integerOnly' => false],
['isAccepted', 'boolean'],
];
}

/**
* {@inheritdoc}
*/
public function behaviors(): array
{
return [
'typecastBehavior' => [
'class' => AttributeTypecastBehavior::class,
'attributeTypes' => null,
],
];
}
}

0 comments on commit 281564e

Please sign in to comment.