HumHub Documentation (unofficial)

AttributeTypecastBehavior extends Behavior
in package

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();
Tags
author

Paul Klimov klimov.paul@gmail.com

since
2.0.10

Table of Contents

Constants

TYPE_BOOLEAN  = 'boolean'
TYPE_FLOAT  = 'float'
TYPE_INTEGER  = 'integer'
TYPE_STRING  = 'string'

Properties

$attributeTypes  : array<string|int, mixed>|null
$owner  : Model|BaseActiveRecord
$skipOnNull  : bool
$typecastAfterFind  : bool
$typecastAfterSave  : bool
$typecastAfterValidate  : bool
$typecastBeforeSave  : bool
$_attachedEvents  : array<string|int, mixed>
$_autoDetectedAttributeTypes  : array<string|int, mixed>

Methods

__call()  : mixed
Calls the named method which is not a class method.
__construct()  : mixed
Constructor.
__get()  : mixed
Returns the value of an object property.
__isset()  : bool
Checks if a property is set, i.e. defined and not null.
__set()  : mixed
Sets value of an object property.
__unset()  : mixed
Sets an object property to null.
afterFind()  : mixed
Handles owner 'afterFind' event, ensuring attribute typecasting.
afterSave()  : mixed
Handles owner 'afterInsert' and 'afterUpdate' events, ensuring attribute typecasting.
afterValidate()  : mixed
Handles owner 'afterValidate' event, ensuring attribute typecasting.
attach()  : mixed
Attaches the behavior object to the component.
beforeSave()  : mixed
Handles owner 'beforeInsert' and 'beforeUpdate' events, ensuring attribute typecasting.
canGetProperty()  : bool
Returns a value indicating whether a property can be read.
canSetProperty()  : bool
Returns a value indicating whether a property can be set.
className()  : string
Returns the fully qualified name of this class.
clearAutoDetectedAttributeTypes()  : mixed
Clears internal static cache of auto detected [[attributeTypes]] values over all affected owner classes.
detach()  : mixed
Detaches the behavior object from the component.
events()  : array<string|int, mixed>
Declares event handlers for the [[owner]]'s events.
hasMethod()  : bool
Returns a value indicating whether a method is defined.
hasProperty()  : bool
Returns a value indicating whether a property is defined.
init()  : mixed
Initializes the object.
typecastAttributes()  : mixed
Typecast owner attributes according to [[attributeTypes]].
detectAttributeTypes()  : array<string|int, mixed>
Composes default value for [[attributeTypes]] from the owner validation rules.
resetOldAttributes()  : mixed
Resets the old values of the named attributes.
typecastValue()  : mixed
Casts the given value to the specified type.

Constants

Properties

$attributeTypes

public array<string|int, mixed>|null $attributeTypes

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

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]].

$typecastAfterFind

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 [[\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.

$typecastAfterSave

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 [[\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.

Tags
since
2.0.14

$typecastAfterValidate

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

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 [[\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.

$_attachedEvents

private array<string|int, mixed> $_attachedEvents = []

Attached events handlers

$_autoDetectedAttributeTypes

private static array<string|int, mixed> $_autoDetectedAttributeTypes = []

internal static cache for auto detected [[attributeTypes]] values in format: ownerClassName => attributeTypes

Methods

__call()

Calls the named method which is not a class method.

public __call(string $name, array<string|int, mixed> $params) : mixed

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.

Parameters
$name : string

the method name

$params : array<string|int, mixed>

method parameters

Tags
throws
UnknownMethodException

when calling unknown method

Return values
mixed

the method return value

__construct()

Constructor.

public __construct([array<string|int, mixed> $config = [] ]) : mixed

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.
Parameters
$config : array<string|int, mixed> = []

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

__get()

Returns the value of an object property.

public __get(string $name) : mixed

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

Parameters
$name : string

the property name

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is write-only

see
__set()
Return values
mixed

the property value

__isset()

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

public __isset(string $name) : bool

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.

Parameters
$name : string

the property name or the event name

Tags
see
https://www.php.net/manual/en/function.isset.php
Return values
bool

whether the named property is set (not null).

__set()

Sets value of an object property.

public __set(string $name, mixed $value) : mixed

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

Parameters
$name : string

the property name or the event name

$value : mixed

the property value

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is read-only

see
__get()

__unset()

Sets an object property to null.

public __unset(string $name) : mixed

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.

Parameters
$name : string

the property name

Tags
throws
InvalidCallException

if the property is read only.

see
https://www.php.net/manual/en/function.unset.php

afterFind()

Handles owner 'afterFind' event, ensuring attribute typecasting.

public afterFind(Event $event) : mixed
Parameters
$event : Event

event instance.

afterSave()

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

public afterSave(Event $event) : mixed
Parameters
$event : Event

event instance.

Tags
since
2.0.14

afterValidate()

Handles owner 'afterValidate' event, ensuring attribute typecasting.

public afterValidate(Event $event) : mixed
Parameters
$event : Event

event instance.

attach()

Attaches the behavior object to the component.

public attach(mixed $owner) : mixed
Parameters
$owner : mixed

the component that this behavior is to be attached to.

beforeSave()

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

public beforeSave(Event $event) : mixed
Parameters
$event : Event

event instance.

canGetProperty()

Returns a value indicating whether a property can be read.

public canGetProperty(string $name[, bool $checkVars = true ]) : bool

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);
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

Tags
see
canSetProperty()
Return values
bool

whether the property can be read

canSetProperty()

Returns a value indicating whether a property can be set.

public canSetProperty(string $name[, bool $checkVars = true ]) : bool

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);
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

Tags
see
canGetProperty()
Return values
bool

whether the property can be written

className()

Returns the fully qualified name of this class.

public static className() : string
Tags
deprecated

since 2.0.14. On PHP >=5.5, use ::class instead.

Return values
string

the fully qualified name of this class.

clearAutoDetectedAttributeTypes()

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

public static clearAutoDetectedAttributeTypes() : mixed

detach()

Detaches the behavior object from the component.

public detach() : mixed

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.

events()

Declares event handlers for the [[owner]]'s events.

public events() : array<string|int, mixed>
Return values
array<string|int, mixed>

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

hasMethod()

Returns a value indicating whether a method is defined.

public hasMethod(string $name) : bool

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

Parameters
$name : string

the method name

Return values
bool

whether the method is defined

hasProperty()

Returns a value indicating whether a property is defined.

public hasProperty(string $name[, bool $checkVars = true ]) : bool

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);
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

Tags
see
canGetProperty()
see
canSetProperty()
Return values
bool

whether the property is defined

init()

Initializes the object.

public init() : mixed

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

typecastAttributes()

Typecast owner attributes according to [[attributeTypes]].

public typecastAttributes([array<string|int, mixed>|null $attributeNames = null ]) : mixed
Parameters
$attributeNames : array<string|int, mixed>|null = 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.

detectAttributeTypes()

Composes default value for [[attributeTypes]] from the owner validation rules.

protected detectAttributeTypes() : array<string|int, mixed>
Return values
array<string|int, mixed>

attribute type map.

typecastValue()

Casts the given value to the specified type.

protected typecastValue(mixed $value, string|callable $type) : mixed
Parameters
$value : mixed

value to be type-casted.

$type : string|callable

type name or typecast callable.

Return values
mixed

typecast result.


        
On this page

Search results