Completed
Push — master ( 3bd5ac...d91a6c )
by Lars
01:37
created

Collection::getType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
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
 * @template T
68
 * @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
     *                                                         "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
     * @param TypeInterface|null $type
96
     *
97
     * @psalm-param array<T> $data
98
     * @psalm-param class-string<\ArrayIterator> $iteratorClass
99
     */
100 57
    public function __construct(
101
        $data = [],
102
        string $iteratorClass = null,
103
        bool $checkPropertiesInConstructor = null,
104
        TypeInterface $type = null
105
    ) {
106
        // fallback
107 57
        if ($iteratorClass === null) {
108 47
            $iteratorClass = ArrayyIterator::class;
109
        }
110 57
        if ($checkPropertiesInConstructor === null) {
111 47
            $checkPropertiesInConstructor = true;
112
        }
113
114 57
        if ($type !== null) {
115 5
            $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...
116
        }
117
118 57
        parent::__construct(
119 57
            $data,
120 57
            $iteratorClass,
121 57
            $checkPropertiesInConstructor
122
        );
123 46
    }
124
125
    /**
126
     * @param string|TypeCheckArray|TypeCheckInterface[] $type
127
     * @param array<mixed>                               $data
128
     * @param bool                                       $checkPropertiesInConstructorAndType
129
     *
130
     * @return static
131
     *
132
     * @psalm-param  class-string<T>|string|TypeCheckArray|TypeCheckInterface[] $type
133
     * @psalm-param  array<T> $data
134
     * @psalm-return static<T>
135
     */
136 6
    public static function construct(
137
        $type,
138
        $data = [],
139
        bool $checkPropertiesInConstructorAndType = true
140
    ): self {
141 6
        $type = self::convertIntoTypeCheckArray($type);
142
143 6
        return new static(
144 6
            $data,
145 6
            ArrayyIterator::class,
146 6
            $checkPropertiesInConstructorAndType,
147 6
            $type
148
        );
149
    }
150
151
    /**
152
     * Returns a new iterator, thus implementing the \Iterator interface.
153
     *
154
     * @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...
155
     *                               <p>An iterator for the values in the array.</p>
156
     *
157
     * @psalm-return \Iterator<T>
158
     *
159
     * @noinspection SenselessProxyMethodInspection
160
     */
161
    public function getIterator(): \Iterator
162
    {
163
        return parent::getIterator();
164
    }
165
166
    /**
167
     * The type (FQCN) associated with this collection.
168
     *
169
     * @return string|TypeCheckArray|TypeCheckInterface[]
170
     */
171 4
    public function getType()
172
    {
173 4
        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...
174
    }
175
176
    /**
177
     * Get a base Collection instance from this Collection.
178
     *
179
     * @return self
180
     *
181
     * @psalm-return self<T>
182
     */
183 1
    public function toBase(): self
184
    {
185 1
        return self::construct($this->getType(), $this->getArray());
186
    }
187
}
188