Completed
Pull Request — master (#6354)
by COLE
10:36
created

LimitSubqueryWalker   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 138
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 98.21%

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 11
dl 0
loc 138
ccs 55
cts 56
cp 0.9821
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
D validate() 0 29 10
A createSelectExpressionItem() 0 12 2
B walkSelectStatement() 0 58 7
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ORM\Tools\Pagination;
21
22
use Doctrine\DBAL\Types\Type;
23
use Doctrine\ORM\Mapping\ClassMetadataInfo;
24
use Doctrine\ORM\Query;
25
use Doctrine\ORM\Query\TreeWalkerAdapter;
26
use Doctrine\ORM\Query\AST\Functions\IdentityFunction;
27
use Doctrine\ORM\Query\AST\PathExpression;
28
use Doctrine\ORM\Query\AST\SelectExpression;
29
use Doctrine\ORM\Query\AST\SelectStatement;
30
31
/**
32
 * Replaces the selectClause of the AST with a SELECT DISTINCT root.id equivalent.
33
 *
34
 * @category    DoctrineExtensions
35
 * @package     DoctrineExtensions\Paginate
36
 * @author      David Abdemoulaie <[email protected]>
37
 * @copyright   Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/)
38
 * @license     http://hobodave.com/license.txt New BSD License
39
 */
40
class LimitSubqueryWalker extends TreeWalkerAdapter
41
{
42
    /**
43
     * ID type hint.
44
     */
45
    const IDENTIFIER_TYPE = 'doctrine_paginator.id.type';
46
47
    /**
48
     * Counter for generating unique order column aliases.
49
     *
50
     * @var int
51
     */
52
    private $_aliasCounter = 0;
53
54
    /**
55
     * Walks down a SelectStatement AST node, modifying it to retrieve DISTINCT ids
56
     * of the root Entity.
57
     *
58
     * @param SelectStatement $AST
59
     *
60
     * @return void
61
     *
62
     * @throws \RuntimeException
63
     */
64 9
    public function walkSelectStatement(SelectStatement $AST)
65
    {
66 9
        $queryComponents = $this->_getQueryComponents();
67
        // Get the root entity and alias from the AST fromClause
68 9
        $from      = $AST->fromClause->identificationVariableDeclarations;
69 9
        $fromRoot  = reset($from);
70 9
        $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable;
71 9
        $rootClass = $queryComponents[$rootAlias]['metadata'];
72 9
        $selectExpressions = [];
73
74 9
        $this->validate($AST);
75
76 7
        foreach ($queryComponents as $dqlAlias => $qComp) {
77
            // Preserve mixed data in query for ordering.
78 7
            if (isset($qComp['resultVariable'])) {
79 1
                $selectExpressions[] = new SelectExpression($qComp['resultVariable'], $dqlAlias);
80 7
                continue;
81
            }
82
        }
83
84 7
        $identifier = $rootClass->getSingleIdentifierFieldName();
85
86 7
        if (isset($rootClass->associationMappings[$identifier])) {
87 1
            throw new \RuntimeException("Paginating an entity with foreign key as identifier only works when using the Output Walkers. Call Paginator#setUseOutputWalkers(true) before iterating the paginator.");
88
        }
89
90 6
        $this->_getQuery()->setHint(
91 6
            self::IDENTIFIER_TYPE,
92 6
            Type::getType($rootClass->fieldMappings[$identifier]['type'])
93
        );
94
95 6
        $pathExpression = new PathExpression(
96 6
            PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION,
97
            $rootAlias,
98
            $identifier
99
        );
100
101 6
        $pathExpression->type = PathExpression::TYPE_STATE_FIELD;
102
103 6
        array_unshift($selectExpressions, new SelectExpression($pathExpression, '_dctrn_id'));
104
105 6
        $AST->selectClause->selectExpressions = $selectExpressions;
106
107 6
        if (isset($AST->orderByClause)) {
108 3
            foreach ($AST->orderByClause->orderByItems as $item) {
109 3
                if ( ! $item->expression instanceof PathExpression) {
110
                    continue;
111
                }
112
113 3
                $AST->selectClause->selectExpressions[] = new SelectExpression(
114 3
                    $this->createSelectExpressionItem($item->expression),
115 3
                    '_dctrn_ord' . $this->_aliasCounter++
116
                );
117
            }
118
        }
119
120 6
        $AST->selectClause->isDistinct = true;
121 6
    }
122
123
    /**
124
     * Validate the AST to ensure that this walker is able to properly manipulate it.
125
     *
126
     * @param SelectStatement $AST
127
     */
128 9
    private function validate(SelectStatement $AST)
129
    {
130
        // Prevent LimitSubqueryWalker from being used with queries that include
131
        // a limit, a fetched to-many join, and an order by condition that
132
        // references a column from the fetch joined table.
133 9
        $queryComponents = $this->getQueryComponents();
134 9
        $query           = $this->_getQuery();
135 9
        $from            = $AST->fromClause->identificationVariableDeclarations;
136 9
        $fromRoot        = reset($from);
137
138 9
        if ($query instanceof Query
139 9
            && $query->getMaxResults()
140 9
            && $AST->orderByClause
141 9
            && count($fromRoot->joins)) {
142
            // Check each orderby item.
143
            // TODO: check complex orderby items too...
144 2
            foreach ($AST->orderByClause->orderByItems as $orderByItem) {
145 2
                $expression = $orderByItem->expression;
146 2
                if ($orderByItem->expression instanceof PathExpression
147 2
                    && isset($queryComponents[$expression->identificationVariable])) {
148 2
                    $queryComponent = $queryComponents[$expression->identificationVariable];
149 2
                    if (isset($queryComponent['parent'])
150 2
                        && $queryComponent['relation']['type'] & ClassMetadataInfo::TO_MANY) {
151 2
                        throw new \RuntimeException("Cannot select distinct identifiers from query with LIMIT and ORDER BY on a column from a fetch joined to-many association. Use output walkers.");
152
                    }
153
                }
154
            }
155
        }
156 7
    }
157
158
    /**
159
     * Retrieve either an IdentityFunction (IDENTITY(u.assoc)) or a state field (u.name).
160
     *
161
     * @param \Doctrine\ORM\Query\AST\PathExpression $pathExpression
162
     *
163
     * @return \Doctrine\ORM\Query\AST\Functions\IdentityFunction
164
     */
165 3
    private function createSelectExpressionItem(PathExpression $pathExpression)
166
    {
167 3
        if ($pathExpression->type === PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION) {
168 1
            $identity = new IdentityFunction('identity');
169
170 1
            $identity->pathExpression = clone $pathExpression;
171
172 1
            return $identity;
173
        }
174
175 2
        return clone $pathExpression;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return clone $pathExpression; (Doctrine\ORM\Query\AST\PathExpression) is incompatible with the return type documented by Doctrine\ORM\Tools\Pagin...ateSelectExpressionItem of type Doctrine\ORM\Query\AST\Functions\IdentityFunction.

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...
176
    }
177
}
178