Skip to content

Instantly share code, notes, and snippets.

@ostrolucky
Last active January 3, 2022 11:53
Show Gist options
  • Save ostrolucky/f9f1e0b271357573fde55b7a2ba91a32 to your computer and use it in GitHub Desktop.
Save ostrolucky/f9f1e0b271357573fde55b7a2ba91a32 to your computer and use it in GitHub Desktop.
Doctrine ColumnHydrator
<?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);
}
}
@ThomasLandauer
Copy link

Thanks for this! I have two questions:

  1. fetchAll() is deprecated, and I don't know of an alternative, see doctrine/orm#8322
  2. What is if (!$result = parent::hydrateAllData()) checking for - ArrayHydrator::hydrateAllData() is always returning an array.

@ostrolucky
Copy link
Author

  1. It's checking if result is empty

@ThomasLandauer
Copy link

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 [];
}

@ostrolucky
Copy link
Author

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