Completed
Push — master ( 51e589...982789 )
by Lars
17:41 queued 16:08
created

Collection::__construct()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
nc 8
nop 4
dl 0
loc 24
ccs 10
cts 10
cp 1
crap 4
rs 9.536
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arrayy\Collection;
6
7
use Arrayy\ArrayyIterator;
8
use Arrayy\Type\TypeInterface;
9
use Arrayy\TypeCheck\TypeCheckArray;
10
use Arrayy\TypeCheck\TypeCheckInterface;
11
12
/**
13
 * A collection represents a group of objects.
14
 *
15
 * Each object in the collection is of a specific, defined type.
16
 *
17
 * This is a direct implementation of `CollectionSetTypeInterface`,
18
 * which provides a simple api for your collections.
19
 *
20
 * Example usage:
21
 *
22
 * ``` php
23
 * $collection = new \Arrayy\Collection\Collection(\My\FooInterface::class);
24
 * $collection->add(new \My\Foo());
25
 * $collection->add(new \My\Foo());
26
 *
27
 * foreach ($collection as $foo) {
28
 *     if ($foo instanceof \My\FooInterface) {
29
 *         // Do something with $foo
30
 *     }
31
 * }
32
 * ```
33
 *
34
 * It is preferable to subclass `AbstractCollection` to create your own typed
35
 * collections. For example:
36
 *
37
 * ``` php
38
 * namespace My;
39
 *
40
 * class FooCollection extends \Arrayy\Collection\AbstractCollection
41
 * {
42
 *     public function getType()
43
 *     {
44
 *         return FooInterface::class;
45
 *     }
46
 * }
47
 * ```
48
 *
49
 * And then use it similarly to the earlier example:
50
 *
51
 * ``` php
52
 * namespace My;
53
 *
54
 * $fooCollection = new \My\FooCollection();
55
 * $fooCollection->add(new \My\Foo());
56
 * $fooCollection->add(new \My\Foo());
57
 *
58
 * foreach ($fooCollection as $foo) {
59
 *     if ($foo instanceof \My\FooInterface) {
60
 *         // Do something with $foo
61
 *     }
62
 * }
63
 * ```
64
 *
65
 * INFO: this collection thingy is inspired by https://github.com/ramsey/collection/
66
 *
67
 * @template TKey of array-key
68
 * @template T
69
 * @extends  AbstractCollection<TKey,T>
70
 */
71
class Collection extends AbstractCollection
72
{
73
    /**
74
     * Constructs a collection object of the specified type, optionally with the
75
     * specified data.
76
     *
77
     * @param mixed              $data
78
     *                                                         <p>
79
     *                                                         The initial items to store in the
80
     *                                                         collection.
81
     *                                                         </p>
82
     * @param string             $iteratorClass                optional <p>
83
     *                                                         You can overwrite the
84
     *                                                         ArrayyIterator, but mostly you
85
     *                                                         don't need this option.
86
     *                                                         </p>
87
     * @param bool               $checkPropertiesInConstructor optional <p>
88
     *                                                         You need to extend the
89
     *                                                         "Arrayy"-class and you need to set
90
     *                                                         the
91
     *                                                         $checkPropertiesMismatchInConstructor
92
     *                                                         class property to true, otherwise
93
     *                                                         this option didn't not work
94
     *                                                         anyway.
95
     *                                                         </p>
96
     * @param TypeInterface|null $type
97
     *
98
     * @psalm-param array<array-key,T>|array<TKey,T>|\Arrayy\Arrayy<TKey,T> $data
99
     * @psalm-param class-string<\Arrayy\ArrayyIterator> $iteratorClass
100
     */
101 64
    public function __construct(
102
        $data = [],
103
        string $iteratorClass = null,
104
        bool $checkPropertiesInConstructor = null,
105
        TypeInterface $type = null
106
    ) {
107
        // fallback
108 64
        if ($iteratorClass === null) {
109 50
            $iteratorClass = ArrayyIterator::class;
110
        }
111 64
        if ($checkPropertiesInConstructor === null) {
112 50
            $checkPropertiesInConstructor = true;
113
        }
114
115 64
        if ($type !== null) {
116 9
            $this->properties = $type;
0 ignored issues
show
Documentation Bug introduced by
It seems like $type of type object<Arrayy\Type\TypeInterface> is incompatible with the declared type array of property $properties.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
117
        }
118
119 64
        parent::__construct(
120 64
            $data,
121
            $iteratorClass,
122
            $checkPropertiesInConstructor
123
        );
124 51
    }
125
126
    /**
127
     * @param string|TypeCheckArray|TypeCheckInterface[] $type
128
     * @param array<mixed>                               $data
129
     * @param bool                                       $checkPropertiesInConstructorAndType
130
     *
131
     * @return static
132
     *
133
     * @template     TKeyConstruct of array-key
134
     * @template     TConstruct
135
     * @psalm-param  string|class-string|class-string<TConstruct>|TypeInterface|TypeCheckArray<array-key,TypeCheckInterface>|array<TypeCheckInterface> $type
136
     * @psalm-param  array<TKeyConstruct,TConstruct> $data
137
     * @psalm-return static<TKeyConstruct,TConstruct>
138
     */
139 6
    public static function construct(
140
        $type,
141
        $data = [],
142
        bool $checkPropertiesInConstructorAndType = true
143
    ): self {
144 6
        $type = self::convertIntoTypeCheckArray($type);
145
146 6
        return new static(
147 6
            $data,
148 6
            ArrayyIterator::class,
149
            $checkPropertiesInConstructorAndType,
150
            $type
151
        );
152
    }
153
154
    /**
155
     * Returns a new iterator, thus implementing the \Iterator interface.
156
     *
157
     * @return \Iterator
158
     *                   <p>An iterator for the values in the array.</p>
159
     *
160
     * @psalm-return \Iterator<T>
161
     *
162
     * @noinspection SenselessProxyMethodInspection
163
     */
164
    public function getIterator(): \Iterator
165
    {
166
        return parent::getIterator();
167
    }
168
169
    /**
170
     * The type (FQCN) associated with this collection.
171
     *
172
     * @return string|TypeCheckArray|TypeCheckInterface[]
173
     *
174
     * @psalm-return string|class-string|class-string<T>|TypeInterface|TypeCheckArray<TKey,T>|TypeCheckArray<int|string,mixed>|array<TypeCheckInterface>|array<array-key,TypeCheckInterface>
175
     */
176 8
    public function getType()
177
    {
178 8
        return $this->properties;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->properties; (array) is incompatible with the return type declared by the interface Arrayy\Collection\CollectionInterface::getType of type string|string[]|Arrayy\T...ck\TypeCheckInterface[].

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...
179
    }
180
181
    /**
182
     * Get a base Collection instance from this Collection.
183
     *
184
     * @return self
185
     *
186
     * @psalm-return self<TKey,T>
187
     *
188
     * @psalm-suppress InvalidReturnStatement - why?
189
     * @psalm-suppress InvalidReturnType - why?
190
     */
191 1
    public function toBase(): self
192
    {
193 1
        return self::construct(
194 1
            $this->getType(),
195 1
            $this->getArray()
196
        );
197
    }
198
}
199