GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

ChangeBuilder::buildChange()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
rs 9.2
cc 4
eloc 9
nc 4
nop 3
1
<?php
2
3
namespace Isolate\UnitOfWork\Entity;
4
5
use Isolate\UnitOfWork\Entity\Definition\Association;
6
use Isolate\UnitOfWork\Entity\Definition\Property;
7
use Isolate\UnitOfWork\Entity\Definition\Repository;
8
use Isolate\UnitOfWork\Entity\Property\PHPUnitValueComparer;
9
use Isolate\UnitOfWork\Entity\Value\Change\AssociatedCollection;
10
use Isolate\UnitOfWork\Entity\Value\ChangeSet;
11
use Isolate\UnitOfWork\Entity\Value\Change\EditedEntity;
12
use Isolate\UnitOfWork\Entity\Value\Change\NewEntity;
13
use Isolate\UnitOfWork\Entity\Value\Change\RemovedEntity;
14
use Isolate\UnitOfWork\Object\PropertyAccessor;
15
use Isolate\UnitOfWork\Entity\Value\Change\ScalarChange;
16
use Isolate\UnitOfWork\Exception\RuntimeException;
17
18
/**
19
 * @api
20
 */
21
final class ChangeBuilder
22
{
23
    /**
24
     * @var PropertyAccessor
25
     */
26
    private $propertyAccessor;
27
28
    /**
29
     * @var PHPUnitValueComparer
30
     */
31
    private $propertyValueComparer;
32
33
    /**
34
     * @var Repository
35
     */
36
    private $definitions;
37
38
    /**
39
     * @var Identifier
40
     */
41
    private $identifier;
42
43
    /**
44
     * @param Repository $definitions
45
     * @param Identifier $identifier
46
     */
47
    public function __construct(Repository $definitions, Identifier $identifier)
48
    {
49
        $this->propertyAccessor = new PropertyAccessor();
50
        $this->propertyValueComparer = new PHPUnitValueComparer();
51
        $this->definitions = $definitions;
52
        $this->identifier = $identifier;
53
    }
54
55
    /**
56
     * @param $oldEntity
57
     * @param $newEntity
58
     * @return ChangeSet
59
     * @throws RuntimeException
60
     * 
61
     * @api
62
     */
63
    public function buildChanges($oldEntity, $newEntity)
64
    {
65
        $changes = [];
66
        $entityDefinition = $this->definitions->getDefinition($oldEntity);
67
        foreach ($entityDefinition->getObservedProperties() as $property) {
68
            if ($this->isDifferent($property, $oldEntity, $newEntity)) {
69
                $oldValue = $this->propertyAccessor->getValue($oldEntity, $property->getName());
70
                $newValue = $this->propertyAccessor->getValue($newEntity, $property->getName());
71
72
                $changes[] = $this->buildChange($property, $oldValue, $newValue);
73
            }
74
        }
75
76
        return new ChangeSet($changes);
77
    }
78
79
    /**
80
     * @param Property $property
81
     * @param $oldEntity
82
     * @param $newEntity
83
     * @return bool
84
     */
85
    private function isDifferent(Property $property, $oldEntity, $newEntity)
86
    {
87
        return $this->propertyValueComparer->hasDifferentValue($property, $newEntity, $oldEntity);
88
    }
89
90
    /**
91
     * @param Property $property
92
     * @param $oldValue
93
     * @param $newValue
94
     * @return \Isolate\UnitOfWork\Entity\Value\Change\ScalarChange
95
     * @throws RuntimeException
96
     */
97
    private function buildChange(Property $property, $oldValue, $newValue)
98
    {
99
        if ($property->isAssociated()) {
100
            $association = $property->getAssociation();
101
            switch ($association->getType()) {
102
                case Association::TO_SINGLE_ENTITY:
103
                    return $this->buildAssociationToSingleEntityChange($property, $oldValue, $newValue);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->buildAssoc... $oldValue, $newValue); (Isolate\UnitOfWork\Entit...lue\Change\EditedEntity) is incompatible with the return type documented by Isolate\UnitOfWork\Entit...ngeBuilder::buildChange of type Isolate\UnitOfWork\Entit...lue\Change\ScalarChange.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
104
                case Association::TO_MANY_ENTITIES;
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
105
                    return $this->buildAssociationToManyEntitiesChange($property, $oldValue, $newValue);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->buildAssoc... $oldValue, $newValue); (Isolate\UnitOfWork\Entit...ge\AssociatedCollection) is incompatible with the return type documented by Isolate\UnitOfWork\Entit...ngeBuilder::buildChange of type Isolate\UnitOfWork\Entit...lue\Change\ScalarChange.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
106
            }
107
        }
