Issue #2902311 by jhedstrom, dawehner, joachim, daffie, moshe weitzman, longwave, Berdir: add __toString() to the entity Query class

merge-requests/2419/head
Alex Pott 2019-12-02 23:27:16 +00:00
parent 001fdae1f8
commit d86ce7363b
No known key found for this signature in database
GPG Key ID: 31905460D4A69276
2 changed files with 56 additions and 0 deletions

View File

@ -326,4 +326,28 @@ class Query extends QueryBase implements QueryInterface {
return new $class($sql_query);
}
/**
* Implements the magic __toString method.
*/
public function __toString() {
// Clone the query so the prepare and compile doesn't get repeated.
$clone = clone($this);
$clone->prepare()
->compile()
->addSort()
->finish();
// Quote arguments so query is able to be run.
$quoted = [];
foreach ($clone->sqlQuery->getArguments() as $key => $value) {
$quoted[$key] = is_null($value) ? 'NULL' : $this->connection->quote($value);
}
// Replace table name brackets.
$sql = $clone->connection->prefixTables((string) $clone->sqlQuery);
return strtr($sql, $quoted);
}
}

View File

@ -1201,4 +1201,36 @@ class EntityQueryTest extends EntityKernelTestBase {
$this->assertEquals($entity->id(), reset($result));
}
/**
* Tests __toString().
*/
public function testToString() {
$query = $this->storage->getQuery();
$group_blue = $query->andConditionGroup()->condition("{$this->figures}.color", ['blue'], 'IN');
$group_red = $query->andConditionGroup()->condition("{$this->figures}.color", ['red'], 'IN');
$null_group = $query->andConditionGroup()->notExists("{$this->figures}.color");
$this->queryResults = $query
->condition($group_blue)
->condition($group_red)
->condition($null_group)
->sort('id');
$figures = $this->figures;
$expected = <<<EOF
SELECT base_table.revision_id AS revision_id, base_table.id AS id
FROM
{entity_test_mulrev} base_table
INNER JOIN {entity_test_mulrev__{$figures}} entity_test_mulrev__$figures ON entity_test_mulrev__$figures.entity_id = base_table.id
INNER JOIN {entity_test_mulrev__{$figures}} entity_test_mulrev__{$figures}_2 ON entity_test_mulrev__{$figures}_2.entity_id = base_table.id
LEFT JOIN {entity_test_mulrev__{$figures}} entity_test_mulrev__{$figures}_3 ON entity_test_mulrev__{$figures}_3.entity_id = base_table.id
WHERE (entity_test_mulrev__{$figures}.{$figures}_color IN ('blue')) AND (entity_test_mulrev__{$figures}_2.{$figures}_color IN ('red')) AND (entity_test_mulrev__{$figures}_3.{$figures}_color IS NULL)
ORDER BY base_table.id ASC
EOF;
// Apply table prefixes to the expected sql.
$expected = \Drupal::database()->prefixTables($expected);
$this->assertEquals($expected, (string) $query);
}
}