MessageBag::first()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 2
nc 8
nop 1
dl 0
loc 4
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
4
namespace SolBianca\Validator;
5
6
use SolBianca\Validator\Interfaces\MessageBagInterface;
7
8
class MessageBag implements MessageBagInterface
9
{
10
    /**
11
     * The registered messages.
12
     *
13
     * @var array
14
     */
15
    protected $messages = [];
16
17
    /**
18
     * Creates a new MessageBag instance.
19
     *
20
     * @param array $messages
21
     */
22
    public function __construct(array $messages)
23
    {
24
        foreach ($messages as $key => $value) {
25
            $this->messages[$key] = (array)$value;
26
        }
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function has(string $key): bool
33
    {
34
        return !is_null($this->first($key));
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function first(string $key = null): ?string
41
    {
42
        $messages = is_null($key) ? $this->flat() : $this->get($key);
43
        return (is_array($messages) && count($messages) > 0) ? $messages[0] : null;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function get(string $key): ?array
50
    {
51
        if (array_key_exists($key, $this->messages)) {
52
            return !empty($this->messages[$key]) ? $this->messages[$key] : null;
53
        }
54
        return null;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function all(): array
61
    {
62
        return $this->messages;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function keys(): array
69
    {
70
        return array_keys($this->messages);
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function isEmpty(): bool
77
    {
78
        return empty($this->messages);
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function flat(): array
85
    {
86
        return iterator_to_array(new \RecursiveIteratorIterator(
87
            new \RecursiveArrayIterator($this->messages)
88
        ), false);
89
    }
90
}