Validator.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Attribute data validator
  4. * Copyright © Magento, Inc. All rights reserved.
  5. * See COPYING.txt for license details.
  6. */
  7. namespace Magento\Customer\Model\Metadata;
  8. class Validator extends \Magento\Eav\Model\Validator\Attribute\Data
  9. {
  10. /**
  11. * @var string
  12. */
  13. protected $_entityType;
  14. /**
  15. * @var array
  16. */
  17. protected $_entityData;
  18. /**
  19. * @param ElementFactory $attrDataFactory
  20. */
  21. public function __construct(ElementFactory $attrDataFactory)
  22. {
  23. $this->_attrDataFactory = $attrDataFactory;
  24. }
  25. /**
  26. * Validate EAV model attributes with data models
  27. *
  28. * @param \Magento\Framework\DataObject|array $entityData Data set from the Model attributes
  29. * @return bool
  30. */
  31. public function isValid($entityData)
  32. {
  33. if ($entityData instanceof \Magento\Framework\DataObject) {
  34. $this->_entityData = $entityData->getData();
  35. } else {
  36. $this->_entityData = $entityData;
  37. }
  38. return $this->validateData($this->_data, $this->_attributes, $this->_entityType);
  39. }
  40. /**
  41. * @param array $data
  42. * @param \Magento\Customer\Api\Data\AttributeMetadataInterface[] $attributes
  43. * @param string $entityType
  44. * @return bool
  45. */
  46. public function validateData(array $data, array $attributes, $entityType)
  47. {
  48. foreach ($attributes as $attribute) {
  49. $attributeCode = $attribute->getAttributeCode();
  50. if (!$attribute->getDataModel() && !$attribute->getFrontendInput()) {
  51. continue;
  52. }
  53. if (!isset($data[$attributeCode])) {
  54. $data[$attributeCode] = null;
  55. }
  56. $dataModel = $this->_attrDataFactory->create($attribute, $data[$attributeCode], $entityType);
  57. $dataModel->setExtractedData($data);
  58. $value = empty($data[$attributeCode]) && isset(
  59. $this->_entityData[$attributeCode]
  60. ) ? $this->_entityData[$attributeCode] : $data[$attributeCode];
  61. $result = $dataModel->validateValue($value);
  62. if (true !== $result) {
  63. $this->_addErrorMessages($attributeCode, (array)$result);
  64. }
  65. }
  66. return count($this->_messages) == 0;
  67. }
  68. /**
  69. * Set type of the entity
  70. *
  71. * @param string $entityType
  72. * @return void
  73. */
  74. public function setEntityType($entityType)
  75. {
  76. $this->_entityType = $entityType;
  77. }
  78. }