Trait yii\base\ArrayableTrait

Implemented byluya\admin\file\Item, luya\admin\folder\Item, luya\admin\image\Item, luya\admin\models\ApiUser, luya\admin\models\Auth, luya\admin\models\Config, luya\admin\models\Group, luya\admin\models\GroupAuth, luya\admin\models\Lang, luya\admin\models\Logger, luya\admin\models\LoginForm, luya\admin\models\NgrestLog, luya\admin\models\Property, luya\admin\models\ProxyBuild, luya\admin\models\ProxyMachine, luya\admin\models\QueueLog, luya\admin\models\QueueLogError, luya\admin\models\ResetPasswordChangeForm, luya\admin\models\ResetPasswordForm, luya\admin\models\Scheduler, luya\admin\models\SearchData, luya\admin\models\StorageEffect, luya\admin\models\StorageFile, luya\admin\models\StorageFilter, luya\admin\models\StorageFilterChain, luya\admin\models\StorageFolder, luya\admin\models\StorageImage, luya\admin\models\Tag, luya\admin\models\TagRelation, luya\admin\models\User, luya\admin\models\UserAuthNotification, luya\admin\models\UserChangePassword, luya\admin\models\UserDevice, luya\admin\models\UserGroup, luya\admin\models\UserLogin, luya\admin\models\UserLoginLockout, luya\admin\models\UserOnline, luya\admin\models\UserRequest, luya\admin\ngrest\base\NgRestModel, luya\admin\storage\ItemAbstract, luya\base\DynamicModel, luya\cms\base\NavItemType, luya\cms\menu\Item, luya\cms\models\Block, luya\cms\models\BlockGroup, luya\cms\models\Config, luya\cms\models\Layout, luya\cms\models\Log, luya\cms\models\Nav, luya\cms\models\NavContainer, luya\cms\models\NavItem, luya\cms\models\NavItemModule, luya\cms\models\NavItemPage, luya\cms\models\NavItemPageBlockItem, luya\cms\models\NavItemRedirect, luya\cms\models\NavPermission, luya\cms\models\Property, luya\cms\models\Redirect, luya\cms\models\Theme, luya\cms\models\Website, luya\theme\ThemeConfig, luya\web\BaseLink, luya\web\EmailLink, luya\web\TelephoneLink, luya\web\WebsiteLink, luya\web\jsonld\AggregateRating, luya\web\jsonld\Article, luya\web\jsonld\BarOrPub, luya\web\jsonld\BaseThing, luya\web\jsonld\BlogPosting, luya\web\jsonld\CafeOrCoffeeShop, luya\web\jsonld\Comment, luya\web\jsonld\ContactPoint, luya\web\jsonld\Country, luya\web\jsonld\CreativeWork, luya\web\jsonld\EntertainmentBusiness, luya\web\jsonld\Event, luya\web\jsonld\FoodEstablishment, luya\web\jsonld\GeoCoordinates, luya\web\jsonld\ImageObject, luya\web\jsonld\LiveBlogPosting, luya\web\jsonld\LocalBusiness, luya\web\jsonld\MediaObject, luya\web\jsonld\NightClub, luya\web\jsonld\Offer, luya\web\jsonld\Organization, luya\web\jsonld\Person, luya\web\jsonld\Place, luya\web\jsonld\PostalAddress, luya\web\jsonld\PropertyValue, luya\web\jsonld\Rating, luya\web\jsonld\Restaurant, luya\web\jsonld\Review, luya\web\jsonld\SocialMediaPosting, luya\web\jsonld\Thing, yii\base\DynamicModel, yii\base\Model, yii\data\ActiveDataFilter, yii\data\DataFilter, yii\db\ActiveRecord, yii\db\BaseActiveRecord
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/base/ArrayableTrait.php

ArrayableTrait provides a common implementation of the yii\base\Arrayable interface.

ArrayableTrait implements toArray() by respecting the field definitions as declared in fields() and extraFields().

Public Methods

Hide inherited methods

Method Description Defined By
extraFields() Returns the list of fields that can be expanded further and returned by toArray(). yii\base\ArrayableTrait
fields() Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. yii\base\ArrayableTrait
toArray() Converts the model into an array. yii\base\ArrayableTrait

Protected Methods

Hide inherited methods

Method Description Defined By
extractFieldsFor() Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id". yii\base\ArrayableTrait
extractRootFields() Extracts the root field names from nested fields. yii\base\ArrayableTrait
resolveFields() Determines which fields can be returned by toArray(). yii\base\ArrayableTrait

Method Details

Hide inherited methods

extraFields() public method

Returns the list of fields that can be expanded further and returned by toArray().

This method is similar to fields() except that the list of fields returned by this method are not returned by default by toArray(). Only when field names to be expanded are explicitly specified when calling toArray(), will their values be exported.

The default implementation returns an empty array.

You may override this method to return a list of expandable fields based on some context information (e.g. the current application user).

See also:

public array extraFields ( )
return array

The list of expandable field names or field definitions. Please refer to fields() on the format of the return value.

                public function extraFields()
{
    return [];
}

            
extractFieldsFor() protected method (available since version 2.0.14)

Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id".

protected array extractFieldsFor ( array $fields, $rootField )
$fields array

The fields requested for extraction

$rootField string

The root field for which we want to extract the nested fields

return array

