Passed
Push — master ( 9efe7c...a42e22 )
by Anton
35s
created

ResourceTrait::getResourceRelationships()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 6
nop 1
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\web\Link;
11
use yii\web\Linkable;
12
13
trait ResourceTrait
14
{
15
    /**
16
     * @return string
17
     */
18
    public function getId()
19
    {
20
        return (string) ($this instanceof ActiveRecordInterface ? $this->getPrimaryKey() : null);
21
    }
22
23
    /**
24
     * @return string
25
     */
26
    public function getType()
27
    {
28
        $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...
29
        $className = $reflect->getShortName();
30
        return Inflector::camel2id($className);
31
    }
32
33
    /**
34
     * @param array $fields
35
     * @return array
36
     */
37
    public function getResourceAttributes(array $fields = [])
38
    {
39
        $attributes = [];
40
        if ($this instanceof Arrayable) {
41
            $fieldDefinitions = $this->fields();
42
        } else {
43
            $vars = array_keys(\Yii::getObjectVars($this));
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 13 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...
44
            $fieldDefinitions = array_combine($vars, $vars);
45
        }
46
47
        foreach ($this->resolveFields($fieldDefinitions, $fields) as $name => $definition) {
48
            $attributes[$name] = is_string($definition) ? $this->$definition : call_user_func($definition, $this, $name);
49
        }
50
        return $attributes;
51
    }
52
53
    /**
54
     * @param array $linked
55
     * @return array
56
     */
57
    public function getResourceRelationships(array $linked = [])
58
    {
59
        $fields = [];
60
        if ($this instanceof Arrayable) {
61
            $fields = $this->extraFields();
62
        }
63
        $resolvedFields = $this->resolveFields($fields);
64
        $keys = array_keys($resolvedFields);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 11 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...
65
66
        $relationships = array_fill_keys($keys, null);
67
        $linkedFields = array_intersect($keys, $linked);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 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...
68
69
        foreach ($linkedFields as $name) {
70
            $definition = $resolvedFields[$name];
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 11 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...
71
            $relationships[$name] = is_string($definition) ? $this->$definition : call_user_func($definition, $this, $name);
72
        }
73
74
        return $relationships;
75
    }
76
77
    /**
78
     * @param string $name the case sensitive name of the relationship.
79
     * @param array|ActiveRecordInterface $relationship
80
     */
81
    public function setResourceRelationship($name, $relationship)
82
    {
83
        /** @var $this ActiveRecordInterface */
84
        if (!$this instanceof ActiveRecordInterface) {
85
            return;
86
        }
87
        if (!is_array($relationship)) {
88
            $relationship = [$relationship];
89
        }
90
        foreach ($relationship as $key => $value) {
91
            if ($value instanceof ActiveRecordInterface) {
92
                $this->link($name, $value);
93
            }
94
        }
95
    }
96
97
    /**
98
     * @param string $name the case sensitive name of the relationship.
99
     * @return array
100
     */
101
    public function getRelationshipLinks($name)
102
    {
103
        if (!$this instanceof Linkable) {
104
            return [];
105
        }
106
        $primaryLinks = $this->getLinks();
107
        if (!array_key_exists(Link::REL_SELF, $primaryLinks)) {
108
            return [];
109
        }
110
        $resourceLink = is_string($primaryLinks[Link::REL_SELF]) ? rtrim($primaryLinks[Link::REL_SELF], '/') : null;
111
        if (!$resourceLink) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $resourceLink of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
112
            return [];
113
        }
114
        return [
115
            Link::REL_SELF => "{$resourceLink}/relationships/{$name}",
116
            'related' => "{$resourceLink}/{$name}",
117
        ];
118
    }
119
120
    /**
121
     * @param array $fields
122
     * @param array $fieldSet
123
     * @return array
124
     */
125
    protected function resolveFields(array $fields, array $fieldSet = [])
126
    {
127
        $result = [];
128
129
        foreach ($fields as $field => $definition) {
130
            if (is_int($field)) {
131
                $field = $definition;
132
            }
133
            $field = Inflector::camel2id(Inflector::variablize($field), '_');
134
            if (empty($fieldSet) || in_array($field, $fieldSet, true)) {
135
                $result[$field] = $definition;
136
            }
137
        }
138
139
        return $result;
140
    }
141
}
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...
142