Passed
Push — master ( 53c726...5a2a34 )
by Anton
02:23
created

ResourceTrait   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 120
Duplicated Lines 5 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
dl 6
loc 120
c 0
b 0
f 0
wmc 25
lcom 0
cbo 5
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getId() 0 7 2
A getType() 0 6 1
A getResourceAttributes() 3 15 4
A getResourceRelationships() 3 13 4
A setResourceRelationship() 0 11 4
B getRelationshipLinks() 0 18 5
B resolveFields() 0 15 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\helpers\Inflector;
11
use yii\web\Link;
12
use yii\web\Linkable;
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
        if ($this instanceof Arrayable) {
45
            $fieldDefinitions = $this->fields();
46
        } else {
47
            $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...
48
            $fieldDefinitions = array_combine($vars, $vars);
49
        }
50
51 View Code Duplication
        foreach ($this->resolveFields($fieldDefinitions, $fields) as $name => $definition) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
52
            $attributes[$name] = is_string($definition) ? $this->$definition : call_user_func($definition, $this, $name);
53
        }
54
        return $attributes;
55
    }
56
57
    /**
58
     * @return array
59
     */
60
    public function getResourceRelationships()
61
    {
62
        $relationships = [];
63
        $fields = [];
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 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...
64
        if ($this instanceof Arrayable) {
65
            $fields = $this->extraFields();
66
        }
67
68 View Code Duplication
        foreach ($this->resolveFields($fields) as $name => $definition) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
69
            $relationships[$name] = is_string($definition) ? $this->$definition : call_user_func($definition, $this, $name);
70
        }
71
        return $relationships;
72
    }
73
74
    /**
75
     * @param string $name the case sensitive name of the relationship.
76
     * @param $relationship
77
     */
78
    public function setResourceRelationship($name, $relationship)
79
    {
80
        if (!is_array($relationship)) {
81
            $relationship = [$relationship];
82
        }
83
        foreach ($relationship as $key => $value) {
84
            if ($value instanceof ActiveRecordInterface) {
85
                $this->link($name, $value);
0 ignored issues
show
Bug introduced by
It seems like link() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
86
            }
87
        }
88
    }
89
90
    /**
91
     * @param string $name the case sensitive name of the relationship.
92
     * @return array
93
     */
94
    public function getRelationshipLinks($name)
95
    {
96
        if (!$this instanceof Linkable) {
97
            return [];
98
        }
99
        $primaryLinks = $this->getLinks();
100
        if (!array_key_exists(Link::REL_SELF, $primaryLinks)) {
101
            return [];
102
        }
103
        $resourceLink = is_string($primaryLinks[Link::REL_SELF]) ? rtrim($primaryLinks[Link::REL_SELF], '/') : null;
104
        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...
105
            return [];
106
        }
107
        return [
108
            Link::REL_SELF => "{$resourceLink}/relationships/{$name}",
109
            'related' => "{$resourceLink}/{$name}",
110
        ];
111
    }
112
113
    /**
114
     * @param array $fields
115
     * @param array $fieldSet
116
     * @return array
117
     */
118
    protected function resolveFields(array $fields, array $fieldSet = [])
119
    {
120
        $result = [];
121
122
        foreach ($fields as $field => $definition) {
123
            if (is_int($field)) {
124
                $field = $definition;
125
            }
126
            if (empty($fieldSet) || in_array($field, $fieldSet, true)) {
127
                $result[$field] = $definition;
128
            }
129
        }
130
131
        return $result;
132
    }
133
}
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...
134