Class yii\behaviors\AttributeTypecastBehavior

Inheritanceyii\behaviors\AttributeTypecastBehavior » yii\base\Behavior » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.0.10
Source Code https://github.com/yiisoft/yii2/blob/master/framework/behaviors/AttributeTypecastBehavior.php

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 yii\db\ActiveRecord or even yii\base\Model, allowing to maintain strict attribute types after model validation.

This behavior should be attached to yii\base\Model or yii\db\BaseActiveRecord descendant.

You should specify exact attribute types via $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 blank - in this case its value will be detected automatically based on owner validation rules. Following example will automatically create same $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, $typecastBeforeSave and $typecastAfterFind. By default typecasting will be performed only after model validation.

Note: you can manually trigger attribute typecasting anytime invoking typecastAttributes() method:

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

Public Properties

Hide inherited properties

Property Type Description Defined By
$attributeTypes array|null Attribute typecast map in format: attributeName => type. yii\behaviors\AttributeTypecastBehavior
$owner yii\base\Model|yii\db\BaseActiveRecord The owner of this behavior. yii\behaviors\AttributeTypecastBehavior
$skipOnNull boolean Whether to skip typecasting of null values. yii\behaviors\AttributeTypecastBehavior
$typecastAfterFind boolean Whether to perform typecasting after retrieving owner model data from the database (after find or refresh). yii\behaviors\AttributeTypecastBehavior
$typecastAfterSave boolean Whether to perform typecasting after saving owner model (insert or update). yii\behaviors\AttributeTypecastBehavior
$typecastAfterValidate boolean Whether to perform typecasting after owner model validation. yii\behaviors\AttributeTypecastBehavior
$typecastBeforeSave boolean Whether to perform typecasting before saving owner model (insert or update). yii\behaviors\AttributeTypecastBehavior

Public Methods

Hide inherited methods

Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
afterFind() Handles owner 'afterFind' event, ensuring attribute typecasting. yii\behaviors\AttributeTypecastBehavior
afterSave() Handles owner 'afterInsert' and 'afterUpdate' events, ensuring attribute typecasting. yii\behaviors\AttributeTypecastBehavior
afterValidate() Handles owner 'afterValidate' event, ensuring attribute typecasting. yii\behaviors\AttributeTypecastBehavior
attach() Attaches the behavior object to the component. yii\behaviors\AttributeTypecastBehavior
beforeSave() Handles owner 'beforeInsert' and 'beforeUpdate' events, ensuring attribute typecasting. yii\behaviors\AttributeTypecastBehavior
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
clearAutoDetectedAttributeTypes() Clears internal static cache of auto detected $attributeTypes values over all affected owner classes. yii\behaviors\AttributeTypecastBehavior
detach() Detaches the behavior object from the component. yii\base\Behavior
events() Declares event handlers for the $owner's events. yii\behaviors\AttributeTypecastBehavior
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
typecastAttributes() Typecast owner attributes according to $attributeTypes. yii\behaviors\AttributeTypecastBehavior

Protected Methods

Hide inherited methods

Method Description Defined By
detectAttributeTypes() Composes default value for $attributeTypes from the owner validation rules. yii\behaviors\AttributeTypecastBehavior
typecastValue() Casts the given value to the specified type. yii\behaviors\AttributeTypecastBehavior

Constants

Hide inherited constants

Constant Value Description Defined By
TYPE_BOOLEAN 'boolean' yii\behaviors\AttributeTypecastBehavior
TYPE_FLOAT 'float' yii\behaviors\AttributeTypecastBehavior
TYPE_INTEGER 'integer' yii\behaviors\AttributeTypecastBehavior
TYPE_STRING 'string' yii\behaviors\AttributeTypecastBehavior

Property Details

Hide inherited properties

$attributeTypes public property

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.

public array|null $attributeTypes null
$owner public property

The owner of this behavior.

$skipOnNull public property

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.

public boolean $skipOnNull true
$typecastAfterFind public property

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 yii\db\ActiveRecord 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.

public boolean $typecastAfterFind false
$typecastAfterSave public property (available since version 2.0.14)

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 yii\db\ActiveRecord 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.

public boolean $typecastAfterSave false
$typecastAfterValidate public property

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 public property

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 yii\db\ActiveRecord 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

Hide inherited methods

__call() public method

