Passed
Pull Request — master (#33)
by Melech
03:18
created

ValidateParamRequestTrait::getRules()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 12
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Valkyrja Framework package.
7
 *
8
 * (c) Melech Mizrachi <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Valkyrja\Routing\Middleware;
15
16
use Valkyrja\Http\Request;
17
18
/**
19
 * Trait ValidateTypeRequestTrait.
20
 *
21
 * @author Melech Mizrachi
22
 */
23
trait ValidateParamRequestTrait
24
{
25
    /**
26
     * @inheritDoc
27
     *
28
     * @return array<string, array{subject: mixed, rules: array<string, array{arguments: array, message?: string}>}>
29
     */
30
    protected static function getRules(Request $request): array
31
    {
32
        $rules = [];
33
34
        foreach (static::getParamRules() as $param => $paramRule) {
35
            $rules[$param] = [
36
                'subject' => static::getParamFromRequest($request, $param),
37
                'rules'   => $paramRule,
38
            ];
39
        }
40
41
        return $rules;
42
    }
43
44
    /**
45
     * Get the param validation rules.
46
     *
47
     * <code>
48
     *      $rules = [
49
     *          'title' => [
50
     *              'required' => [
51
     *                  'arguments'    => [],
52
     *                  'errorMessage' => 'Title is required.',
53
     *              ],
54
     *              'notEmpty' => [
55
     *                  'arguments'    => [],
56
     *                  'errorMessage' => 'Title must not be empty.',
57
     *              ],
58
     *              'min' => [
59
     *                  'arguments'    => [20],
60
     *                  'errorMessage' => 'Title must be at least 20 characters long.',
61
     *              ],
62
     *              'max' => [
63
     *                  'arguments'    => [500],
64
     *                  'errorMessage' => 'Title must be not be longer than 500 characters.',
65
     *              ],
66
     *          ],
67
     *      ]
68
     * </code>
69
     *
70
     * @return array<string, array<string, array{arguments: array, message?: string}>>
71
     */
72
    abstract protected static function getParamRules(): array;
73
74
    /**
75
     * Get a param from the request.
76
     *
77
     * @param Request $request The request
78
     * @param string  $param   The param
79
     *
80
     * @return mixed
81
     */
82
    abstract protected static function getParamFromRequest(Request $request, string $param): mixed;
83
}
84