Passed
Push — main ( 954523...045e26 )
by Breno
01:54
created

HasKey   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 37
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 19 6
A __construct() 0 6 1
A translatedMessage() 0 3 1
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
use BrenoRoosevelt\Validation\StopSign;
10
use BrenoRoosevelt\Validation\Translation\Translator;
11
12
#[Attribute(Attribute::TARGET_PROPERTY)]
13
class HasKey extends AbstractRule
14
{
15
    const MESSAGE = 'Key not found: %s';
16
17
    public function __construct(
18
        private string $key,
19
        ?string $message = null,
20
        int $stopOnFailure = StopSign::DONT_STOP
21
    ) {
22
        parent::__construct($message, $stopOnFailure);
23
    }
24
25
    public function isValid($input, array $context = []): bool
26
    {
27
        if (is_array($input)) {
28
            return array_key_exists($this->key, $input);
29
        }
30
31
        if ($input instanceof ArrayAccess) {
32
            return $input->offsetExists($this->key);
33
        }
34
35
        if (is_iterable($input)) {
36
            foreach ($input as $k => $v) {
37
                if ($this->key === $k) {
38
                    return true;
39
                }
40
            }
41
        }
42
43
        return false;
44
    }
45
46
    public function translatedMessage(): ?string
47
    {
48
        return Translator::translate(self::MESSAGE, $this->key);
49
    }
50
}
51