101 lines
2.3 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\MainBundle\Form\ChoiceLoader;
use Chill\MainBundle\Entity\PostalCode;
use Chill\MainBundle\Repository\PostalCodeRepository;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
use function call_user_func;
/**
* Class PostalCodeChoiceLoader.
*/
class PostalCodeChoiceLoader implements ChoiceLoaderInterface
{
/**
* @var array
*/
protected $lazyLoadedPostalCodes = [];
/**
* @var PostalCodeRepository
*/
protected $postalCodeRepository;
/**
* PostalCodeChoiceLoader constructor.
*/
public function __construct(PostalCodeRepository $postalCodeRepository)
{
$this->postalCodeRepository = $postalCodeRepository;
}
/**
* @param null $value
*/
public function loadChoiceList($value = null): ChoiceListInterface
{
return new \Symfony\Component\Form\ChoiceList\ArrayChoiceList(
$this->lazyLoadedPostalCodes,
static function (?PostalCode $pc = null) use ($value) {
return call_user_func($value, $pc);
}
);
}
/**
* @param null $value
*
* @return array
*/
public function loadChoicesForValues(array $values, $value = null)
{
$choices = [];
foreach ($values as $value) {
if (empty($value)) {
$choices[] = null;
} else {
$choices[] = $this->postalCodeRepository->find($value);
}
}
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->lazyLoadedPostalCodes[$id] = $choice;
}
return $values;
}
}