GroupByTrait   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 54
Duplicated Lines 100 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 54
loc 54
ccs 8
cts 8
cp 1
rs 10
c 0
b 0
f 0
wmc 4
lcom 0
cbo 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A groupBy() 15 15 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * @copyright Zicht Online <http://zicht.nl>
4
 */
5
6
namespace Zicht\Itertools\lib\Traits;
7
8
use Zicht\Itertools\conversions;
9
use Zicht\Itertools\lib\GroupbyIterator;
10
11 View Code Duplication
trait GroupByTrait
0 ignored issues
show
Duplication introduced by
This class 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...
12
{
13
    /**
14
     * Make an iterator that returns consecutive groups from this
15
     * iterable.  Generally, this iterable needs to already be sorted on
16
     * the same key function.
17
     *
18
     * When $strategy is a string, the key is obtained through one of
19
     * the following:
20
     * 1. $value->{$strategy}, when $value is an object and
21
     *    $strategy is an existing property,
22
     * 2. call $value->{$strategy}(), when $value is an object and
23
     *    $strategy is an existing method,
24
     * 3. $value[$strategy], when $value is an array and $strategy
25
     *    is an existing key,
26
     * 4. otherwise the key will default to null.
27
     *
28
     * Alternatively $strategy can be a closure.  In this case the
29
     * $strategy closure is called with each value in this iterable and the
30
     * key will be its return value.  $strategy is called with two
31
     * parameters: the value and the key of the iterable as the first and
32
     * second parameter, respectively.
33
     *
34
     * The operation of groupBy() is similar to the uniq filter in Unix.
35
     * It generates a break or new group every time the value of the key
36
     * function changes (which is why it is usually necessary to have
37
     * sorted the data using the same key function).  That behavior
38
     * differs from SQL's GROUP BY which aggregates common elements
39
     * regardless of their input order.
40
     *
41
     * > $list = [['type'=>'A', 'title'=>'one'], ['type'=>'A', 'title'=>'two'], ['type'=>'B', 'title'=>'three']]
42
     * > iter\iterable($list)->groupBy('type')
43
     * 'A'=>[['type'=>'A', 'title'=>'one'], ['type'=>'A', 'title'=>'two']] 'B'=>[['type'=>'B', 'title'=>'three']]
44
     *
45
     * @param null|string|\Closure $strategy
46
     * @param bool $sort
47
     * @return GroupbyIterator
48
     */
49 24
    public function groupBy($strategy, $sort = true)
50
    {
51 24
        if (!is_bool($sort)) {
52 1
            throw new \InvalidArgumentException('Argument $sort must be a boolean');
53
        }
54
55 23
        if ($this instanceof \Iterator) {
56 22
            return new GroupbyIterator(
57 22
                conversions\mixed_to_value_getter($strategy),
0 ignored issues
show
Deprecated Code introduced by
The function Zicht\Itertools\conversi...mixed_to_value_getter() has been deprecated with message: Use \Zicht\Itertools\util\Conversions::mixedToClosure, will be removed in version 3.0

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
58 20
                $sort ? $this->sorted($strategy) : $this
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Iterator as the method sorted() does only exist in the following implementations of said interface: Zicht\Itertools\lib\AccumulateIterator, Zicht\Itertools\lib\ChainIterator, Zicht\Itertools\lib\CollapseIterator, Zicht\Itertools\lib\DifferenceIterator, Zicht\Itertools\lib\FilterIterator, Zicht\Itertools\lib\GroupbyIterator, Zicht\Itertools\lib\GroupedIterator, Zicht\Itertools\lib\IntersectionIterator, Zicht\Itertools\lib\IterableIterator, Zicht\Itertools\lib\MapByIterator, Zicht\Itertools\lib\MapIterator, Zicht\Itertools\lib\ReversedIterator, Zicht\Itertools\lib\SliceIterator, Zicht\Itertools\lib\SortedIterator, Zicht\Itertools\lib\StringIterator, Zicht\Itertools\lib\UniqueIterator, Zicht\Itertools\lib\ZipIterator.

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...
59
            );
60
        }
61
62 1
        return null;
63
    }
64
}
65