Validator.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Bundle\Model\Option;
  7. use Magento\Framework\Validator\NotEmpty;
  8. use Magento\Framework\Validator\NotEmptyFactory;
  9. use Zend_Validate_Exception;
  10. class Validator extends \Magento\Framework\Validator\AbstractValidator
  11. {
  12. /**
  13. * @var NotEmpty
  14. */
  15. private $notEmpty;
  16. /**
  17. * @param NotEmptyFactory $notEmptyFactory
  18. */
  19. public function __construct(NotEmptyFactory $notEmptyFactory)
  20. {
  21. $this->notEmpty = $notEmptyFactory->create(['options' => NotEmpty::ALL]);
  22. }
  23. /**
  24. * @param \Magento\Bundle\Model\Option $value
  25. * @return boolean
  26. * @throws Zend_Validate_Exception If validation of $value is impossible
  27. */
  28. public function isValid($value)
  29. {
  30. $this->validateRequiredFields($value);
  31. return !$this->hasMessages();
  32. }
  33. /**
  34. * @param \Magento\Bundle\Model\Option $value
  35. * @return void
  36. * @throws Zend_Validate_Exception
  37. * @throws \Exception
  38. */
  39. protected function validateRequiredFields($value)
  40. {
  41. $messages = [];
  42. $requiredFields = [
  43. 'title' => $value->getTitle(),
  44. 'type' => $value->getType()
  45. ];
  46. foreach ($requiredFields as $requiredField => $requiredValue) {
  47. if (!$this->notEmpty->isValid(trim($requiredValue))) {
  48. $messages[$requiredField] =
  49. __('"%fieldName" is required. Enter and try again.', ['fieldName' => $requiredField]);
  50. }
  51. }
  52. $this->_addMessages($messages);
  53. }
  54. }