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

HavingGroupBuilder   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 6
dl 0
loc 45
ccs 0
cts 18
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A apply() 0 10 3
A applyWhere() 0 11 2
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 RDS\Hydrogen\Criteria\Criterion;
15
use RDS\Hydrogen\Criteria\CriterionInterface;
16
use RDS\Hydrogen\Criteria\WhereGroup;
17
use RDS\Hydrogen\Criteria\Having;
18
use RDS\Hydrogen\Criteria\Where;
19
use RDS\Hydrogen\Processor\DatabaseProcessor\Common\Expression;
20
21
/**
22
 * Class HavingGroupBuilder
23
 */
24
class HavingGroupBuilder extends GroupBuilder
25
{
26
    /**
27
     * @var string[]|Criterion[]
28
     */
29
    protected const ALLOWED_INNER_TYPES = [
30
        Where::class      => 'applyWhere',
31
        Having::class     => 'applyWhere',
32
        WhereGroup::class => 'applyGroup',
33
    ];
34
35
    /**
36
     * @param QueryBuilder $builder
37
     * @param CriterionInterface|WhereGroup $group
38
     * @return iterable|null
39
     */
40
    public function apply($builder, CriterionInterface $group): ?iterable
41
    {
42
        $expression = $builder->expr()->andX();
43
44
        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...
45
            yield from $fn($builder, $expression, $criterion);
46
        }
47
48
        return $group->isAnd() ? $builder->andHaving($expression) : $builder->orHaving($expression);
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() ?...>orHaving($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...
49
    }
50
51
    /**
52
     * @param QueryBuilder $builder
53
     * @param Andx $context
54
     * @param Where $where
55
     * @return \Generator
56
     */
57
    final protected function applyWhere(QueryBuilder $builder, Andx $context, Where $where): \Generator
58
    {
59
        $expression = new Expression($builder, $where->getOperator(), $where->getValue());
60
        yield from $result = $expression->create($where->getField());
61
62
        if ($where->isAnd()) {
63
            $context->add($result->getReturn());
64
        } else {
65
            $builder->orHaving($result->getReturn());
66
        }
67
    }
68
}
69