Validation.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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;
  11. use Symfony\Component\Validator\Exception\ValidationFailedException;
  12. use Symfony\Component\Validator\Validator\ValidatorInterface;
  13. /**
  14. * Entry point for the Validator component.
  15. *
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. final class Validation
  19. {
  20. /**
  21. * Creates a callable chain of constraints.
  22. *
  23. * @param Constraint|ValidatorInterface|null $constraintOrValidator
  24. */
  25. public static function createCallable($constraintOrValidator = null, Constraint ...$constraints): callable
  26. {
  27. $validator = $constraintOrValidator;
  28. if ($constraintOrValidator instanceof Constraint) {
  29. $constraints = \func_get_args();
  30. $validator = null;
  31. } elseif (null !== $constraintOrValidator && !$constraintOrValidator instanceof ValidatorInterface) {
  32. throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a "%s" or a "%s" object, "%s" given.', __METHOD__, Constraint::class, ValidatorInterface::class, get_debug_type($constraintOrValidator)));
  33. }
  34. $validator = $validator ?? self::createValidator();
  35. return static function ($value) use ($constraints, $validator) {
  36. $violations = $validator->validate($value, $constraints);
  37. if (0 !== $violations->count()) {
  38. throw new ValidationFailedException($value, $violations);
  39. }
  40. return $value;
  41. };
  42. }
  43. /**
  44. * Creates a new validator.
  45. *
  46. * If you want to configure the validator, use
  47. * {@link createValidatorBuilder()} instead.
  48. */
  49. public static function createValidator(): ValidatorInterface
  50. {
  51. return self::createValidatorBuilder()->getValidator();
  52. }
  53. /**
  54. * Creates a configurable builder for validator objects.
  55. */
  56. public static function createValidatorBuilder(): ValidatorBuilder
  57. {
  58. return new ValidatorBuilder();
  59. }
  60. /**
  61. * This class cannot be instantiated.
  62. */
  63. private function __construct()
  64. {
  65. }
  66. }