|
- <?php
-
-
- namespace yii\base;
-
- use Yii;
- use yii\helpers\ArrayHelper;
- use yii\web\Link;
- use yii\web\Linkable;
-
-
- trait ArrayableTrait
- {
-
-
- public function fields()
- {
- $fields = array_keys(Yii::getObjectVars($this));
- return array_combine($fields, $fields);
- }
-
-
-
- public function extraFields()
- {
- return [];
- }
-
-
-
- public function toArray(array $fields = [], array $expand = [], $recursive = true)
- {
- $data = [];
- foreach ($this->resolveFields($fields, $expand) as $field => $definition) {
- $data[$field] = is_string($definition) ? $this->$definition : call_user_func($definition, $this, $field);
- }
-
- if ($this instanceof Linkable) {
- $data['_links'] = Link::serialize($this->getLinks());
- }
-
- return $recursive ? ArrayHelper::toArray($data) : $data;
- }
-
-
-
- protected function resolveFields(array $fields, array $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;
- }
- }
|