Files
chill-bundles/src/Bundle/ChillThirdPartyBundle/Form/ChoiceLoader/ThirdPartyChoiceLoader.php
2021-12-21 10:59:23 +01:00

95 lines
2.2 KiB
PHP

<?php
/**
* 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.
*/
declare(strict_types=1);
namespace Chill\ThirdPartyBundle\Form\ChoiceLoader;
use Chill\MainBundle\Entity\Center;
use Doctrine\ORM\EntityRepository;
use RuntimeException;
use Symfony\Component\Form\ChoiceList\ArrayChoiceList;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
use function call_user_func;
use function in_array;
/**
* Lazy load third parties.
*/
class ThirdPartyChoiceLoader implements ChoiceLoaderInterface
{
/**
* @var Center
*/
protected $center;
/**
* @var \Chill\ThirdPartyBundle\Entity\ThirdParty[]
*/
protected $lazyLoadedParties = [];
/**
* @var EntityRepository
*/
protected $partyRepository;
public function __construct(Center $center, EntityRepository $partyRepository)
{
$this->center = $center;
$this->partyRepository = $partyRepository;
}
public function loadChoiceList($value = null): ChoiceListInterface
{
return new ArrayChoiceList($this->lazyLoadedParties, $value);
}
public function loadChoicesForValues($values, $value = null)
{
$choices = [];
foreach ($values as $value) {
if (empty($value)) {
continue;
}
$party = $this->partyRepository->find($value);
if (false === in_array($this->center, $party->getCenters()->toArray(), true)) {
throw new RuntimeException("the party's center is not authorized");
}
$choices[] = $party;
}
return $choices;
}
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->lazyLoadedParties[$id] = $choice;
}
return $values;
}
}