Backend.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Eav\Model\Validator\Attribute;
  7. /**
  8. * Validation EAV entity via EAV attributes' backend models
  9. *
  10. * @author Magento Core Team <core@magentocommerce.com>
  11. */
  12. class Backend extends \Magento\Framework\Validator\AbstractValidator
  13. {
  14. /**
  15. * Returns true if and only if $value meets the validation requirements.
  16. *
  17. * @param \Magento\Framework\Model\AbstractModel $entity
  18. * @return bool
  19. * @throws \InvalidArgumentException
  20. */
  21. public function isValid($entity)
  22. {
  23. $this->_messages = [];
  24. if (!$entity instanceof \Magento\Framework\Model\AbstractModel) {
  25. throw new \InvalidArgumentException('Model must be extended from \Magento\Framework\Model\AbstractModel');
  26. }
  27. /** @var \Magento\Eav\Model\Entity\AbstractEntity $resource */
  28. $resource = $entity->getResource();
  29. if (!$resource instanceof \Magento\Eav\Model\Entity\AbstractEntity) {
  30. throw new \InvalidArgumentException(
  31. 'Model resource must be extended from \Magento\Eav\Model\Entity\AbstractEntity'
  32. );
  33. }
  34. $resource->loadAllAttributes($entity);
  35. $attributes = $resource->getAttributesByCode();
  36. /** @var \Magento\Eav\Model\Entity\Attribute $attribute */
  37. foreach ($attributes as $attribute) {
  38. $backend = $attribute->getBackend();
  39. if (!method_exists($backend, 'validate') || !is_callable([$backend, 'validate'])) {
  40. continue;
  41. }
  42. try {
  43. $result = $backend->validate($entity);
  44. if (false === $result) {
  45. $this->_messages[$attribute->getAttributeCode()][] = __(
  46. 'The value of attribute "%1" is invalid.',
  47. $attribute->getAttributeCode()
  48. );
  49. } elseif (is_string($result)) {
  50. $this->_messages[$attribute->getAttributeCode()][] = $result;
  51. }
  52. } catch (\Magento\Framework\Exception\LocalizedException $e) {
  53. $this->_messages[$attribute->getAttributeCode()][] = $e->getMessage();
  54. }
  55. }
  56. return 0 == count($this->_messages);
  57. }
  58. }