108
109
        return new ScalarChange($property, $oldValue, $newValue);
110
    }
111
112
    /**
113
     * @param Property $property
114
     * @param $oldValue
115
     * @param $newValue
116
     * @return EditedEntity|NewEntity|RemovedEntity
117
     * @throws RuntimeException
118
     */
119
    private function buildAssociationToSingleEntityChange(Property $property, $oldValue, $newValue)
120
    {
121
        if (is_null($newValue)) {
122
            return new RemovedEntity($property, $oldValue);
123
        }
124
125
        if (is_null($oldValue)) {
126
            $this->validateAssociatedEntity($property, $newValue);
127
128
            return new NewEntity($property, $newValue, $this->identifier->isPersisted($newValue));
129
        }
130
131
        return new EditedEntity(
132
            $property,
133
            $this->buildChanges($oldValue, $newValue),
134
            $oldValue,
135
            $newValue
136
        );
137
    }
138
139
    /**
140
     * @param Property $property
141
     * @param $oldValue
142
     * @param $newValue
143
     * @return AssociatedCollection
144
     * @throws RuntimeException
145
     */
146
    private function buildAssociationToManyEntitiesChange(Property $property, $oldValue, $newValue)
147
    {
148
        if (!$this->isTraversableArray($newValue)) {
149
            throw new RuntimeException(
150
                sprintf(
151
                    "Property \"%s\" is marked as associated with many entities and require new value to be traversable collection.",
152
                    $property->getName()
153
                )
154
            );
155
        }
156
157
158
        $oldPersistedArray = $this->toPersistedArray($oldValue);
159
        $newPersistedArray = [];
160
        $changes = [];
161
162
        foreach ($newValue as $newElement) {
163
            $this->validateAssociatedEntity($property, $newElement);
164
165
            if (!$this->identifier->isPersisted($newElement)) {
166
                $changes[] = new NewEntity($property, $newElement, false);
167
                continue;
168
            }
169
170
            $identity = $this->identifier->getIdentity($newElement);
171
            $newPersistedArray[$identity] = $newElement;
172
173
            if (array_key_exists($identity, $oldPersistedArray)) {
174
                $oldElement = $oldPersistedArray[$identity];
175
                $changeSet = $this->buildChanges($oldElement, $newElement);
176
177
                if ($changeSet->count()) {
178
                    $changes[] = new EditedEntity($property, $changeSet, $oldElement, $newElement);
179
                }
180
181
                continue;
182
            }
183
184
            $changes[] = new NewEntity($property, $newElement, true);
185
        }
186
187
        foreach ($oldPersistedArray as $identity => $oldElement) {
188
            if (!array_key_exists($identity, $newPersistedArray)) {
189
                $changes[] = new RemovedEntity($property, $oldElement);
190
            }
191
        }
192
193
        return new AssociatedCollection($property, $oldValue, $newValue, $changes);
194
    }
195
196
    /**
197
     * @param $traversableArray
198
     * @return array
199
     */
200
    private function toPersistedArray($traversableArray)
201
    {
202
        if (!$this->isTraversableArray($traversableArray)) {
203
            return [];
204
        }
205
206
        $result = [];
207
        foreach ($traversableArray as $valueElement) {
208
            $result[$this->identifier->getIdentity($valueElement)] = $valueElement;
209
        }
210
211
        return $result;
212
    }
213
214
    /**
215
     * @param Property $property
216
     * @param $newElement
217
     * @throws RuntimeException
218
     */
219
    private function validateAssociatedEntity(Property $property, $newElement)
220
    {
221
        if (!is_object($newElement) || !$property->getAssociation()->getTargetClassName()->isClassOf($newElement)) {
222
            throw new RuntimeException(
223
                sprintf(
224
                    "Property \"%s\" expects instanceof \"%s\" as a value.",
225
                    $property->getName(),
226
                    (string) $property->getAssociation()->getTargetClassName()
227
                )
228
            );
229
        }
230
    }
231
232
    /**
233
     * @param $newValue
234
     * @return bool
235
     */
236
    private function isTraversableArray($newValue)
237
    {
238
        return is_array($newValue) || ($newValue instanceof \Traversable && $newValue instanceof \ArrayAccess);
239
    }
240
}
241