AbstractChoiceLoader.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Form\ChoiceList\Loader;
  11. use Symfony\Component\Form\ChoiceList\ArrayChoiceList;
  12. /**
  13. * @author Jules Pietri <jules@heahprod.com>
  14. */
  15. abstract class AbstractChoiceLoader implements ChoiceLoaderInterface
  16. {
  17. /**
  18. * The loaded choice list.
  19. *
  20. * @var ArrayChoiceList
  21. */
  22. private $choiceList;
  23. /**
  24. * @final
  25. *
  26. * {@inheritdoc}
  27. */
  28. public function loadChoiceList(callable $value = null)
  29. {
  30. return $this->choiceList ?? ($this->choiceList = new ArrayChoiceList($this->loadChoices(), $value));
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function loadChoicesForValues(array $values, callable $value = null)
  36. {
  37. if (!$values) {
  38. return [];
  39. }
  40. if ($this->choiceList) {
  41. return $this->choiceList->getChoicesForValues($values);
  42. }
  43. return $this->doLoadChoicesForValues($values, $value);
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function loadValuesForChoices(array $choices, callable $value = null)
  49. {
  50. if (!$choices) {
  51. return [];
  52. }
  53. if ($value) {
  54. // if a value callback exists, use it
  55. return array_map($value, $choices);
  56. }
  57. if ($this->choiceList) {
  58. return $this->choiceList->getValuesForChoices($choices);
  59. }
  60. return $this->doLoadValuesForChoices($choices);
  61. }
  62. abstract protected function loadChoices(): iterable;
  63. protected function doLoadChoicesForValues(array $values, ?callable $value): array
  64. {
  65. return $this->loadChoiceList($value)->getChoicesForValues($values);
  66. }
  67. protected function doLoadValuesForChoices(array $choices): array
  68. {
  69. return $this->loadChoiceList()->getValuesForChoices($choices);
  70. }
  71. }