Test Setup Failed
Push — develop ( 082d66...6f26e1 )
by Guilherme
63:04
created

MultiTableUpdateExecutor   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 181
Duplicated Lines 3.31 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 98.59%

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 10
dl 6
loc 181
ccs 70
cts 71
cp 0.9859
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
D __construct() 6 97 9
B execute() 0 43 6

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
declare(strict_types=1);
4
5
namespace Doctrine\ORM\Query\Exec;
6
7
use Doctrine\DBAL\Connection;
8
use Doctrine\ORM\Mapping\ColumnMetadata;
9
use Doctrine\ORM\Query\AST;
10
use Doctrine\ORM\Query\ParameterTypeInferer;
11
use Doctrine\ORM\Utility\PersisterHelper;
12
13
/**
14
 * Executes the SQL statements for bulk DQL UPDATE statements on classes in
15
 * Class Table Inheritance (JOINED).
16
 *
17
 * @author Roman Borschel <[email protected]>
18
 * @since 2.0
19
 */
20
class MultiTableUpdateExecutor extends AbstractSqlExecutor
21
{
22
    /**
23
     * @var string
24
     */
25
    private $createTempTableSql;
26
27
    /**
28
     * @var string
29
     */
30
    private $dropTempTableSql;
31
32
    /**
33
     * @var string
34
     */
35
    private $insertSql;
36
37
    /**
38
     * @var array
39
     */
40
    private $sqlParameters = [];
41
42
    /**
43
     * @var int
44
     */
45
    private $numParametersInUpdateClause = 0;
46
47
    /**
48
     * Initializes a new <tt>MultiTableUpdateExecutor</tt>.
49
     *
50
     * Internal note: Any SQL construction and preparation takes place in the constructor for
51
     *                best performance. With a query cache the executor will be cached.
52
     *
53
     * @param \Doctrine\ORM\Query\AST\Node  $AST The root AST node of the DQL query.
54
     * @param \Doctrine\ORM\Query\SqlWalker $sqlWalker The walker used for SQL generation from the AST.
55
     */
56
    public function __construct(AST\Node $AST, $sqlWalker)
57
    {
58
        $em             = $sqlWalker->getEntityManager();
59
        $conn           = $em->getConnection();
60
        $platform       = $conn->getDatabasePlatform();
61
62
        $updateClause   = $AST->updateClause;
0 ignored issues
show
Bug introduced by
The property updateClause does not seem to exist in Doctrine\ORM\Query\AST\Node.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
63
        $primaryClass   = $sqlWalker->getEntityManager()->getClassMetadata($updateClause->abstractSchemaName);
64
        $rootClass      = $em->getClassMetadata($primaryClass->getRootClassName());
0 ignored issues
show
Bug introduced by
The method getRootClassName() does not seem to exist on object<Doctrine\Common\P...\Mapping\ClassMetadata>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
65
66
        $updateItems    = $updateClause->updateItems;
67
68
        $tempTable         = $platform->getTemporaryTableName($rootClass->getTemporaryIdTableName());
0 ignored issues
show
Bug introduced by
The method getTemporaryIdTableName() does not seem to exist on object<Doctrine\Common\P...\Mapping\ClassMetadata>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
69
        $idColumns         = $rootClass->getIdentifierColumns($em);
0 ignored issues
show
Bug introduced by
The method getIdentifierColumns() does not exist on Doctrine\Common\Persistence\Mapping\ClassMetadata. Did you maybe mean getIdentifier()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
70
        $idColumnNameList  = implode(', ', array_keys($idColumns));
71 4
72
        // 1. Create an INSERT INTO temptable ... SELECT identifiers WHERE $AST->getWhereClause()
73 4
        $sqlWalker->setSQLTableAlias($primaryClass->getTableName(), 'i0', $updateClause->aliasIdentificationVariable);
0 ignored issues
show
Bug introduced by
The method getTableName() does not seem to exist on object<Doctrine\Common\P...\Mapping\ClassMetadata>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
74 4
75 4
        $this->insertSql = 'INSERT INTO ' . $tempTable . ' (' . $idColumnNameList . ')'
76 4
                . ' SELECT i0.' . implode(', i0.', array_keys($idColumns));
77
78 4
        $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->getClassName(), $updateClause->aliasIdentificationVariable);
0 ignored issues
show
Bug introduced by
The method getClassName() does not seem to exist on object<Doctrine\Common\P...\Mapping\ClassMetadata>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
79 4
        $fromClause = new AST\FromClause([new AST\IdentificationVariableDeclaration($rangeDecl, null, [])]);
80 4
81
        $this->insertSql .= $sqlWalker->walkFromClause($fromClause);
82 4
83
        // 2. Create statement used in UPDATE ... WHERE ... IN (subselect)
84 4
        $updateSQLTemplate = sprintf(
85 4
            'UPDATE %%s SET %%s WHERE (%s) IN (SELECT %s FROM %s)',
86 4
            $idColumnNameList,
87
            $idColumnNameList,
88
            $tempTable
89 4
        );
90
91 4
        // 3. Create and store UPDATE statements
92 4
        $hierarchyClasses = array_merge(
93
            array_map(
94 4
                function ($className) use ($em) { return $em->getClassMetadata($className); },
95 4
                array_reverse($primaryClass->getSubClasses())
0 ignored issues
show
Bug introduced by
The method getSubClasses() does not seem to exist on object<Doctrine\Common\P...\Mapping\ClassMetadata>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
96
            ),
97 4
            [$primaryClass],
98
            $primaryClass->getAncestorsIterator()->getArrayCopy()
0 ignored issues
show
Bug introduced by
The method getAncestorsIterator() does not seem to exist on object<Doctrine\Common\P...\Mapping\ClassMetadata>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
99
        );
100 4
101
        $i = 0;
102
103 4
        foreach ($hierarchyClasses as $class) {
104 4
            $updateSQLParts = [];
105
106 4
            foreach ($updateItems as $updateItem) {
107 4
                $field    = $updateItem->pathExpression->field;
108 4
                $property = $class->getProperty($field);
109 4
110
                if ($property && ! $class->isInheritedProperty($field)) {
111 4
                    $updateSQLParts[] = $sqlWalker->walkUpdateItem($updateItem);
112 4
                    $newValue         = $updateItem->newValue;
113
114 4
                    if ($newValue instanceof AST\InputParameter) {
115 4
                        $this->sqlParameters[$i][] = $newValue->name;
116 4
117
                        ++$this->numParametersInUpdateClause;
118 4
                    }
119 4
                }
120 4
            }
121
122 1
            if ($updateSQLParts) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $updateSQLParts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
123
                $this->sqlStatements[$i] = sprintf(
124
                    $updateSQLTemplate,
125 4
                    $class->table->getQuotedQualifiedName($platform),
126
                    implode(', ', $updateSQLParts)
127 4
                );
128 3
129
                $i++;
130 4
            }
131
        }
