Completed
Push — master ( cb544b...3bd5ac )
by Lars
01:40
created

Collection::getIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
rs 10
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
 * @phpstan-template T
68
 * @phpstan-extends AbstractCollection<T>
69
 */
70
class Collection extends AbstractCollection
71
{
72
    /**
73
     * Constructs a collection object of the specified type, optionally with the
74
     * specified data.
75
     *
76
     * @param mixed              $data
77
     *                                                         <p>
78
     *                                                         The initial items to store in the
79
     *                                                         collection.
80
     *                                                         </p>
81
     * @param string             $iteratorClass                optional <p>
82
     *                                                         You can overwrite the
83
     *                                                         ArrayyIterator, but mostly you
84
     *                                                         don't need this option.
85
     *                                                         </p>
86
     * @param bool               $checkPropertiesInConstructor optional <p>
87
     *                                                         You need to extend the
88 56
     *                                                         "Arrayy"-class and you need to set
89
     *                                                         the
90
     *                                                         $checkPropertiesMismatchInConstructor
91
     *                                                         class property to true, otherwise
92
     *                                                         this option didn't not work
93
     *                                                         anyway.
94
     *                                                         </p>
95 56
     * @param TypeInterface|null $type
96 46
     *
97
     * @phpstan-param class-string $iteratorClass
98 56
     */
99 46
    public function __construct(
100
        $data = [],
101
        string $iteratorClass = null,
102 56
        bool $checkPropertiesInConstructor = null,
103 6
        TypeInterface $type = null
104
    ) {
105
        // fallback
106 56
        if ($iteratorClass === null) {
107 56
            $iteratorClass = ArrayyIterator::class;
108 56
        }
109 56
        if ($checkPropertiesInConstructor === null) {
110
            $checkPropertiesInConstructor = true;
111 45
        }
112
113
        if ($type !== null) {
114
            $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...
115
        }
116
117
        parent::__construct(
118
            $data,
119
            $iteratorClass,
120 6
            $checkPropertiesInConstructor
121
        );
122
    }
123
124
    /**
125 6
     * @param string|TypeCheckArray|TypeCheckInterface[] $type
126
     * @param array<mixed>                               $data
127 6
     * @param bool                                       $checkPropertiesInConstructorAndType
128 6
     *
129 6
     * @return static
130 6
     *
131 6
     * @phpstan-param array<T> $data
132
     * @phpstan-return static<T>
133
     */
134
    public static function construct(
135
        $type,
136
        $data = [],
137
        bool $checkPropertiesInConstructorAndType = true
138
    ): self {
139
        $type = self::convertIntoTypeCheckArray($type);
140 5
141
        return new static(
142 5
            $data,
143
            ArrayyIterator::class,
144
            $checkPropertiesInConstructorAndType,
145
            $type
146
        );
147
    }
148
149
    /**
150 1
     * The type (FQCN) associated with this collection.
151
     *
152
     * @return string|TypeCheckArray|TypeCheckInterface[]
153 1
     */
154
    public function getType()
155
    {
156
        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...
157
    }
158
159
    /**
160
     * Returns a new iterator, thus implementing the \Iterator interface.
161
     *
162
     * @return \ArrayIterator<mixed, mixed>
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayIterator<mixed, could not be parsed: Expected "|" or "end of type", but got "<" at position 14. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
163
     *                               <p>An iterator for the values in the array.</p>
164
     *
165
     * @phpstan-return \Iterator<T>
166
     *
167
     * @noinspection SenselessProxyMethodInspection
168
     */
169
    public function getIterator(): \Iterator
170
    {
171
        return parent::getIterator();
172
    }
173
174
    /**
175
     * Get a base Collection instance from this Collection.
176
     *
177
     * @return self
178
     *
179
     * @phpstan-return self<T>
180
     */
181
    public function toBase(): self
182
    {
183
        return self::construct($this->getType(), $this->getArray());
184
    }
185
}
186