# AttributeTypecastBehavior

> AttributeTypecastBehavior provides an ability of automatic model attribute typecasting.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [behaviors](/docs/api/yii/behaviors/index.md) › AttributeTypecastBehavior

| class | `yii\behaviors\AttributeTypecastBehavior` |
| --- | --- |
| Extends | [`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0.10 |
| Source | [`framework/behaviors/AttributeTypecastBehavior.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/behaviors/AttributeTypecastBehavior.php#L116) |

AttributeTypecastBehavior provides an ability of automatic model attribute typecasting.

This behavior is very useful in case of usage of ActiveRecord for the schema-less databases like MongoDB or Redis.
It may also come in handy for regular [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) or even [`Model`](/docs/api/yii/base/model/index.md), allowing to maintain
strict attribute types after model validation.

This behavior should be attached to [`Model`](/docs/api/yii/base/model/index.md) or [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) descendant.

You should specify exact attribute types via [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes).

For example:

```
use yii\behaviors\AttributeTypecastBehavior;

class Item extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            'typecast' => [
                'class' => AttributeTypecastBehavior::class,
                'attributeTypes' => [
                    'amount' => AttributeTypecastBehavior::TYPE_INTEGER,
                    'price' => AttributeTypecastBehavior::TYPE_FLOAT,
                    'is_active' => AttributeTypecastBehavior::TYPE_BOOLEAN,
                ],
                'typecastAfterValidate' => true,
                'typecastBeforeSave' => false,
                'typecastAfterFind' => false,
            ],
        ];
    }

    // ...
}
```

Tip: you may left [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes) blank - in this case its value will be detected
automatically based on owner validation rules.
Following example will automatically create same [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes) value as it was configured at the above one:

```
use yii\behaviors\AttributeTypecastBehavior;

class Item extends \yii\db\ActiveRecord
{

    public function rules()
    {
        return [
            ['amount', 'integer'],
            ['price', 'number'],
            ['is_active', 'boolean'],
        ];
    }

    public function behaviors()
    {
        return [
            'typecast' => [
                'class' => AttributeTypecastBehavior::class,
                // 'attributeTypes' will be composed automatically according to `rules()`
            ],
        ];
    }

    // ...
}
```

This behavior allows automatic attribute typecasting at following cases:

- after successful model validation
- before model save (insert or update)
- after model find (found by query or refreshed)

You may control automatic typecasting for particular case using fields [`$typecastAfterValidate`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-typecastAfterValidate),
[`$typecastBeforeSave`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-typecastBeforeSave) and [`$typecastAfterFind`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-typecastAfterFind).
By default typecasting will be performed only after model validation.

Note: you can manually trigger attribute typecasting anytime invoking [`typecastAttributes()`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#method-typecastAttributes) method:

```
$model = new Item();
$model->price = '38.5';
$model->is_active = 1;
$model->typecastAttributes();
```

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| [`$attributeTypes`](#property-attributeTypes) | `array\|null` | Attribute typecast map in format: attributeName => type. Default: `null`. | `AttributeTypecastBehavior` |
| <span id="property-owner"></span>`$owner` | `yii\behaviors\T\|null` | The owner of this behavior. Default: `null`. | `AttributeTypecastBehavior` |
| [`$skipOnNull`](#property-skipOnNull) | `bool` | Whether to skip typecasting of `null` values. Default: `true`. | `AttributeTypecastBehavior` |
| [`$typecastAfterFind`](#property-typecastAfterFind) | `bool` | Whether to perform typecasting after retrieving owner model data from the database (after find or refresh). Default: `false`. | `AttributeTypecastBehavior` |
| [`$typecastAfterSave`](#property-typecastAfterSave) | `bool` | Whether to perform typecasting after saving owner model (insert or update). Default: `false`. Available since 2.0.14. | `AttributeTypecastBehavior` |
| [`$typecastAfterValidate`](#property-typecastAfterValidate) | `bool` | Whether to perform typecasting after owner model validation. Default: `true`. | `AttributeTypecastBehavior` |
| [`$typecastBeforeSave`](#property-typecastBeforeSave) | `bool` | Whether to perform typecasting before saving owner model (insert or update). Default: `false`. | `AttributeTypecastBehavior` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/baseobject/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/baseobject/index.md#method-__get) | Returns the value of an object property. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/baseobject/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/baseobject/index.md#method-__set) | Sets value of an object property. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/baseobject/index.md#method-__unset) | Sets an object property to null. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`afterFind()`](#method-afterFind) | Handles owner 'afterFind' event, ensuring attribute typecasting. | `AttributeTypecastBehavior` |
| [`afterSave()`](#method-afterSave) | Handles owner 'afterInsert' and 'afterUpdate' events, ensuring attribute typecasting. | `AttributeTypecastBehavior` |
| [`afterValidate()`](#method-afterValidate) | Handles owner 'afterValidate' event, ensuring attribute typecasting. | `AttributeTypecastBehavior` |
| [`attach()`](#method-attach) | Attaches the behavior object to the component. | `AttributeTypecastBehavior` |
| [`beforeSave()`](#method-beforeSave) | Handles owner 'beforeInsert' and 'beforeUpdate' events, ensuring attribute typecasting. | `AttributeTypecastBehavior` |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/baseobject/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/baseobject/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`clearAutoDetectedAttributeTypes()`](#method-clearAutoDetectedAttributeTypes) static | Clears internal static cache of auto detected [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes) values over all affected owner classes. | `AttributeTypecastBehavior` |
| <span id="method-detach"></span>[`detach()`](/docs/api/yii/base/behavior/index.md#method-detach) | Detaches the behavior object from the component. | [`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md) |
| [`events()`](#method-events) | Declares event handlers for the [`$owner`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-owner)'s events. | `AttributeTypecastBehavior` |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/baseobject/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/baseobject/index.md#method-hasProperty) | Returns a value indicating whether a property is defined. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-init"></span>[`init()`](/docs/api/yii/base/baseobject/index.md#method-init) | Initializes the object. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`typecastAttributes()`](#method-typecastAttributes) | Typecast owner attributes according to [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes). | `AttributeTypecastBehavior` |
| [`detectAttributeTypes()`](#method-detectAttributeTypes) protected | Composes default value for [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes) from the owner validation rules. | `AttributeTypecastBehavior` |
| [`resetOldAttributes()`](#method-resetOldAttributes) protected | Resets the old values of the named attributes. | `AttributeTypecastBehavior` |
| [`typecastValue()`](#method-typecastValue) protected | Casts the given value to the specified type. | `AttributeTypecastBehavior` |

## Constants

| Constant | Value | Description | Defined by |
| --- | --- | --- | --- |
| <span id="const-TYPE_INTEGER"></span>`TYPE_INTEGER` | `'integer'` |  | `AttributeTypecastBehavior` |
| <span id="const-TYPE_FLOAT"></span>`TYPE_FLOAT` | `'float'` |  | `AttributeTypecastBehavior` |
| <span id="const-TYPE_BOOLEAN"></span>`TYPE_BOOLEAN` | `'boolean'` |  | `AttributeTypecastBehavior` |
| <span id="const-TYPE_STRING"></span>`TYPE_STRING` | `'string'` |  | `AttributeTypecastBehavior` |

## Property details

### $attributeTypes <span id="property-attributeTypes"></span>

```php
public array|null $attributeTypes = null
```

Attribute typecast map in format: attributeName => type.

Type can be set via PHP callable, which accept raw value as an argument and should return
typecast result.
For example:

```
[
    'amount' => 'integer',
    'price' => 'float',
    'is_active' => 'boolean',
    'date' => function ($value) {
        return ($value instanceof \DateTime) ? $value->getTimestamp(): (int) $value;
    },
]
```

If not set, attribute type map will be composed automatically from the owner validation rules.

### $skipOnNull <span id="property-skipOnNull"></span>

```php
public bool $skipOnNull = true
```

Whether to skip typecasting of `null` values.

If enabled attribute value which equals to `null` will not be type-casted (e.g. `null` remains `null`),
otherwise it will be converted according to the type configured at [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes).

### $typecastAfterFind <span id="property-typecastAfterFind"></span>

```php
public bool $typecastAfterFind = false
```

Whether to perform typecasting after retrieving owner model data from the database (after find or refresh).

This option may be disabled in order to achieve better performance.
For example, in case of [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) usage, typecasting after find
will grant no benefit in most cases an thus can be disabled.
Note that changing this option value will have no effect after this behavior has been attached to the model.

### $typecastAfterSave <span id="property-typecastAfterSave"></span>

```php
public bool $typecastAfterSave = false
```

Whether to perform typecasting after saving owner model (insert or update).

This option may be disabled in order to achieve better performance.
For example, in case of [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) usage, typecasting after save
will grant no benefit an thus can be disabled.
Note that changing this option value will have no effect after this behavior has been attached to the model.

**Since**

2.0.14

### $typecastAfterValidate <span id="property-typecastAfterValidate"></span>

```php
public bool $typecastAfterValidate = true
```

Whether to perform typecasting after owner model validation.

Note that typecasting will be performed only if validation was successful, e.g.
owner model has no errors.
Note that changing this option value will have no effect after this behavior has been attached to the model.

### $typecastBeforeSave <span id="property-typecastBeforeSave"></span>

```php
public bool $typecastBeforeSave = false
```

Whether to perform typecasting before saving owner model (insert or update).

This option may be disabled in order to achieve better performance.
For example, in case of [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) usage, typecasting before save
will grant no benefit an thus can be disabled.
Note that changing this option value will have no effect after this behavior has been attached to the model.

## Method details

### afterFind() <span id="method-afterFind"></span>

```php
public function afterFind(yii\base\Event $event): mixed
```

Handles owner 'afterFind' event, ensuring attribute typecasting.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$event` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | Event instance. |

**Returns**

`mixed`

### afterSave() <span id="method-afterSave"></span>

```php
public function afterSave(yii\base\Event $event): mixed
```

Handles owner 'afterInsert' and 'afterUpdate' events, ensuring attribute typecasting.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$event` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | Event instance. |

**Returns**

`mixed`

**Since**

2.0.14

### afterValidate() <span id="method-afterValidate"></span>

```php
public function afterValidate(yii\base\Event $event): mixed
```

Handles owner 'afterValidate' event, ensuring attribute typecasting.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$event` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | Event instance. |

**Returns**

`mixed`

### attach() <span id="method-attach"></span>

```php
public function attach(mixed $owner): mixed
```

Attaches the behavior object to the component.

The default implementation will set the [`$owner`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-owner) property
and attach event handlers as declared in [`events()`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#method-events).
Make sure you call the parent implementation if you override this method.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$owner` | `mixed` | The component that this behavior is to be attached to. |

**Returns**

`mixed`

### beforeSave() <span id="method-beforeSave"></span>

```php
public function beforeSave(yii\base\Event $event): mixed
```

Handles owner 'beforeInsert' and 'beforeUpdate' events, ensuring attribute typecasting.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$event` | [`yii\base\Event`](/docs/api/yii/base/event/index.md) | Event instance. |

**Returns**

`mixed`

### clearAutoDetectedAttributeTypes() <span id="method-clearAutoDetectedAttributeTypes"></span>

```php
public static function clearAutoDetectedAttributeTypes(): mixed
```

Clears internal static cache of auto detected [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes) values
over all affected owner classes.

**Returns**

`mixed`

### events() <span id="method-events"></span>

```php
public function events(): array
```

Declares event handlers for the [`$owner`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-owner)'s events.

Child classes may override this method to declare what PHP callbacks should
be attached to the events of the [`$owner`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-owner) component.

The callbacks will be attached to the [`$owner`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-owner)'s events when the behavior is
attached to the owner; and they will be detached from the events when
the behavior is detached from the component.

The callbacks can be any of the following:

- method in this behavior: `'handleClick'`, equivalent to `[$this, 'handleClick']`
- object method: `[$object, 'handleClick']`
- static method: `['Page', 'handleClick']`
- anonymous function: `function ($event) { ... }`

The following is an example:

```
[
    Model::EVENT_BEFORE_VALIDATE => 'myBeforeValidate',
    Model::EVENT_AFTER_VALIDATE => 'myAfterValidate',
]
```

**Returns**

`array`: Events (array keys) and the corresponding event handler methods (array values).

### typecastAttributes() <span id="method-typecastAttributes"></span>

```php
public function typecastAttributes(array|null $attributeNames = null): mixed
```

Typecast owner attributes according to [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attributeNames` | `array\|null` | List of attribute names that should be type-casted. If this parameter is empty, it means any attribute listed in the [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes) should be type-casted. |

**Returns**

`mixed`

### detectAttributeTypes() <span id="method-detectAttributeTypes"></span>

```php
protected function detectAttributeTypes(): array
```

Composes default value for [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes) from the owner validation rules.

Validators that have a [when](/docs/api/yii/validators/validator/index.md#property-when) condition are ignored: the detection
result is composed once per owner class, while such a condition can only be resolved against a particular
model instance at validation time. Type-casting an attribute whose rule may not even be applied would
convert a value that has never been validated, so attributes covered by conditional rules only are left
out of the map. Specify [`$attributeTypes`](/docs/api/yii/behaviors/attributetypecastbehavior/index.md#property-attributeTypes) explicitly if you need them to be type-casted.

**Returns**

`array`: Attribute type map.

### resetOldAttributes() <span id="method-resetOldAttributes"></span>

```php
protected function resetOldAttributes(): mixed
```

Resets the old values of the named attributes.

**Returns**

`mixed`

### typecastValue() <span id="method-typecastValue"></span>

```php
protected function typecastValue(mixed $value, string|callable $type): mixed
```

Casts the given value to the specified type.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$value` | `mixed` | Value to be type-casted. |
| `$type` | `string\|callable` | Type name or typecast callable. |

**Returns**

`mixed`: Typecast result.