Skip to content

Instantly share code, notes, and snippets.

@ajaxray
Created August 26, 2018 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajaxray/9ef4c5dcc4e2aa881240370b6f27c8f4 to your computer and use it in GitHub Desktop.
Save ajaxray/9ef4c5dcc4e2aa881240370b6f27c8f4 to your computer and use it in GitHub Desktop.
PHP Trait for key key-value array of various entities (e,g, Doctrine 2 ORM)
<?php
/**
* Provide key-value list of various entities
*
* Created by: Anis Ahmad <anis.programmer@gmail.com>
* Created at: 8/26/18 4:42 PM
*/
namespace AppBundle\Traits;
trait ListProvider
{
/**
* Get an array of $valueField indexed by $keyField
*
* @param null $keyField
* @param null $valueField
* @return array
*/
public function getIndexedList($keyField = null, $valueField = null)
{
if (is_a($this, 'Doctrine\ORM\EntityRepository')) {
return $this->makeEntityList($keyField, $valueField);
}
// else if (is_a($this, 'Other\TypeOf\Class')) {
// return $this->makeOtherTypeList($keyField, $valueField);
// }
throw new \RuntimeException("ListProvider::getList() was not implemented for ". get_parent_class($this));
}
/**
* Make list of entities from a repository
*
* @param $keyField
* @param $valueField
* @return array
*/
private function makeEntityList($keyField, $valueField)
{
$rawList = $this->createQueryBuilder('a')
->select("a.{$keyField}, a.{$valueField}")
->getQuery()
->getArrayResult();
$list = [];
foreach ($rawList as $item) {
$list[$item[$keyField]] = $item[$valueField];
}
return $list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment