Contains.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 is_scalar;
  11. use function mb_stripos;
  12. use function mb_strpos;
  13. /**
  14. * Validates if the input contains some 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. * @author William Espindola <oi@williamespindola.com.br>
  20. */
  21. final class Contains extends AbstractRule
  22. {
  23. /**
  24. * @var mixed
  25. */
  26. private $containsValue;
  27. /**
  28. * @var bool
  29. */
  30. private $identical;
  31. /**
  32. * Initializes the Contains rule.
  33. *
  34. * @param mixed $containsValue Value that will be sought
  35. * @param bool $identical Defines whether the value is identical, default is false
  36. */
  37. public function __construct($containsValue, bool $identical = false)
  38. {
  39. $this->containsValue = $containsValue;
  40. $this->identical = $identical;
  41. }
  42. /**
  43. * {@inheritDoc}
  44. */
  45. public function validate($input): bool
  46. {
  47. if (is_array($input)) {
  48. return in_array($this->containsValue, $input, $this->identical);
  49. }
  50. if (!is_scalar($input) || !is_scalar($this->containsValue)) {
  51. return false;
  52. }
  53. return $this->validateString((string) $input, (string) $this->containsValue);
  54. }
  55. private function validateString(string $haystack, string $needle): bool
  56. {
  57. if ($needle === '') {
  58. return false;
  59. }
  60. if ($this->identical) {
  61. return mb_strpos($haystack, $needle) !== false;
  62. }
  63. return mb_stripos($haystack, $needle) !== false;
  64. }
  65. }