summaryrefslogtreecommitdiff
path: root/src/Hird.php
blob: f60eca878a8653386e42d31826a266f9a26da191 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
<?php

declare(strict_types=1);

namespace Asko\Hird;

use Asko\Hird\Validators\DateFormatValidator;
use Asko\Hird\Validators\Validator;
use Asko\Hird\Validators\LenValidator;
use Asko\Hird\Validators\EmailValidator;
use Asko\Hird\Validators\RequiredValidator;

/**
 * Hird takes in an array of `$fields` and an array of  
 * `$rules`.
 * 
 * The key of each item in the `$fields` array must correspond to the 
 * the key of each item in the `$rules` array, so that Bouncer 
 * would know how to connect the two to each other.
 * 
 * The `$rules` must have a value that is a string where the rules
 * are separated by a `|` character, and each rule must match the key of
 * the implemented validator, such as `len`, `email` or one that you have 
 * implemented yourself. Additionally, each rule can take in a modifier, 
 * where the name of the rule and the modifier is separated by a `:` character.
 * 
 * For example, say we have a validator called `len` which takes a modifier that
 * lets that validator validate the length of a string, in such a case we'd write
 * that rule as `len:8`, which would indicate using a `len` validator and passing 
 * a modifier with the value `8` to it. 
 * 
 * Example usage of Hird: 
 * 
 * ```php
 * $fields = ['email' => 'asko@bien.ee'];
 * $rules = ['email' => 'required|email'];
 * $hird = new Hird($fields, $rules);
 * 
 * if ($hird->fails()) {
 *  return $hird->errors();
 * }
 * ```
 * 
 * @author Asko Nomm <asko@asko.dev>
 */
class Hird
{
    private array $errors = [];
    private array $validators = [];
    private array $fieldNames = [];

    public function __construct(
        private array $fields,
        private array $rules,
        array $fieldNames = []
    ) {
        $this->composeFieldNames($fieldNames);
        $this->registerDefaultValidators();
    }

    /**
     * Registers the default, built-in validators.
     *
     * @return void
     */
    private function registerDefaultValidators(): void
    {
        $this->registerValidator('len', LenValidator::class);
        $this->registerValidator('email', EmailValidator::class);
        $this->registerValidator('required', RequiredValidator::class);
        $this->registerValidator('date-format', DateFormatValidator::class);
    }

    /**
     * Composes the field names array.
     *
     * @param array $fieldNames
     * @return void
     */
    private function composeFieldNames(array $fieldNames): void
    {
        $updatedFieldNames = [];

        foreach ($this->fields as $field => $value) {
            $updatedFieldNames[$field] = $fieldNames[$field] ?? $field;
        }

        $this->fieldNames = $updatedFieldNames;
    }

    /**
     * Registers a validator to a `$ruleName`.
     *
     * @param string $ruleName
     * @param Validator $validator
     * @return void
     */
    public function registerValidator(string $ruleName, string $validator): void
    {
        $class = new \ReflectionClass($validator);
        $instance = null;

        if ($class->getConstructor() !== null) {
            $instance = $class->newInstanceArgs([$this->fields, $this->fieldNames]);
        } else {
            $instance = $class->newInstance();
        }

        $this->validators[$ruleName] = $instance;
    }

    /**
     * Removes a validator assigned to the `$ruleName`.
     *
     * @param string $ruleName
     * @return void
     */
    public function removeValidator(string $ruleName): void
    {
        unset($this->validators[$ruleName]);
    }

    /**
     * Runs `$this->rules` over `$this->fields` to construct 
     * potential errors that will be stored as an array of strings 
     * in `$this->errors`.
     *
     * @return void
     */
    public function validate(): void
    {
        foreach ($this->rules as $field => $rule) {
            $value = isset($this->fields[$field]) ? $this->fields[$field] : '';

            foreach (explode('|', $rule) as $item) {
                if (str_contains($item, ':')) {
                    $itemParts = explode(':', $item);
                    $name = $itemParts[0];
                    $modifier = implode(':', array_slice($itemParts, 1, count($itemParts) - 1, true));

                    if (!$this->validators[$name]->validate($field, $value, $modifier)) {
                        $this->errors[] = $this->validators[$name]->composeError($field, $modifier);
                    }
                } else {
                    if (!$this->validators[$item]->validate($field, $value)) {
                        $this->errors[] = $this->validators[$item]->composeError($field);
                    }
                }
            }
        }
    }

    /**
     * Returns a boolean `true` if there have been any errors.
     * Returns `false` otherwise.
     *
     * @return boolean
     */
    public function fails(): bool
    {
        $this->validate();

        return count($this->errors) !== 0;
    }

    /**
     * Returns an array of strings where each string 
     * is a single error that happened during validation.
     * 
     * @return array
     */
    public function errors(): array
    {
        return $this->errors;
    }

    /**
     * If errors are present, returns the first one.
     * Otherwise returns an empty string.
     *
     * @return string
     */
    public function firstError(): string
    {
        if (count($this->errors) > 0) {
            return $this->errors[0];
        }

        return '';
    }
}