AbstractOptionsField.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Ui\Component\Form\Element;
  7. use Magento\Framework\Data\OptionSourceInterface;
  8. use Magento\Framework\View\Element\UiComponent\ContextInterface;
  9. /**
  10. * @api
  11. * @since 100.1.0
  12. */
  13. abstract class AbstractOptionsField extends AbstractElement
  14. {
  15. /**
  16. * @var array|OptionSourceInterface|null
  17. * @since 100.1.0
  18. */
  19. protected $options;
  20. /**
  21. * Constructor
  22. *
  23. * @param ContextInterface $context
  24. * @param array|OptionSourceInterface|null $options
  25. * @param array $components
  26. * @param array $data
  27. */
  28. public function __construct(
  29. ContextInterface $context,
  30. $options = null,
  31. array $components = [],
  32. array $data = []
  33. ) {
  34. $this->options = $options;
  35. parent::__construct($context, $components, $data);
  36. }
  37. /**
  38. * Prepare component configuration
  39. *
  40. * @return void
  41. * @since 100.1.0
  42. */
  43. public function prepare()
  44. {
  45. $config = $this->getData('config');
  46. if (isset($this->options)) {
  47. if (!isset($config['options'])) {
  48. $config['options'] = [];
  49. }
  50. if ($this->options instanceof OptionSourceInterface) {
  51. $options = $this->options->toOptionArray();
  52. } else {
  53. $options = array_values($this->options);
  54. }
  55. if (empty($config['rawOptions'])) {
  56. $options = $this->convertOptionsValueToString($options);
  57. }
  58. $config['options'] = array_values(array_merge_recursive($config['options'], $options));
  59. }
  60. $this->setData('config', (array)$config);
  61. parent::prepare();
  62. }
  63. /**
  64. * Check if option value
  65. *
  66. * @param string $optionValue
  67. * @return bool
  68. * @SuppressWarnings(PHPMD.BooleanGetMethodName)
  69. * @since 100.1.0
  70. */
  71. abstract public function getIsSelected($optionValue);
  72. /**
  73. * Convert options value to string
  74. *
  75. * @param array $options
  76. * @return array
  77. * @since 100.1.0
  78. */
  79. protected function convertOptionsValueToString(array $options)
  80. {
  81. array_walk($options, function (&$value) {
  82. if (isset($value['value']) && is_scalar($value['value'])) {
  83. $value['value'] = (string)$value['value'];
  84. }
  85. });
  86. return $options;
  87. }
  88. }