Passed
Push — master ( 491c94...672c08 )
by Anton
03:46
created

ResourceTrait::setResourceRelationships()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
c 0
b 0
f 0
rs 9.2
cc 4
eloc 7
nc 6
nop 2
1
<?php
2
/**
3
 * @author Anton Tuyakhov <[email protected]>
4
 */
5
6
namespace tuyakhov\jsonapi;
7
8
use yii\base\Arrayable;
9
use yii\db\ActiveRecordInterface;
10
use yii\db\BaseActiveRecord;
11
use yii\helpers\ArrayHelper;
12
use yii\helpers\Inflector;
13
14
trait ResourceTrait
15
{
16
    /**
17
     * @return null|string
18
     */
19
    public function getId()
20
    {
21
        if ($this instanceof ActiveRecordInterface) {
22
            return (string) $this->getPrimaryKey();
23
        }
24
        return null;
25
    }
26
27
    /**
28
     * @return string
29
     */
30
    public function getType()
31
    {
32
        $reflect = new \ReflectionClass($this);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
33
        $className = $reflect->getShortName();
34
        return Inflector::pluralize(Inflector::camel2id($className));
35
    }
36
37
    /**
38
     * @param array $fields
39
     * @return array
40
     */
41
    public function getResourceAttributes(array $fields = [])
42
    {
43
        $attributes = [];
44
45
        foreach ($this->resolveFields($this->fields(), $fields) as $name => $definition) {
46
            $attributes[$name] = is_string($definition) ? $this->$definition : call_user_func($definition, $this, $name);
47
        }
48
        return $attributes;
49
    }
50
51
    /**
52
     * @return array
53
     */
54
    public function getResourceRelationships()
55
    {
56
        $relationships = [];
57
58
        foreach ($this->resolveFields($this->extraFields()) as $name => $definition) {
59
            if (is_string($definition)) {
60
                $relation = $this->$definition;
61
                if (!is_array($relation)) {
62
                    $relation = [$relation];
63
                }
64
                foreach ($relation as $item) {
65
                    if ($item instanceof ResourceIdentifierInterface) {
66
                        $relationships[$name]['data'] = ['id' => $item->getId(), 'type' => $item->getType()];
67
                    }
68
                }
69
                // TODO add links and meta. Should create interface
70
            }
71
        }
72
        return $relationships;
73
    }
74
75
    /**
76
     * @param string $name the case sensitive name of the relationship.
77
     * @param $relationship
78
     */
79
    public function setResourceRelationships($name, $relationship)
80
    {
81
        /** @var $this BaseActiveRecord */
82
        $this->unlinkAll($name);
83
        if (!is_array($relationship)) {
84
            $relationship = [$relationship];
85
        }
86
        foreach ($relationship as $key => $value) {
87
            if ($value instanceof ActiveRecordInterface) {
88
                $this->link($name, $value);
89
            }
90
        }
91
    }
92
93
    /**
94
     * @param array $fields
95
     * @param array $expand
96
     * @param bool $recursive
97
     * @return array
98
     */
99
    public function toArray(array $fields = [], array $expand = [], $recursive = true)
0 ignored issues
show
Unused Code introduced by
The parameter $expand is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
100
    {
101
        $data = [
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 10 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
102
            'id' => $this->getId(),
103
            'type' => $this->getType(),
104
        ];
105
        $attributes = $this->getResourceAttributes($fields);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
106
        $relationships = $this->getResourceRelationships();
107
        if (!empty($attributes)) {
108
            $data['attributes'] = $attributes;
109
        }
110
        if (!empty($relationships)) {
111
            $data['relationships'] = $relationships;
112
        }
113
114
        // TODO add links and meta. Should create interface
115
116
        return $recursive ? ArrayHelper::toArray($data) : $data;
117
    }
118
119
    /**
120
     * @return array
121
     */
122
    public function fields()
123
    {
124
        $fields = array_keys(\Yii::getObjectVars($this));
125
        return array_combine($fields, $fields);
126
    }
127
128
    /**
129
     * @return array
130
     */
131
    public function extraFields()
132
    {
133
        return [];
134
    }
135
136
    /**
137
     * @param array $fields
138
     * @param array $fieldSet
139
     * @return array
140
     */
141
    protected function resolveFields(array $fields, array $fieldSet = [])
142
    {
143
        $result = [];
144
145
        foreach ($fields as $field => $definition) {
146
            if (is_int($field)) {
147
                $field = $definition;
148
            }
149
            if (empty($fieldSet) || in_array($field, $fieldSet, true)) {
150
                $result[$field] = $definition;
151
            }
152
        }
153
154
        return $result;
155
    }
156
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
157