Options.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\View\Layout\Argument\Interpreter;
  7. use Magento\Framework\Data\Argument\InterpreterInterface;
  8. use Magento\Framework\ObjectManagerInterface;
  9. /**
  10. * Interpreter that retrieves options from an option source model
  11. */
  12. class Options implements InterpreterInterface
  13. {
  14. /**
  15. * @var ObjectManagerInterface
  16. */
  17. protected $objectManager;
  18. /**
  19. * @param ObjectManagerInterface $objectManager
  20. */
  21. public function __construct(ObjectManagerInterface $objectManager)
  22. {
  23. $this->objectManager = $objectManager;
  24. }
  25. /**
  26. * {@inheritdoc}
  27. * @return array Format: array(array('value' => <value>, 'label' => '<label>'), ...)
  28. * @throws \InvalidArgumentException
  29. * @throws \UnexpectedValueException
  30. */
  31. public function evaluate(array $data)
  32. {
  33. if (!isset($data['model'])) {
  34. throw new \InvalidArgumentException('Options source model class is missing.');
  35. }
  36. $modelClass = $data['model'];
  37. $modelInstance = $this->objectManager->get($modelClass);
  38. if (!$modelInstance instanceof \Magento\Framework\Data\OptionSourceInterface) {
  39. throw new \UnexpectedValueException(
  40. sprintf("Instance of the options source model is expected, got %s instead.", get_class($modelInstance))
  41. );
  42. }
  43. $result = [];
  44. foreach ($modelInstance->toOptionArray() as $value => $label) {
  45. if (is_array($label)) {
  46. $result[] = $label;
  47. } else {
  48. $result[] = ['value' => $value, 'label' => $label];
  49. }
  50. }
  51. return $result;
  52. }
  53. }