Defined in: yii\base\BaseObject::__call()

Calls the named method which is not a class method.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

public mixed __call ( $name, $params )
$name string

The method name

$params array

Method parameters

return mixed

The method return value

throws yii\base\UnknownMethodException

when calling unknown method

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

Constructor.

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call init().

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
public void __construct ( $config = [] )
$config array

Name-value pairs that will be used to initialize the object properties

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

Defined in: yii\base\BaseObject::__get()

Returns the value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $object->property;.

See also __set().

public mixed __get ( $name )
$name string

The property name

return mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is write-only

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

Defined in: yii\base\BaseObject::__isset()

Checks if a property is set, i.e. defined and not null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($object->property).

Note that if the property is not defined, false will be returned.

See also https://www.php.net/manual/en/function.isset.php.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the named property is set (not null).

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() public method

Defined in: yii\base\BaseObject::__set()

Sets value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $object->property = $value;.

See also __get().

public void __set ( $name, $value )
$name string

The property name or the event name

$value mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is read-only

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() public method

Defined in: yii\base\BaseObject::__unset()

Sets an object property to null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($object->property).

Note that if the property is not defined, this method will do nothing. If the property is read-only, it will throw an exception.

See also https://www.php.net/manual/en/function.unset.php.

public void __unset ( $name )
$name string

The property name

throws yii\base\InvalidCallException

if the property is read only.

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
afterFind() public method

Handles owner 'afterFind' event, ensuring attribute typecasting.

public void afterFind ( $event )
$event yii\base\Event

Event instance.

                public function afterFind($event)
{
    $this->typecastAttributes();
}

            
afterSave() public method (available since version 2.0.14)

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

public void afterSave ( $event )
$event yii\base\Event

Event instance.

                public function afterSave($event)
{
    $this->typecastAttributes();
}

            
afterValidate() public method

Handles owner 'afterValidate' event, ensuring attribute typecasting.

public void afterValidate ( $event )
$event yii\base\Event

Event instance.

                public function afterValidate($event)
{
    if (!$this->owner->hasErrors()) {
        $this->typecastAttributes();
    }
}

            
attach() public method

Attaches the behavior object to the component.

The default implementation will set the $owner property and attach event handlers as declared in events(). Make sure you call the parent implementation if you override this method.

public void attach ( $owner )
$owner yii\base\Component

The component that this behavior is to be attached to.

                public function attach($owner)
{
    parent::attach($owner);
    if ($this->attributeTypes === null) {
        $ownerClass = get_class($this->owner);
        if (!isset(self::$autoDetectedAttributeTypes[$ownerClass])) {
            self::$autoDetectedAttributeTypes[$ownerClass] = $this->detectAttributeTypes();
        }
        $this->attributeTypes = self::$autoDetectedAttributeTypes[$ownerClass];
    }
}

            
beforeSave() public method

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

public void beforeSave ( $event )
$event yii\base\Event

Event instance.

                public function beforeSave($event)
{
    $this->typecastAttributes();
}

            
canGetProperty() public method

Defined in: yii\base\BaseObject::canGetProperty()

Returns a value indicating whether a property can be read.

A property is readable if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be read

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() public method

Defined in: yii\base\BaseObject::canSetProperty()

Returns a value indicating whether a property can be set.

A property is writable if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be written

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Defined in: yii\base\BaseObject::className()

Returns the fully qualified name of this class.

public static string className ( )
return string

The fully qualified name of this class.

                public static function className()
{
    return get_called_class();
}

            
clearAutoDetectedAttributeTypes() public static method

Clears internal static cache of auto detected $attributeTypes values over all affected owner classes.

public static void clearAutoDetectedAttributeTypes ( )

                public static function clearAutoDetectedAttributeTypes()
{
    self::$autoDetectedAttributeTypes = [];
}

            
detach() public method

Defined in: yii\base\Behavior::detach()

Detaches the behavior object from the component.

The default implementation will unset the $owner property and detach event handlers declared in events(). Make sure you call the parent implementation if you override this method.

public void detach ( )

                public function detach()
{
    if ($this->owner) {
        foreach ($this->_attachedEvents as $event => $handler) {
            $this->owner->off($event, is_string($handler) ? [$this, $handler] : $handler);
        }
        $this->_attachedEvents = [];
        $this->owner = null;
    }
}

            
detectAttributeTypes() protected method

