Files
chill-bundles/src/Bundle/ChillPersonBundle/Form/ChoiceLoader/PersonChoiceLoader.php

125 lines
2.8 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Form\ChoiceLoader;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Repository\PersonRepository;
use RuntimeException;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
use function call_user_func;
use function count;
use function in_array;
/**
* Allow to load a list of person.
*/
class PersonChoiceLoader implements ChoiceLoaderInterface
{
protected array $centers = [];
protected array $lazyLoadedPersons = [];
protected PersonRepository $personRepository;
/**
* PersonChoiceLoader constructor.
*
* @param EntityRepository $personRepository
*/
public function __construct(
PersonRepository $personRepository,
?array $centers = null
) {
$this->personRepository = $personRepository;
if (null !== $centers) {
$this->centers = $centers;
}
}
/**
* @param null $value
*/
public function loadChoiceList($value = null): ChoiceListInterface
{
return new \Symfony\Component\Form\ChoiceList\ArrayChoiceList(
$this->lazyLoadedPersons,
static function (Person $p) use ($value) {
return call_user_func($value, $p);
}
);
}
/**
* @param null $value
*
* @return array
*/
public function loadChoicesForValues(array $values, $value = null)
{
$choices = [];
foreach ($values as $value) {
if (empty($value)) {
continue;
}
$person = $this->personRepository->find($value);
if (
$this->hasCenterFilter()
&& !in_array($person->getCenter(), $this->centers, true)
) {
throw new RuntimeException('chosen a person not in correct center');
}
$choices[] = $person;
}
return $choices;
}
/**
* @param null $value
*
* @return array|string[]
*/
public function loadValuesForChoices(array $choices, $value = null)
{
$values = [];
foreach ($choices as $choice) {
if (null === $choice) {
$values[] = null;
continue;
}
$id = call_user_func($value, $choice);
$values[] = $id;
$this->lazyLoadedPersons[$id] = $choice;
}
return $values;
}
/**
* @return bool
*/
protected function hasCenterFilter()
{
return count($this->centers) > 0;
}
}