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

HasKey   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 29
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A isValid() 0 19 6
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