Composes default value for $attributeTypes from the owner validation rules.

protected array detectAttributeTypes ( )
return array

Attribute type map.

                protected function detectAttributeTypes()
{
    $attributeTypes = [];
    foreach ($this->owner->getValidators() as $validator) {
        $type = null;
        if ($validator instanceof BooleanValidator) {
            $type = self::TYPE_BOOLEAN;
        } elseif ($validator instanceof NumberValidator) {
            $type = $validator->integerOnly ? self::TYPE_INTEGER : self::TYPE_FLOAT;
        } elseif ($validator instanceof StringValidator) {
            $type = self::TYPE_STRING;
        }
        if ($type !== null) {
            $attributeTypes += array_fill_keys($validator->getAttributeNames(), $type);
        }
    }
    return $attributeTypes;
}

            
events() public method

Declares event handlers for the $owner's events.

Child classes may override this method to declare what PHP callbacks should be attached to the events of the $owner component.

The callbacks will be attached to the $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',
]
public array events ( )
return array

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

                public function events()
{
    $events = [];
    if ($this->typecastAfterValidate) {
        $events[Model::EVENT_AFTER_VALIDATE] = 'afterValidate';
    }
    if ($this->typecastBeforeSave) {
        $events[BaseActiveRecord::EVENT_BEFORE_INSERT] = 'beforeSave';
        $events[BaseActiveRecord::EVENT_BEFORE_UPDATE] = 'beforeSave';
    }
    if ($this->typecastAfterSave) {
        $events[BaseActiveRecord::EVENT_AFTER_INSERT] = 'afterSave';
        $events[BaseActiveRecord::EVENT_AFTER_UPDATE] = 'afterSave';
    }
    if ($this->typecastAfterFind) {
        $events[BaseActiveRecord::EVENT_AFTER_FIND] = 'afterFind';
    }
    return $events;
}

            
hasMethod() public method

Defined in: yii\base\BaseObject::hasMethod()

Returns a value indicating whether a method is defined.

The default implementation is a call to php function method_exists(). You may override this method when you implemented the php magic method __call().

public boolean hasMethod ( $name )
$name string

The method name

return boolean

Whether the method is defined

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() public method

Defined in: yii\base\BaseObject::hasProperty()

Returns a value indicating whether a property is defined.

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also:

public boolean hasProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property is defined

                public function hasProperty($name, $checkVars = true)
{
    return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}

            
init() public method

Defined in: yii\base\BaseObject::init()

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

public void init ( )

                public function init()
{
}

            
typecastAttributes() public method

Typecast owner attributes according to $attributeTypes.

public void typecastAttributes ( $attributeNames null )
$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 should be type-casted.

                public function typecastAttributes($attributeNames = null)
{
    $attributeTypes = [];
    if ($attributeNames === null) {
        $attributeTypes = $this->attributeTypes;
    } else {
        foreach ($attributeNames as $attribute) {
            if (!isset($this->attributeTypes[$attribute])) {
                throw new InvalidArgumentException("There is no type mapping for '{$attribute}'.");
            }
            $attributeTypes[$attribute] = $this->attributeTypes[$attribute];
        }
    }
    foreach ($attributeTypes as $attribute => $type) {
        $value = $this->owner->{$attribute};
        if ($this->skipOnNull && $value === null) {
            continue;
        }
        $this->owner->{$attribute} = $this->typecastValue($value, $type);
    }
}

            
typecastValue() protected method

Casts the given value to the specified type.

protected mixed typecastValue ( $value, $type )
$value mixed

Value to be type-casted.

$type string|callable

Type name or typecast callable.

return mixed

Typecast result.

                protected function typecastValue($value, $type)
{
    if (is_scalar($type)) {
        if (is_object($value) && method_exists($value, '__toString')) {
            $value = $value->__toString();
        }
        switch ($type) {
            case self::TYPE_INTEGER:
                return (int) $value;
            case self::TYPE_FLOAT:
                return (float) $value;
            case self::TYPE_BOOLEAN:
                return (bool) $value;
            case self::TYPE_STRING:
                if (is_float($value)) {
                    return StringHelper::floatToString($value);
                }
                return (string) $value;
            default:
                throw new InvalidArgumentException("Unsupported type '{$type}'");
        }
    }
    return call_user_func($type, $value);
}