132
133
        // Append WHERE clause to insertSql, if there is one.
134
        if ($AST->whereClause) {
135 4
            $this->insertSql .= $sqlWalker->walkWhereClause($AST->whereClause);
0 ignored issues
show
Bug introduced by
The property whereClause does not seem to exist in Doctrine\ORM\Query\AST\Node.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
136 4
        }
137
138
        // 4. Store DDL for temporary identifier table.
139
        $columnDefinitions = [];
140
141 4 View Code Duplication
        foreach ($idColumns as $columnName => $column) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
142 3
            $columnDefinitions[$columnName] = [
143
                'notnull' => true,
144
                'type'    => $column->getType(),
145
            ];
146 4
        }
147
148 4
        $this->createTempTableSql = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' ('
149 4
                . $platform->getColumnDeclarationListSQL($columnDefinitions) . ')';
150 4
151 4
        $this->dropTempTableSql = $platform->getDropTemporaryTableSQL($tempTable);
152
    }
153
154 4
    /**
155 4
     * {@inheritDoc}
156 4
     */
157
    public function execute(Connection $conn, array $params, array $types)
158
    {
159
        // Create temporary id table
160 4
        $conn->executeUpdate($this->createTempTableSql);
161 4
162
        try {
163 4
            // Insert identifiers. Parameters from the update clause are cut off.
164 4
            $numUpdated = $conn->executeUpdate(
165
                $this->insertSql,
166
                array_slice($params, $this->numParametersInUpdateClause),
167
                array_slice($types, $this->numParametersInUpdateClause)
168
            );
169 5
170
            // Execute UPDATE statements
171
            foreach ($this->sqlStatements as $key => $statement) {
172 5
                $paramValues = [];
173
                $paramTypes  = [];
174
175
                if (isset($this->sqlParameters[$key])) {
176 5
                    foreach ($this->sqlParameters[$key] as $parameterKey => $parameterName) {
177 5
                        $paramValues[] = $params[$parameterKey];
178 5
                        $paramTypes[]  = isset($types[$parameterKey])
179 5
                            ? $types[$parameterKey]
180
                            : ParameterTypeInferer::inferType($params[$parameterKey])
181
                        ;
182
                    }
183 5
                }
184 5
185 5
                $conn->executeUpdate($statement, $paramValues, $paramTypes);
186
            }
187 5
        } catch (\Exception $exception) {
188 3
            // FAILURE! Drop temporary table to avoid possible collisions
189 3
            $conn->executeUpdate($this->dropTempTableSql);
190 3
191 3
            // Re-throw exception
192 3
            throw $exception;
193
        }
194
195
        // Drop temporary table
196
        $conn->executeUpdate($this->dropTempTableSql);
197 5
198
        return $numUpdated;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $numUpdated; (integer) is incompatible with the return type declared by the abstract method Doctrine\ORM\Query\Exec\...actSqlExecutor::execute of type Doctrine\DBAL\Driver\Statement.

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...
199
    }
200
}
201