DataObject.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. /**
  7. * Validator encapsulates multiple validation rules for \Magento\Framework\DataObject.
  8. * Able to validate both individual fields and a whole object.
  9. */
  10. namespace Magento\Framework\Validator;
  11. /**
  12. * @api
  13. * @since 100.0.2
  14. */
  15. class DataObject implements \Zend_Validate_Interface
  16. {
  17. /**
  18. * Validation rules per scope (particular fields or entire entity)
  19. *
  20. * @var \Zend_Validate_Interface[]
  21. */
  22. private $_rules = [];
  23. /**
  24. * Validation error messages
  25. *
  26. * @var array
  27. */
  28. private $_messages = [];
  29. /**
  30. * Add rule to be applied to a validation scope
  31. *
  32. * @param \Zend_Validate_Interface $validator
  33. * @param string $fieldName Field name to apply validation to, or empty value to validate entity as a whole
  34. * @return \Magento\Framework\Validator\DataObject
  35. * @api
  36. */
  37. public function addRule(\Zend_Validate_Interface $validator, $fieldName = '')
  38. {
  39. if (!array_key_exists($fieldName, $this->_rules)) {
  40. $this->_rules[$fieldName] = $validator;
  41. } else {
  42. $existingValidator = $this->_rules[$fieldName];
  43. if (!$existingValidator instanceof \Zend_Validate) {
  44. $compositeValidator = new \Zend_Validate();
  45. $compositeValidator->addValidator($existingValidator);
  46. $this->_rules[$fieldName] = $compositeValidator;
  47. }
  48. $this->_rules[$fieldName]->addValidator($validator);
  49. }
  50. return $this;
  51. }
  52. /**
  53. * Check whether the entity is valid according to defined validation rules
  54. *
  55. * @param \Magento\Framework\DataObject $entity
  56. * @return bool
  57. *
  58. * @throws \Exception
  59. * @api
  60. */
  61. public function isValid($entity)
  62. {
  63. $this->_messages = [];
  64. /** @var $validator \Zend_Validate_Interface */
  65. foreach ($this->_rules as $fieldName => $validator) {
  66. $value = $fieldName ? $entity->getDataUsingMethod($fieldName) : $entity;
  67. if (!$validator->isValid($value)) {
  68. $this->_messages = array_merge($this->_messages, array_values($validator->getMessages()));
  69. }
  70. }
  71. return empty($this->_messages);
  72. }
  73. /**
  74. * Return error messages (if any) after the last validation
  75. *
  76. * @return array
  77. */
  78. public function getMessages()
  79. {
  80. return $this->_messages;
  81. }
  82. }