Passed
Pull Request — master (#33)
by Melech
05:54 queued 02:40
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
    protected static function getRules(Request $request): array
29
    {
30
        $rules = [];
31
32
        foreach (static::getParamRules() as $param => $paramRule) {
33
            $rules[$param] = [
34
                'subject' => static::getParamFromRequest($request, $param),
35
                'rules'   => $paramRule,
36
            ];
37
        }
38
39
        return $rules;
40
    }
41
42
    /**
43
     * Get the param validation rules.
44
     *
45
     * <code>
46
     *      $rules = [
47
     *          'title' => [
48
     *              'required' => [
49
     *                  'arguments'    => [],
50
     *                  'errorMessage' => 'Title is required.',
51
     *              ],
52
     *              'notEmpty' => [
53
     *                  'arguments'    => [],
54
     *                  'errorMessage' => 'Title must not be empty.',
55
     *              ],
56
     *              'min' => [
57
     *                  'arguments'    => [20],
58
     *                  'errorMessage' => 'Title must be at least 20 characters long.',
59
     *              ],
60
     *              'max' => [
61
     *                  'arguments'    => [500],
62
     *                  'errorMessage' => 'Title must be not be longer than 500 characters.',
63
     *              ],
64
     *          ],
65
     *      ]
66
     * </code>
67
     *
68
     * @return array{string: array<string, array{arguments: array, errorMessage: string}>}
69
     */
70
    abstract protected static function getParamRules(): array;
71
72
    /**
73
     * Get a param from the request.
74
     *
75
     * @param Request $request The request
76
     * @param string  $param   The param
77
     *
78
     * @return mixed
79
     */
80
    abstract protected static function getParamFromRequest(Request $request, string $param): mixed;
81
}
82