Nested fields extracted for the given field

                protected function extractFieldsFor(array $fields, $rootField)
{
    $result = [];
    foreach ($fields as $field) {
        if (0 === strpos($field, "{$rootField}.")) {
            $result[] = preg_replace('/^' . preg_quote($rootField, '/') . '\./i', '', $field);
        }
    }
    return array_unique($result);
}

            
extractRootFields() protected method (available since version 2.0.14)

Extracts the root field names from nested fields.

Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "item".

protected array extractRootFields ( array $fields )
$fields array

The fields requested for extraction

return array

Root fields extracted from the given nested fields

                protected function extractRootFields(array $fields)
{
    $result = [];
    foreach ($fields as $field) {
        $result[] = current(explode('.', $field, 2));
    }
    if (in_array('*', $result, true)) {
        $result = [];
    }
    return array_unique($result);
}

            
fields() public method

Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.

A field is a named element in the returned array by toArray().

This method should return an array of field names or field definitions. If the former, the field name will be treated as an object property name whose value will be used as the field value. If the latter, the array key should be the field name while the array value should be the corresponding field definition which can be either an object property name or a PHP callable returning the corresponding field value. The signature of the callable should be:

function ($model, $field) {
    // return field value
}

For example, the following code declares four fields:

  • email: the field name is the same as the property name email;
  • firstName and lastName: the field names are firstName and lastName, and their values are obtained from the first_name and last_name properties;
  • fullName: the field name is fullName. Its value is obtained by concatenating first_name and last_name.
return [
    'email',
    'firstName' => 'first_name',
    'lastName' => 'last_name',
    'fullName' => function () {
        return $this->first_name . ' ' . $this->last_name;
    },
];

In this method, you may also want to return different lists of fields based on some context information. For example, depending on the privilege of the current application user, you may return different sets of visible fields or filter out some fields.

The default implementation of this method returns the public object member variables indexed by themselves.

See also toArray().

public array fields ( )
return array

The list of field names or field definitions.

                public function fields()
{
    $fields = array_keys(Yii::getObjectVars($this));
    return array_combine($fields, $fields);
}

            
resolveFields() protected method

Determines which fields can be returned by toArray().

This method will first extract the root fields from the given fields. Then it will check the requested root fields against those declared in fields() and extraFields() to determine which fields can be returned.

protected array resolveFields ( array $fields, array $expand )
$fields array

The fields being requested for exporting

$expand array

The additional fields being requested for exporting

return array

The list of fields to be exported. The array keys are the field names, and the array values are the corresponding object property names or PHP callables returning the field values.

                protected function resolveFields(array $fields, array $expand)
{
    $fields = $this->extractRootFields($fields);
    $expand = $this->extractRootFields($expand);
    $result = [];
    foreach ($this->fields() as $field => $definition) {
        if (is_int($field)) {
            $field = $definition;
        }
        if (empty($fields) || in_array($field, $fields, true)) {
            $result[$field] = $definition;
        }
    }
    if (empty($expand)) {
        return $result;
    }
    foreach ($this->extraFields() as $field => $definition) {
        if (is_int($field)) {
            $field = $definition;
        }
        if (in_array($field, $expand, true)) {
            $result[$field] = $definition;
        }
    }
    return $result;
}

            
toArray() public method

Converts the model into an array.

This method will first identify which fields to be included in the resulting array by calling resolveFields(). It will then turn the model into an array with these fields. If $recursive is true, any embedded objects will also be converted into arrays. When embedded objects are yii\base\Arrayable, their respective nested fields will be extracted and passed to toArray().

If the model implements the yii\web\Linkable interface, the resulting array will also have a _link element which refers to a list of links as specified by the interface.

public array toArray ( array $fields = [], array $expand = [], $recursive true )
$fields array

The fields being requested. If empty or if it contains '*', all fields as specified by fields() will be returned. Fields can be nested, separated with dots (.). e.g.: item.field.sub-field $recursive must be true for nested fields to be extracted. If $recursive is false, only the root fields will be extracted.

$expand array

The additional fields being requested for exporting. Only fields declared in extraFields() will be considered. Expand can also be nested, separated with dots (.). e.g.: item.expand1.expand2 $recursive must be true for nested expands to be extracted. If $recursive is false, only the root expands will be extracted.

$recursive boolean

Whether to recursively return array representation of embedded objects.

return array

The array representation of the object

                public function toArray(array $fields = [], array $expand = [], $recursive = true)
{
    $data = [];
    foreach ($this->resolveFields($fields, $expand) as $field => $definition) {
        $attribute = is_string($definition) ? $this->$definition : $definition($this, $field);
        if ($recursive) {
            $nestedFields = $this->extractFieldsFor($fields, $field);
            $nestedExpand = $this->extractFieldsFor($expand, $field);
            if ($attribute instanceof Arrayable) {
                $attribute = $attribute->toArray($nestedFields, $nestedExpand);
            } elseif ($attribute instanceof \JsonSerializable) {
                $attribute = $attribute->jsonSerialize();
            } elseif (is_array($attribute)) {
                $attribute = array_map(
                    function ($item) use ($nestedFields, $nestedExpand) {
                        if ($item instanceof Arrayable) {
                            return $item->toArray($nestedFields, $nestedExpand);
                        } elseif ($item instanceof \JsonSerializable) {
                            return $item->jsonSerialize();
                        }
                        return $item;
                    },
                    $attribute
                );
            }
        }
        $data[$field] = $attribute;
    }
    if ($this instanceof Linkable) {
        $data['_links'] = Link::serialize($this->getLinks());
    }
    return $recursive ? ArrayHelper::toArray($data) : $data;
}