Completed
Push — master ( b7ef6a...58a002 )
by Kirill
03:12
created

GroupBuilder::apply()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 7
cp 0.8571
rs 9.8666
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 3.0261
1
<?php
2
/**
3
 * This file is part of Hydrogen package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace RDS\Hydrogen\Processor\DatabaseProcessor;
11
12
use Doctrine\ORM\Query\Expr\Andx;
13
use Doctrine\ORM\QueryBuilder;
14
use phpDocumentor\Reflection\Types\Static_;
15
use RDS\Hydrogen\Criteria\Criterion;
16
use RDS\Hydrogen\Criteria\CriterionInterface;
17
use RDS\Hydrogen\Criteria\WhereGroup;
18
use RDS\Hydrogen\Criteria\Where;
19
use RDS\Hydrogen\Processor\DatabaseProcessor\Common\Expression;
20
21
/**
22
 * Class GroupBuilder
23
 */
24
class GroupBuilder extends Builder
25
{
26
    /**
27
     * @var string[]|Criterion[]
28
     */
29
    protected const ALLOWED_INNER_TYPES = [
30
        Where::class      => 'applyWhere',
31
        WhereGroup::class => 'applyGroup'
32
    ];
33
34
    /**
35
     * @param QueryBuilder $builder
36
     * @param CriterionInterface|WhereGroup $group
37
     * @return iterable|null
38
     */
39 2
    public function apply($builder, CriterionInterface $group): ?iterable
40
    {
41 2
        $expression = $builder->expr()->andX();
42
43 2
        foreach ($this->getInnerSelections($group) as $criterion => $fn) {
0 ignored issues
show
Compatibility introduced by
$group of type object<RDS\Hydrogen\Criteria\CriterionInterface> is not a sub-type of object<RDS\Hydrogen\Criteria\WhereGroup>. It seems like you assume a concrete implementation of the interface RDS\Hydrogen\Criteria\CriterionInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
44 2
            yield from $fn($builder, $expression, $criterion);
45
        }
46
47 2
        return $group->isAnd()
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface RDS\Hydrogen\Criteria\CriterionInterface as the method isAnd() does only exist in the following implementations of said interface: RDS\Hydrogen\Criteria\Having, RDS\Hydrogen\Criteria\HavingGroup, RDS\Hydrogen\Criteria\Where, RDS\Hydrogen\Criteria\WhereGroup.

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...
Bug Best Practice introduced by
The return type of return $group->isAnd() ?...->orWhere($expression); (Doctrine\ORM\QueryBuilder) is incompatible with the return type declared by the interface RDS\Hydrogen\Processor\BuilderInterface::apply of type RDS\Hydrogen\Processor\iterable|null.

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...
48
            ? $builder->andWhere($expression)
49 2
            : $builder->orWhere($expression);
50
    }
51
52
    /**
53
     * @param QueryBuilder $builder
54
     * @param Andx $context
55
     * @param WhereGroup $group
56
     * @return \Generator
57
     */
58
    protected function applyGroup(QueryBuilder $builder, Andx $context, WhereGroup $group): \Generator
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
59
    {
60
        return $this->apply($builder, $group);
61
    }
62
63
    /**
64
     * @param QueryBuilder $builder
65
     * @param Andx $context
66
     * @param Where $where
67
     * @return \Generator
68
     */
69 2
    protected function applyWhere(QueryBuilder $builder, Andx $context, Where $where): \Generator
70
    {
71 2
        $expression = new Expression($builder, $where->getOperator(), $where->getValue());
72 2
        yield from $result = $expression->create($where->getField());
73
74 2
        if ($where->isAnd()) {
75 2
            $context->add($result->getReturn());
76
        } else {
77 2
            $builder->orWhere($result->getReturn());
78
        }
79 2
    }
80
81
    /**
82
     * @param WhereGroup $group
83
     * @return iterable|callable[]
84
     */
85 2
    protected function getInnerSelections(WhereGroup $group): iterable
86
    {
87 2
        $query = $group->getQuery();
88
89 2
        foreach ($query->getCriteria() as $criterion) {
90 2
            foreach (static::ALLOWED_INNER_TYPES as $typeOf => $fn) {
91 2
                if ($criterion instanceof $typeOf) {
92 2
                    yield $criterion => [$this, $fn];
93 2
                    continue 2;
94
                }
95
            }
96
97
            $error = 'Groups not allowed for %s criterion';
98
            throw new \LogicException(\sprintf($error, \get_class($criterion)));
99
        }
100 2
    }
101
}
102