Completed
Push — master ( e9b885...d44876 )
by Christopher
02:27
created

ValueObjectCollection::sort()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 0
cts 6
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
1
<?php namespace C4tech\RayEmitter\Domain;
2
3
use C4tech\RayEmitter\Contracts\Domain\ValueObject as ValueObjectInterface;
4
use Illuminate\Support\Collection;
5
6
abstract class ValueObjectCollection extends ValueObject
7
{
8
    /**
9
     * Collection Class
10
     *
11
     * Class name of member Value Objects
12
     * @var string
13
     */
14
    protected $collectionClass = '';
15
16
    public function __construct(array $values = [])
17
    {
18
        $this->values = new Collection($values);
0 ignored issues
show
Bug introduced by
The property values does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
19
        $this->sort();
20
    }
21
22
    /**
23
     * @inheritDoc
24
     */
25
    public function equals(ValueObjectInterface $other)
26
    {
27
        if (get_class($other) !== get_class($this)) {
28
            return false;
29
        }
30
31
        if ($other->getHash() === $this->getHash()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface C4tech\RayEmitter\Contracts\Domain\ValueObject as the method getHash() does only exist in the following implementations of said interface: C4tech\RayEmitter\Domain\ValueObjectCollection.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
32
            return true;
33
        }
34
35
        return false;
36
    }
37
38
    /**
39
     * Get Hash
40
     *
41
     * Calculate an md5 sum of the collection.
42
     * @return string
43
     */
44
    public function getHash()
45
    {
46
        return hash('md5', json_encode($this->values));
47
    }
48
49
    /**
50
     * @inheritDoc
51
     */
52
    public function getValue()
53
    {
54
        return $this->values->all();
55
    }
56
57
    /**
58
     * @inheritDoc
59
     */
60
    public function jsonSerialize()
61
    {
62
        return [
63
            'class' => $this->collectionClass,
64
            'values' => $this->values->jsonSerialize()
65
        ];
66
    }
67
68
    /**
69
     * @inheritDoc
70
     */
71
    public static function jsonUnserialize($json)
72
    {
73
        $data = json_decode($json, true);
74
        $class = $data['class'];
75
76
        $values = array_map(
77
            function ($value) use ($class) {
78
                return new $class($value);
79
            },
80
            $data['values']
81
        );
82
83
        return new static($values);
84
    }
85
86
    public function push(ValueObject $value)
87
    {
88
        $this->values->push($value);
89
    }
90
91
    /**
92
     * Sort By Value
93
     *
94
     * Sort the array by the VO's value.
95
     * @return void
96
     */
97
    private function sort()
98
    {
99
        $this->values = $this->values->sortBy(function ($item) {
100
            return $item->getValue();
101
        });
102
    }
103
}
104