Passed
Push — master ( 355c97...01e0b8 )
by Michael
56s queued 11s
created

GroupbyIterator::toArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 12
ccs 9
cts 9
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Boudewijn Schoon <[email protected]>
4
 * @copyright Zicht Online <http://zicht.nl>
5
 */
6
7
namespace Zicht\Itertools\lib;
8
9
use Zicht\Itertools\lib\Interfaces\FiniteIterableInterface;
10
use Zicht\Itertools\lib\Traits\FiniteIterableTrait;
11
12
// todo: place the two classed in their own file
13
14
/**
15
 * Class GroupedIterator
16
 *
17
 * @package Zicht\Itertools\lib
18
 */
19
class GroupedIterator extends \IteratorIterator implements FiniteIterableInterface
20
{
21
    use FiniteIterableTrait;
22
23
    /** @var mixed */
24
    protected $groupKey;
25
26
    /**
27
     * GroupedIterator constructor.
28
     *
29
     * @param mixed $groupKey
30
     */
31 20
    public function __construct($groupKey)
32
    {
33 20
        $this->groupKey = $groupKey;
34 20
        parent::__construct(new \ArrayIterator());
35 20
    }
36
37
    /**
38
     * @return mixed
39
     */
40 18
    public function getGroupKey()
41
    {
42 18
        return $this->groupKey;
43
    }
44
45
    /**
46
     * Adds an element to the iterable
47
     *
48
     * @param mixed $key
49
     * @param mixed $value
50
     */
51 20
    public function append($key, $value)
52
    {
53 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...
54 20
    }
55
56
    /**
57
     * @{inheritDoc}
58
     */
59 18
    public function current()
60
    {
61 18
        return $this->getInnerIterator()->current()[1];
62
    }
63
64
    /**
65
     * @{inheritDoc}
66
     */
67 18
    public function key()
68
    {
69 18
        return $this->getInnerIterator()->current()[0];
70
    }
71
72
    /**
73
     * @{inheritDoc}
74
     */
75 11
    public function count()
76
    {
77 11
        return iterator_count($this->getInnerIterator());
78
    }
79
}
80
81
/**
82
 * Class GroupbyIterator
83
 *
84
 * @package Zicht\Itertools\lib
85
 */
86
class GroupbyIterator extends \IteratorIterator implements FiniteIterableInterface
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
87
{
88
    use FiniteIterableTrait;
89
90
    /**
91
     * GroupbyIterator constructor.
92
     *
93
     * @param \Closure $func
94
     * @param \Iterator $iterable
95
     */
96 20
    public function __construct(\Closure $func, \Iterator $iterable)
97
    {
98
        // todo: this implementation pre-computes everything... this is
99
        // not the way an iterator should work.  Please re-write.
100 20
        $groupedIterator = null;
101 20
        $previousGroupKey = null;
102 20
        $data = [];
103
104 20
        foreach ($iterable as $key => $value) {
105 20
            $groupKey = call_user_func($func, $value, $key);
106 20
            if ($previousGroupKey !== $groupKey || $groupedIterator === null) {
107 20
                $previousGroupKey = $groupKey;
108 20
                $groupedIterator = new GroupedIterator($groupKey);
109 20
                $data [] = $groupedIterator;
110 20
            }
111 20
            $groupedIterator->append($key, $value);
112 20
        }
113
114 20
        parent::__construct(new \ArrayIterator($data));
115 20
    }
116
117
    /**
118
     * @{inheritDoc}
119
     */
120 18
    public function key()
121
    {
122 18
        return $this->current()->getGroupKey();
123
    }
124
125
    /**
126
     * @{inheritDoc}
127
     */
128 11
    public function count()
129
    {
130 11
        return iterator_count($this->getInnerIterator());
131
    }
132
}
133