AbstractComparison.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\PropertyAccess\PropertyAccess;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
  14. use Symfony\Component\Validator\Exception\LogicException;
  15. /**
  16. * Used for the comparison of values.
  17. *
  18. * @author Daniel Holmes <daniel@danielholmes.org>
  19. * @author Bernhard Schussek <bschussek@gmail.com>
  20. */
  21. abstract class AbstractComparison extends Constraint
  22. {
  23. public $message;
  24. public $value;
  25. public $propertyPath;
  26. /**
  27. * {@inheritdoc}
  28. *
  29. * @param mixed $value the value to compare or a set of options
  30. */
  31. public function __construct($value = null, $propertyPath = null, string $message = null, array $groups = null, $payload = null, array $options = [])
  32. {
  33. if (\is_array($value)) {
  34. $options = array_merge($value, $options);
  35. } elseif (null !== $value) {
  36. $options['value'] = $value;
  37. }
  38. parent::__construct($options, $groups, $payload);
  39. $this->message = $message ?? $this->message;
  40. $this->propertyPath = $propertyPath ?? $this->propertyPath;
  41. if (null === $this->value && null === $this->propertyPath) {
  42. throw new ConstraintDefinitionException(sprintf('The "%s" constraint requires either the "value" or "propertyPath" option to be set.', static::class));
  43. }
  44. if (null !== $this->value && null !== $this->propertyPath) {
  45. throw new ConstraintDefinitionException(sprintf('The "%s" constraint requires only one of the "value" or "propertyPath" options to be set, not both.', static::class));
  46. }
  47. if (null !== $this->propertyPath && !class_exists(PropertyAccess::class)) {
  48. throw new LogicException(sprintf('The "%s" constraint requires the Symfony PropertyAccess component to use the "propertyPath" option.', static::class));
  49. }
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function getDefaultOption()
  55. {
  56. return 'value';
  57. }
  58. }