Passed
Push — master ( 1c0269...8ffc57 )
by
unknown
03:51 queued 01:27
created

GroupbyIterator::values()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 10
Ratio 100 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 0
dl 10
loc 10
ccs 6
cts 6
cp 1
crap 3
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 18
    public function __construct($groupKey)
32
    {
33 18
        $this->groupKey = $groupKey;
34 18
        parent::__construct(new \ArrayIterator());
35 18
    }
36
37
    /**
38
     * @return mixed
39
     */
40 16
    public function getGroupKey()
41
    {
42 16
        return $this->groupKey;
43
    }
44
45
    /**
46
     * Adds an element to the iterable
47
     *
48
     * @param mixed $key
49
     * @param mixed $value
50
     */
51 18
    public function append($key, $value)
52
    {
53 18
        $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 18
    }
55
56
    /**
57
     * @{inheritDoc}
58
     */
59 16
    public function current()
60
    {
61 16
        return $this->getInnerIterator()->current()[1];
62
    }
63
64
    /**
65
     * @{inheritDoc}
66
     */
67 16
    public function key()
68
    {
69 16
        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 18
    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 18
        $groupedIterator = null;
101 18
        $previousGroupKey = null;
102 18
        $data = [];
103
104 18
        foreach ($iterable as $key => $value) {
105 18
            $groupKey = call_user_func($func, $value, $key);
106 18
            if ($previousGroupKey !== $groupKey || $groupedIterator === null) {
107 18
                $previousGroupKey = $groupKey;
108 18
                $groupedIterator = new GroupedIterator($groupKey);
109 18
                $data [] = $groupedIterator;
110
            }
111 18
            $groupedIterator->append($key, $value);
112
        }
113
114 18
        parent::__construct(new \ArrayIterator($data));
115 18
    }
116
117
    /**
118
     * @{inheritDoc}
119
     */
120 16
    public function key()
121
    {
122 16
        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
    /**
134
     * @{inheritDoc}
135
     */
136 2
    public function toArray()
137
    {
138 2
        $array = iterator_to_array($this);
139 2
        array_walk(
140
            $array,
141 2
            function (&$value) {
142
                /** @var GroupedIterator $value */
143 2
                $value = $value->toArray();
144 2
            }
145
        );
146 2
        return $array;
147
    }
148
149
    /**
150
     * @{inheritDoc}
151
     */
152 2 View Code Duplication
    public function values()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
153
    {
154 2
        $values = [];
155 2
        if ($this instanceof \Traversable) {
156 2
            foreach ($this as $key => $value) {
157 2
                $values [] = $value->values();
158
            }
159
        }
160 2
        return $values;
161
    }
162
}
163