Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
19 / 19 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
HasOne | |
100.00% |
19 / 19 |
|
100.00% |
2 / 2 |
13 | |
100.00% |
1 / 1 |
evaluate | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
9 | |||
generateDefaultMessage | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
4 |
1 | <?php |
2 | /** |
3 | * Pop PHP Framework (http://www.popphp.org/) |
4 | * |
5 | * @link https://github.com/popphp/popphp-framework |
6 | * @author Nick Sagona, III <dev@noladev.com> |
7 | * @copyright Copyright (c) 2009-2025 NOLA Interactive, LLC. |
8 | * @license http://www.popphp.org/license New BSD License |
9 | */ |
10 | |
11 | /** |
12 | * @namespace |
13 | */ |
14 | namespace Pop\Validator; |
15 | |
16 | /** |
17 | * Has one validator class |
18 | * |
19 | * @category Pop |
20 | * @package Pop\Validator |
21 | * @author Nick Sagona, III <dev@noladev.com> |
22 | * @copyright Copyright (c) 2009-2025 NOLA Interactive, LLC. |
23 | * @license http://www.popphp.org/license New BSD License |
24 | * @version 4.5.0 |
25 | */ |
26 | class HasOne extends AbstractValidator |
27 | { |
28 | |
29 | /** |
30 | * Traits |
31 | */ |
32 | use TraverseTrait; |
33 | |
34 | /** |
35 | * Method to evaluate the validator |
36 | * |
37 | * @param mixed $input |
38 | * @throws Exception |
39 | * @return bool |
40 | */ |
41 | public function evaluate(mixed $input = null): bool |
42 | { |
43 | // Set the input, if passed |
44 | if ($input !== null) { |
45 | $this->input = $input; |
46 | } |
47 | |
48 | // Set the default message |
49 | if (!$this->hasMessage()) { |
50 | $this->generateDefaultMessage(); |
51 | } |
52 | |
53 | if (!is_array($input)) { |
54 | throw new Exception('Error: The evaluated input must be an array.'); |
55 | } |
56 | if (empty($this->value)) { |
57 | throw new Exception('Error: The evaluated value cannot be empty.'); |
58 | } |
59 | |
60 | if (!str_contains($this->value, '.')) { |
61 | return (array_key_exists($this->value, $this->input) && |
62 | is_array($this->input[$this->value]) && count($this->input[$this->value]) > 0); |
63 | } else { |
64 | $value = []; |
65 | self::traverseData($this->value, $this->input, $value); |
66 | return (is_array($value) && (count($value) > 0)); |
67 | } |
68 | } |
69 | |
70 | /** |
71 | * Generate default message |
72 | |
73 | * @param mixed $name |
74 | * @param mixed $value |
75 | * @return string |
76 | */ |
77 | public function generateDefaultMessage(mixed $name = null, mixed $value = null): string |
78 | { |
79 | if ($value === null) { |
80 | $value = $this->value; |
81 | } |
82 | $this->message = "The " . (($name !== null) ? "'" . $name . "'" : "value") . |
83 | " must contain at least one item" . (($value !== null) ? " of '" . $value . "'." : "."); |
84 | |
85 | return $this->message; |
86 | } |
87 | |
88 | } |