In.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 in_array;
  9. use function is_array;
  10. use function mb_stripos;
  11. use function mb_strpos;
  12. /**
  13. * Validates if the input can be found in a defined array or string.
  14. *
  15. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  16. * @author Danilo Benevides <danilobenevides01@gmail.com>
  17. * @author Henrique Moody <henriquemoody@gmail.com>
  18. */
  19. final class In extends AbstractRule
  20. {
  21. /**
  22. * @var mixed[]|mixed
  23. */
  24. private $haystack;
  25. /**
  26. * @var bool
  27. */
  28. private $compareIdentical;
  29. /**
  30. * Initializes the rule with the haystack and optionally compareIdentical flag.
  31. *
  32. * @param mixed[]|mixed $haystack
  33. */
  34. public function __construct($haystack, bool $compareIdentical = false)
  35. {
  36. $this->haystack = $haystack;
  37. $this->compareIdentical = $compareIdentical;
  38. }
  39. /**
  40. * {@inheritDoc}
  41. */
  42. public function validate($input): bool
  43. {
  44. if ($this->compareIdentical) {
  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($this->haystack)) {
  55. return in_array($input, $this->haystack);
  56. }
  57. if ($input === null || $input === '') {
  58. return $input == $this->haystack;
  59. }
  60. return mb_stripos($this->haystack, (string) $input) !== false;
  61. }
  62. /**
  63. * @param mixed $input
  64. */
  65. private function validateIdentical($input): bool
  66. {
  67. if (is_array($this->haystack)) {
  68. return in_array($input, $this->haystack, true);
  69. }
  70. if ($input === null || $input === '') {
  71. return $input === $this->haystack;
  72. }
  73. return mb_strpos($this->haystack, (string) $input) !== false;
  74. }
  75. }