StartsWith.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 is_array;
  9. use function is_string;
  10. use function mb_stripos;
  11. use function mb_strpos;
  12. use function reset;
  13. /**
  14. * Validates whether the input starts with a given value.
  15. *
  16. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  17. * @author Henrique Moody <henriquemoody@gmail.com>
  18. * @author Marcelo Araujo <msaraujo@php.net>
  19. */
  20. final class StartsWith extends AbstractRule
  21. {
  22. /**
  23. * @var mixed
  24. */
  25. private $startValue;
  26. /**
  27. * @var bool
  28. */
  29. private $identical;
  30. /**
  31. * @param mixed $startValue
  32. */
  33. public function __construct($startValue, bool $identical = false)
  34. {
  35. $this->startValue = $startValue;
  36. $this->identical = $identical;
  37. }
  38. /**
  39. * {@inheritDoc}
  40. */
  41. public function validate($input): bool
  42. {
  43. if ($this->identical) {
  44. return $this->validateIdentical($input);
  45. }
  46. return $this->validateEquals($input);
  47. }
  48. /**
  49. * @param mixed $input
  50. */
  51. protected function validateEquals($input): bool
  52. {
  53. if (is_array($input)) {
  54. return reset($input) == $this->startValue;
  55. }
  56. if (is_string($input) && is_string($this->startValue)) {
  57. return mb_stripos($input, $this->startValue) === 0;
  58. }
  59. return false;
  60. }
  61. /**
  62. * @param mixed $input
  63. */
  64. protected function validateIdentical($input): bool
  65. {
  66. if (is_array($input)) {
  67. return reset($input) === $this->startValue;
  68. }
  69. if (is_string($input) && is_string($this->startValue)) {
  70. return mb_strpos($input, $this->startValue) === 0;
  71. }
  72. return false;
  73. }
  74. }