AttributeMapper.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Ui\Component\Form;
  7. /**
  8. * @api
  9. * @since 100.0.2
  10. */
  11. class AttributeMapper
  12. {
  13. /**
  14. * Form element mapping
  15. *
  16. * @var array
  17. */
  18. private $formElementMap = [
  19. 'text' => 'input',
  20. 'hidden' => 'input',
  21. 'boolean' => 'checkbox',
  22. ];
  23. /**
  24. * EAV attribute properties to fetch from meta storage
  25. * @var array
  26. */
  27. private $metaPropertiesMap = [
  28. 'dataType' => 'getFrontendInput',
  29. 'visible' => 'getIsVisible',
  30. 'required' => 'getIsRequired',
  31. 'label' => 'getStoreLabel',
  32. 'sortOrder' => 'getSortOrder',
  33. 'notice' => 'getNote',
  34. 'default' => 'getDefaultValue',
  35. 'size' => 'getMultilineCount'
  36. ];
  37. /**
  38. * @var array
  39. */
  40. protected $validationRules = [
  41. 'input_validation' => [
  42. 'email' => ['validate-email' => true],
  43. 'date' => ['validate-date' => true],
  44. ],
  45. ];
  46. /**
  47. * Get attributes meta
  48. *
  49. * @param \Magento\Eav\Api\Data\AttributeInterface $attribute
  50. * @return array
  51. * @throws \Magento\Framework\Exception\LocalizedException
  52. */
  53. public function map($attribute)
  54. {
  55. foreach ($this->metaPropertiesMap as $metaName => $methodName) {
  56. $value = $attribute->$methodName();
  57. $meta[$metaName] = $value;
  58. if ('getFrontendInput' === $methodName) {
  59. $meta['formElement'] = isset($this->formElementMap[$value])
  60. ? $this->formElementMap[$value]
  61. : $value;
  62. }
  63. }
  64. if ($attribute->usesSource()) {
  65. $meta['options'] = $attribute->getSource()->getAllOptions();
  66. }
  67. $rules = [];
  68. if (isset($meta['required']) && $meta['required'] == 1) {
  69. $rules['required-entry'] = true;
  70. }
  71. foreach ($attribute->getValidateRules() as $name => $value) {
  72. if (isset($this->validationRules[$name][$value])) {
  73. $rules = array_merge($rules, $this->validationRules[$name][$value]);
  74. } else {
  75. $rules[$name] = $value;
  76. }
  77. }
  78. $meta['validation'] = $rules;
  79. return $meta;
  80. }
  81. }