|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com> |
| 5 | + * SPDX-License-Identifier: MIT |
| 6 | + */ |
| 7 | + |
| 8 | +declare(strict_types=1); |
| 9 | + |
| 10 | +namespace Respect\Validation\Validators; |
| 11 | + |
| 12 | +use Attribute; |
| 13 | +use Respect\Validation\Message\Template; |
| 14 | +use Respect\Validation\Result; |
| 15 | +use Respect\Validation\Validator; |
| 16 | + |
| 17 | +use function in_array; |
| 18 | +use function is_array; |
| 19 | +use function is_scalar; |
| 20 | +use function mb_strtolower; |
| 21 | +use function mb_substr_count; |
| 22 | + |
| 23 | +#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] |
| 24 | +#[Template( |
| 25 | + '{{subject}} must contain {{containsValue}} {{count}} time(s)', |
| 26 | + '{{subject}} must not contain {{containsValue}} {{count}} time(s)', |
| 27 | +)] |
| 28 | +final readonly class ContainsCount implements Validator |
| 29 | +{ |
| 30 | + public function __construct( |
| 31 | + private mixed $containsValue, |
| 32 | + private int $count, |
| 33 | + private bool $identical = false, |
| 34 | + ) { |
| 35 | + } |
| 36 | + |
| 37 | + public function evaluate(mixed $input): Result |
| 38 | + { |
| 39 | + $parameters = [ |
| 40 | + 'containsValue' => $this->containsValue, |
| 41 | + 'count' => $this->count, |
| 42 | + ]; |
| 43 | + |
| 44 | + if (is_array($input)) { |
| 45 | + return Result::of( |
| 46 | + $this->countArrayOccurrences($input) === $this->count, |
| 47 | + $input, |
| 48 | + $this, |
| 49 | + $parameters, |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + if (!is_scalar($input) || !is_scalar($this->containsValue)) { |
| 54 | + return Result::failed($input, $this, $parameters); |
| 55 | + } |
| 56 | + |
| 57 | + $needle = (string) $this->containsValue; |
| 58 | + |
| 59 | + if ($needle === '') { |
| 60 | + return Result::failed($input, $this, $parameters); |
| 61 | + } |
| 62 | + |
| 63 | + return Result::of( |
| 64 | + $this->countStringOccurrences((string) $input, $needle) === $this->count, |
| 65 | + $input, |
| 66 | + $this, |
| 67 | + $parameters, |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + private function countArrayOccurrences(mixed $input): int |
| 72 | + { |
| 73 | + $count = 0; |
| 74 | + foreach ($input as $item) { |
| 75 | + if (!in_array($this->containsValue, [$item], $this->identical)) { |
| 76 | + continue; |
| 77 | + } |
| 78 | + |
| 79 | + $count++; |
| 80 | + } |
| 81 | + |
| 82 | + return $count; |
| 83 | + } |
| 84 | + |
| 85 | + private function countStringOccurrences(string $haystack, string $needle): int |
| 86 | + { |
| 87 | + if ($this->identical) { |
| 88 | + return mb_substr_count($haystack, $needle); |
| 89 | + } |
| 90 | + |
| 91 | + return mb_substr_count(mb_strtolower($haystack), mb_strtolower($needle)); |
| 92 | + } |
| 93 | +} |
0 commit comments