Completed
Pull Request — master (#6055)
by Martin
09:59
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
/**
4
 * Doctrine ORM
5
 *
6
 * LICENSE
7
 *
8
 * This source file is subject to the new BSD license that is bundled
9
 * with this package in the file LICENSE. This license can also be viewed
10
 * at http://hobodave.com/license.txt
11
 *
12
 * @category    DoctrineExtensions
13
 * @package     DoctrineExtensions\Paginate
14
 * @author      David Abdemoulaie <[email protected]>
15
 * @copyright   Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/)
16
 * @license     http://hobodave.com/license.txt New BSD License
17
 */
18
19
namespace Doctrine\ORM\Tools\Pagination;
20
21
use Doctrine\DBAL\Types\Type;
22
use Doctrine\ORM\Mapping\ClassMetadataInfo;
23
use Doctrine\ORM\Query;
24
use Doctrine\ORM\Query\TreeWalkerAdapter;
25
use Doctrine\ORM\Query\AST\Functions\IdentityFunction;
26
use Doctrine\ORM\Query\AST\PathExpression;
27
use Doctrine\ORM\Query\AST\SelectExpression;
28
use Doctrine\ORM\Query\AST\SelectStatement;
29
30
/**
31
 * Replaces the selectClause of the AST with a SELECT DISTINCT root.id equivalent.
32
 *
33
 * @category    DoctrineExtensions
34
 * @package     DoctrineExtensions\Paginate
35
 * @author      David Abdemoulaie <[email protected]>
36
 * @copyright   Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/)
37
 * @license     http://hobodave.com/license.txt New BSD License
38
 */
39
class LimitSubqueryWalker extends TreeWalkerAdapter
40
{
41
    /**
42
     * ID type hint.
43
     */
44
    const IDENTIFIER_TYPE = 'doctrine_paginator.id.type';
45
46
    /**
47
     * Counter for generating unique order column aliases.
48
     *
49
     * @var int
50
     */
51
    private $_aliasCounter = 0;
52
53
    /**
54
     * Walks down a SelectStatement AST node, modifying it to retrieve DISTINCT ids
55
     * of the root Entity.
56
     *
57
     * @param SelectStatement $AST
58
     *
59
     * @return void
60
     *
61
     * @throws \RuntimeException
62
     */
63 29
    public function walkSelectStatement(SelectStatement $AST)
64
    {
65 29
        $queryComponents = $this->_getQueryComponents();
66
        // Get the root entity and alias from the AST fromClause
67 29
        $from      = $AST->fromClause->identificationVariableDeclarations;
68 29
        $fromRoot  = reset($from);
69 29
        $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable;
70 29
        $rootClass = $queryComponents[$rootAlias]['metadata'];
71 29
        $selectExpressions = array();
72
73 29
        $this->validate($AST);
74
75 27
        foreach ($queryComponents as $dqlAlias => $qComp) {
76
            // Preserve mixed data in query for ordering.
77 27
            if (isset($qComp['resultVariable'])) {
78 2
                $selectExpressions[] = new SelectExpression($qComp['resultVariable'], $dqlAlias);
79 27
                continue;
80
            }
81
        }
82
        
83 27
        $identifier = $rootClass->getSingleIdentifierFieldName();
84
        
85 27
        if (isset($rootClass->associationMappings[$identifier])) {
86
            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.");
87
        }
88
89 27
        $this->_getQuery()->setHint(
90 27
            self::IDENTIFIER_TYPE,
91 27
            Type::getType($rootClass->fieldMappings[$identifier]['type'])
92
        );
93
94 27
        $pathExpression = new PathExpression(
95 27
            PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION,
96
            $rootAlias,
97
            $identifier
98
        );
99
100 27
        $pathExpression->type = PathExpression::TYPE_STATE_FIELD;
101
102 27
        array_unshift($selectExpressions, new SelectExpression($pathExpression, '_dctrn_id'));
103
104 27
        $AST->selectClause->selectExpressions = $selectExpressions;
105
106 27
        if (isset($AST->orderByClause)) {
107 21
            foreach ($AST->orderByClause->orderByItems as $item) {
108 21
                if ( ! $item->expression instanceof PathExpression) {
109 1
                    continue;
110
                }
111
                
112 20
                $AST->selectClause->selectExpressions[] = new SelectExpression(
113 20
                    $this->createSelectExpressionItem($item->expression),
114 20
                    '_dctrn_ord' . $this->_aliasCounter++
115
                );
116
            }
117
        }
118
119 27
        $AST->selectClause->isDistinct = true;
120 27
    }
121
122
    /**
123
     * Validate the AST to ensure that this walker is able to properly manipulate it.
124
     *
125
     * @param SelectStatement $AST
126
     */
127 29
    private function validate(SelectStatement $AST)
128
    {
129
        // Prevent LimitSubqueryWalker from being used with queries that include
130
        // a limit, a fetched to-many join, and an order by condition that
131
        // references a column from the fetch joined table.
132 29
        $queryComponents = $this->getQueryComponents();
133 29
        $query           = $this->_getQuery();
134 29
        $from            = $AST->fromClause->identificationVariableDeclarations;
135 29
        $fromRoot        = reset($from);
136
137 29
        if ($query instanceof Query
138 29
            && $query->getMaxResults()
139 29
            && $AST->orderByClause
140 29
            && count($fromRoot->joins)) {
141
            // Check each orderby item.
142
            // TODO: check complex orderby items too...
143 10
            foreach ($AST->orderByClause->orderByItems as $orderByItem) {
144 10
                $expression = $orderByItem->expression;
145 10
                if ($orderByItem->expression instanceof PathExpression
146 10
                    && isset($queryComponents[$expression->identificationVariable])) {
147 10
                    $queryComponent = $queryComponents[$expression->identificationVariable];
148 10
                    if (isset($queryComponent['parent'])
149 10
                        && $queryComponent['relation']['type'] & ClassMetadataInfo::TO_MANY) {
150 10
                        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.");
151
                    }
152
                }
153
            }
154
        }
155 27
    }
156
    
157
    /**
158
     * Retrieve either an IdentityFunction (IDENTITY(u.assoc)) or a state field (u.name).
159
     * 
160
     * @param \Doctrine\ORM\Query\AST\PathExpression $pathExpression
161
     * 
162
     * @return \Doctrine\ORM\Query\AST\Functions\IdentityFunction
163
     */
164 20
    private function createSelectExpressionItem(PathExpression $pathExpression)
165
    {
166 20
        if ($pathExpression->type === PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION) {
167 1
            $identity = new IdentityFunction('identity');
168
            
169 1
            $identity->pathExpression = clone $pathExpression;
170
            
171 1
            return $identity;
172
        }
173
        
174 19
        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...
175
    }
176
}
177