Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#DDC-2313: QueryBuilder Deep Cloning #327

Merged
merged 1 commit into from Jun 13, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 33 additions & 1 deletion lib/Doctrine/DBAL/Query/QueryBuilder.php
Expand Up @@ -962,7 +962,7 @@ private function getSQLForSelect()
throw QueryException::unknownAlias($fromAlias, array_keys($knownAliases));
}
}

$query .= implode(', ', $fromClauses)
. ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '')
. ($this->sqlParts['groupBy'] ? ' GROUP BY ' . implode(', ', $this->sqlParts['groupBy']) : '')
Expand Down Expand Up @@ -1096,4 +1096,36 @@ private function getSQLForJoins($fromAlias, array &$knownAliases)

return $sql;
}

/**
* Deep clone of all expression objects in the SQL parts.
*
* @return void
*/
public function __clone()
{
foreach ($this->sqlParts as $part => $elements) {
if (is_array($this->sqlParts[$part])) {
foreach ($this->sqlParts[$part] as $idx => $element) {
if (is_object($element)) {
$this->sqlParts[$part][$idx] = clone $element;
}
}
} else if (is_object($elements)) {
$this->sqlParts[$part] = clone $elements;
}
}

$params = array();

foreach ($this->params as $param) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be simplified:

foreach ($this->params as $key => $param) {
    if (is_object($param)) {
        $this->params[$key] = clone $param;
    }
}

if(is_object($param)){
$params[] = clone $param;
} else {
$params[] = $param;
}
}

$this->params = $params;
}
}
22 changes: 21 additions & 1 deletion tests/Doctrine/Tests/DBAL/Query/QueryBuilderTest.php
Expand Up @@ -602,4 +602,24 @@ public function testSelectWithMultipleFromAndJoins()

$this->assertEquals('SELECT DISTINCT u.id FROM users u INNER JOIN permissions p ON p.user_id = u.id, articles a INNER JOIN comments c ON c.article_id = a.id WHERE (u.id = a.user_id) AND (p.read = 1)', $qb->getSQL());
}
}

public function testClone()
{
$qb = new QueryBuilder($this->conn);

$qb->select('u.id')
->from('users', 'u')
->where('u.id = :test');

$qb->setParameter(':test', (object) 1);

$qb_clone = clone $qb;

$this->assertEquals((string) $qb, (string) $qb_clone);

$qb->andWhere('u.id = 1');

$this->assertFalse($qb->getQueryParts() === $qb_clone->getQueryParts());
$this->assertFalse($qb->getParameters() === $qb_clone->getParameters());
}
}