Validator.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Sales\Model;
  7. use Magento\Framework\Exception\ConfigurationMismatchException;
  8. use Magento\Framework\ObjectManagerInterface;
  9. /**
  10. * Class Validator
  11. *
  12. * @internal
  13. */
  14. class Validator
  15. {
  16. /**
  17. * @var ObjectManagerInterface
  18. */
  19. private $objectManager;
  20. /**
  21. * @var ValidatorResultInterfaceFactory
  22. */
  23. private $validatorResultFactory;
  24. /**
  25. * Validator constructor.
  26. *
  27. * @param ObjectManagerInterface $objectManager
  28. * @param ValidatorResultInterfaceFactory $validatorResult
  29. */
  30. public function __construct(
  31. ObjectManagerInterface $objectManager,
  32. ValidatorResultInterfaceFactory $validatorResult
  33. ) {
  34. $this->objectManager = $objectManager;
  35. $this->validatorResultFactory = $validatorResult;
  36. }
  37. /**
  38. * @param object $entity
  39. * @param ValidatorInterface[] $validators
  40. * @param object|null $context
  41. * @return ValidatorResultInterface
  42. * @throws ConfigurationMismatchException
  43. */
  44. public function validate($entity, array $validators, $context = null)
  45. {
  46. $messages = [];
  47. $validatorArguments = [];
  48. if ($context !== null) {
  49. $validatorArguments['context'] = $context;
  50. }
  51. foreach ($validators as $validatorName) {
  52. $validator = $this->objectManager->create($validatorName, $validatorArguments);
  53. if (!$validator instanceof ValidatorInterface) {
  54. throw new ConfigurationMismatchException(
  55. __('The "%1" validator is not an instance of the general validator interface.', $validatorName)
  56. );
  57. }
  58. $messages = array_merge($messages, $validator->validate($entity));
  59. }
  60. $validationResult = $this->validatorResultFactory->create();
  61. foreach ($messages as $message) {
  62. $validationResult->addMessage($message);
  63. }
  64. return $validationResult;
  65. }
  66. }