Passed
Push — main ( 9fd9c1...757bec )
by Breno
01:56
created

HasKey::evaluate()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 9
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 19
rs 9.2222
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Rules;
5
6
use ArrayAccess;
7
use Attribute;
8
use BrenoRoosevelt\Validation\AbstractRule;
9
10
#[Attribute(Attribute::TARGET_PROPERTY)]
11
class HasKey extends AbstractRule
12
{
13
    const MESSAGE = 'Key not found: %s';
14
15
    public function __construct(private string $key, string $message = null)
16
    {
17
        parent::__construct($message ?? sprintf(self::MESSAGE, $this->key));
18
    }
19
20
    public function isValid($input, array $context = []): bool
21
    {
22
        if (is_array($input)) {
23
            return array_key_exists($this->key, $input);
24
        }
25
26
        if ($input instanceof ArrayAccess) {
27
            return $input->offsetExists($this->key);
28
        }
29
30
        if (is_iterable($input)) {
31
            foreach ($input as $k => $v) {
32
                if ($this->key === $k) {
33
                    return true;
34
                }
35
            }
36
        }
37
38
        return false;
39
    }
40
}
41