Assert.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * Assert
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * If you did not receive a copy of the license and are unable to
  10. * obtain it through the world-wide-web, please send an email
  11. * to kontakt@beberlei.de so I can send you a copy immediately.
  12. */
  13. namespace Assert;
  14. /**
  15. * AssertionChain factory.
  16. */
  17. abstract class Assert
  18. {
  19. /** @var string */
  20. protected static $lazyAssertionExceptionClass = LazyAssertionException::class;
  21. /** @var string */
  22. protected static $assertionClass = Assertion::class;
  23. /**
  24. * Start validation on a value, returns {@link AssertionChain}.
  25. *
  26. * The invocation of this method starts an assertion chain
  27. * that is happening on the passed value.
  28. *
  29. * @param mixed $value
  30. * @param string|callable|null $defaultMessage
  31. *
  32. * @example
  33. *
  34. * Assert::that($value)->notEmpty()->integer();
  35. * Assert::that($value)->nullOr()->string()->startsWith("Foo");
  36. *
  37. * The assertion chain can be stateful, that means be careful when you reuse
  38. * it. You should never pass around the chain.
  39. */
  40. public static function that($value, $defaultMessage = null, ?string $defaultPropertyPath = null): AssertionChain
  41. {
  42. $assertionChain = new AssertionChain($value, $defaultMessage, $defaultPropertyPath);
  43. return $assertionChain->setAssertionClassName(static::$assertionClass);
  44. }
  45. /**
  46. * Start validation on a set of values, returns {@link AssertionChain}.
  47. *
  48. * @param mixed $values
  49. * @param string|callable|null $defaultMessage
  50. */
  51. public static function thatAll($values, $defaultMessage = null, ?string $defaultPropertyPath = null): AssertionChain
  52. {
  53. return static::that($values, $defaultMessage, $defaultPropertyPath)->all();
  54. }
  55. /**
  56. * Start validation and allow NULL, returns {@link AssertionChain}.
  57. *
  58. * @param mixed $value
  59. * @param string|callable|null $defaultMessage
  60. */
  61. public static function thatNullOr($value, $defaultMessage = null, ?string $defaultPropertyPath = null): AssertionChain
  62. {
  63. return static::that($value, $defaultMessage, $defaultPropertyPath)->nullOr();
  64. }
  65. /**
  66. * Create a lazy assertion object.
  67. */
  68. public static function lazy(): LazyAssertion
  69. {
  70. $lazyAssertion = new LazyAssertion();
  71. return $lazyAssertion
  72. ->setAssertClass(\get_called_class())
  73. ->setExceptionClass(static::$lazyAssertionExceptionClass);
  74. }
  75. }