Last active
January 3, 2022 11:53
-
-
Save ostrolucky/f9f1e0b271357573fde55b7a2ba91a32 to your computer and use it in GitHub Desktop.
Doctrine ColumnHydrator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\ORM\Hydration; | |
use Doctrine\ORM\Internal\Hydration\ArrayHydrator; | |
/** | |
* Returns one-dimensional scalar array from query: mixed[][] => mixed[] | |
* | |
* Example: | |
* ArrayHydrator: [['id' => 1], ['id' => 2]] | |
* ColumnHydrator: [1, 2] | |
* | |
* @see https://stackoverflow.com/questions/11657835/how-to-get-a-one-dimensional-scalar-array-as-a-doctrine-dql-query-result | |
* @author Gabriel Ostrolucký | |
* @license MIT | |
*/ | |
class ColumnHydrator extends ArrayHydrator | |
{ | |
/** | |
* @return mixed[] | |
*/ | |
protected function hydrateAllData(): array | |
{ | |
if (!isset($this->_rsm->indexByMap['scalars'])) { | |
return $this->_stmt->fetchAll(\PDO::FETCH_COLUMN); | |
} | |
if (!$result = parent::hydrateAllData()) { | |
return $result; | |
} | |
$indexColumn = $this->_rsm->scalarMappings[$this->_rsm->indexByMap['scalars']]; | |
$keys = array_keys(reset($result)); | |
return array_column($result, isset($keys[1]) && $keys[0] === $indexColumn ? $keys[1] : $keys[0], $indexColumn); | |
} | |
} |
@kiler129 thanks, added the license
Thanks for this! I have two questions:
fetchAll()
is deprecated, and I don't know of an alternative, see doctrine/orm#8322- What is
if (!$result = parent::hydrateAllData())
checking for -ArrayHydrator::hydrateAllData()
is always returning an array.
- It's checking if result is empty
Is there a way to create a PR for this gist? If no, I'd suggest to change it to (to make phpstan happy :-)
$result = parent::hydrateAllData();
if ([] === $result) {
return [];
}
You should use this instead doctrine/orm#8919
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As a formality: can you specify a license (I want to use it in a closed source project).
Thanks!
For anyone wondering how to use it - you have to create entry in Doctrine config:
Later on you can just use it as
$query->getResult('ColumnHydrator')
.