Passed
Pull Request — master (#48)
by
unknown
07:52 queued 04:23
created

GroupedIterator::append()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Zicht Online <http://zicht.nl>
4
 */
5
6
// todo: place the two classed in their own file
7
// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses
8
// phpcs:disable Zicht.Commenting.PropertyComment.VarTypeAvoidMixed
9
10
namespace Zicht\Itertools\lib;
11
12
use Zicht\Itertools\lib\Interfaces\FiniteIterableInterface;
13
use Zicht\Itertools\lib\Traits\FiniteIterableTrait;
14
15
class GroupedIterator extends \IteratorIterator implements FiniteIterableInterface
16
{
17
    use FiniteIterableTrait;
18
19
    /** @var mixed */
20
    protected $groupKey;
21
22
    /**
23
     * @param mixed $groupKey
24
     */
25 20
    public function __construct($groupKey)
26
    {
27 20
        $this->groupKey = $groupKey;
28 20
        parent::__construct(new \ArrayIterator());
29 20
    }
30
31
    /**
32
     * @return mixed
33
     */
34 18
    public function getGroupKey()
35
    {
36 18
        return $this->groupKey;
37
    }
38
39
    /**
40
     * Adds an element to the iterable
41
     *
42
     * @param mixed $key
43
     * @param mixed $value
44
     */
45 20
    public function append($key, $value)
46
    {
47 20
        $this->getInnerIterator()->append([$key, $value]);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Iterator as the method append() does only exist in the following implementations of said interface: AppendIterator, ArrayIterator, Issue523, RecursiveArrayIterator, Zicht\Itertools\lib\ChainIterator, Zicht\Itertools\lib\GroupedIterator.

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...
48 20
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53 18
    public function current()
54
    {
55 18
        return $this->getInnerIterator()->current()[1];
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61 18
    public function key()
62
    {
63 18
        return $this->getInnerIterator()->current()[0];
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69 11
    public function count()
70
    {
71 11
        return iterator_count($this->getInnerIterator());
72
    }
73
}
74
75
class GroupbyIterator extends \IteratorIterator implements FiniteIterableInterface
76
{
77
    use FiniteIterableTrait;
78
79
    /**
80
     * @param \Closure $func
81
     * @param \Iterator $iterable
82
     */
83 20
    public function __construct(\Closure $func, \Iterator $iterable)
84
    {
85
        // todo: this implementation pre-computes everything... this is
86
        // not the way an iterator should work.  Please re-write.
87 20
        $groupedIterator = null;
88 20
        $previousGroupKey = null;
89 20
        $data = [];
90
91 20
        foreach ($iterable as $key => $value) {
92 20
            $groupKey = call_user_func($func, $value, $key);
93 20
            if ($previousGroupKey !== $groupKey || $groupedIterator === null) {
94 20
                $previousGroupKey = $groupKey;
95 20
                $groupedIterator = new GroupedIterator($groupKey);
96 20
                $data [] = $groupedIterator;
97
            }
98 20
            $groupedIterator->append($key, $value);
99
        }
100
101 20
        parent::__construct(new \ArrayIterator($data));
102 20
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107 18
    public function key()
108
    {
109 18
        return $this->current()->getGroupKey();
110
    }
111
112
    /**
113
     * {@inheritdoc}
114
     */
115 11
    public function count()
116
    {
117 11
        return iterator_count($this->getInnerIterator());
118
    }
119
}
120