EavValidationRules.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Ui\DataProvider;
  7. use Magento\Eav\Model\Entity\Attribute\AbstractAttribute;
  8. /**
  9. * @api
  10. * @since 100.0.2
  11. */
  12. class EavValidationRules
  13. {
  14. /**
  15. * @var array
  16. * @since 100.0.6
  17. */
  18. protected $validationRules = [
  19. 'email' => ['validate-email' => true],
  20. 'date' => ['validate-date' => true],
  21. ];
  22. /**
  23. * Build validation rules
  24. *
  25. * @param AbstractAttribute $attribute
  26. * @param array $data
  27. * @return array
  28. */
  29. public function build(AbstractAttribute $attribute, array $data)
  30. {
  31. $validations = [];
  32. if (isset($data['required']) && $data['required'] == 1) {
  33. $validations = array_merge($validations, ['required-entry' => true]);
  34. }
  35. if ($attribute->getFrontendInput() === 'price') {
  36. $validations = array_merge($validations, ['validate-zero-or-greater' => true]);
  37. }
  38. if ($attribute->getValidateRules()) {
  39. $validations = array_merge($validations, $this->clipLengthRules($attribute->getValidateRules()));
  40. }
  41. return $this->aggregateRules($validations);
  42. }
  43. /**
  44. * @param array $validations
  45. * @return array
  46. */
  47. private function aggregateRules(array $validations): array
  48. {
  49. $rules = [];
  50. foreach ($validations as $type => $ruleValue) {
  51. $rule = [$type => $ruleValue];
  52. if ($type === 'input_validation') {
  53. $rule = $this->validationRules[$ruleValue] ?? [];
  54. }
  55. if (count($rule) !== 0) {
  56. $key = key($rule);
  57. $rules[$key] = $rule[$key];
  58. }
  59. }
  60. return $rules;
  61. }
  62. /**
  63. * @param array $rules
  64. * @return array
  65. */
  66. private function clipLengthRules(array $rules): array
  67. {
  68. if (empty($rules['input_validation'])) {
  69. unset(
  70. $rules['min_text_length'],
  71. $rules['max_text_length']
  72. );
  73. }
  74. return $rules;
  75. }
  76. }