EndsWith.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation\Rules;
  8. use function end;
  9. use function is_array;
  10. use function mb_strlen;
  11. use function mb_strripos;
  12. use function mb_strrpos;
  13. /**
  14. * Validates only if the value is at the end of the input.
  15. *
  16. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  17. * @author Henrique Moody <henriquemoody@gmail.com>
  18. * @author Hugo Hamon <hugo.hamon@sensiolabs.com>
  19. * @author William Espindola <oi@williamespindola.com.br>
  20. */
  21. final class EndsWith extends AbstractRule
  22. {
  23. /**
  24. * @var mixed
  25. */
  26. private $endValue;
  27. /**
  28. * @var bool
  29. */
  30. private $identical;
  31. /**
  32. * @param mixed $endValue
  33. */
  34. public function __construct($endValue, bool $identical = false)
  35. {
  36. $this->endValue = $endValue;
  37. $this->identical = $identical;
  38. }
  39. /**
  40. * {@inheritDoc}
  41. */
  42. public function validate($input): bool
  43. {
  44. if ($this->identical) {
  45. return $this->validateIdentical($input);
  46. }
  47. return $this->validateEquals($input);
  48. }
  49. /**
  50. * @param mixed $input
  51. */
  52. private function validateEquals($input): bool
  53. {
  54. if (is_array($input)) {
  55. return end($input) == $this->endValue;
  56. }
  57. return mb_strripos($input, $this->endValue) === mb_strlen($input) - mb_strlen($this->endValue);
  58. }
  59. /**
  60. * @param mixed $input
  61. */
  62. private function validateIdentical($input): bool
  63. {
  64. if (is_array($input)) {
  65. return end($input) === $this->endValue;
  66. }
  67. return mb_strrpos($input, $this->endValue) === mb_strlen($input) - mb_strlen($this->endValue);
  68. }
  69. }