summaryrefslogtreecommitdiff
path: root/src/DTS/Validator.php
blob: a2ab48faca8de617cb0a165d7385ea0e43ef308b (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
<?php

declare(strict_types=1);

namespace DTS;

use DTS\Errors;
use DTS\Validated;

class Validator
{
    public Errors $errors;

    public Validated $validated;

    function __construct(array $request) 
    {
        $this->errors = new Errors();

        $this->validated = new Validated();

        $this->validateTask($request['task'], 2, 256);

        $this->validateDescription($request['description'], 8, 512);

        $this->validateTag($request['tag'], 2, 16);
    }

    private function validateTask(string $task, int $minLength, int $maxLength): void
    {
        $task = trim($task);

        if (strlen($task) < $minLength  || strlen($task) > $maxLength) {
            $this->errors->add('task', "Must be between $minLength and $maxLength in characters in length");
        }

        if (!$this->errors->has('tite')) {
            $this->validated->task = $task;
        }
    }

    private function validateDescription(string $description, int $minLength, int $maxLength): void
    {
        $description = trim($description);

        if ($description === '') {
            return;
        }

        if (strlen($description) < $minLength  || strlen($description) > $maxLength) {
            $this->errors->add('description', "Must be between $minLength and $maxLength in characters in length");
        }

        if (!$this->errors->has('tite')) {
            $this->validated->description = $description;
        }
    }

    private function validateTag(string $tag, int $minLength, int $maxLength): void
    {
        $tag = trim($tag);

        if ($tag === '') {
            return;
        }

        if (strlen($tag) < $minLength  || strlen($tag) > $maxLength) {
            $this->errors->add('tag', "Must be between $minLength and $maxLength in characters in length");
        }
        if (preg_match('/\W/', $tag) === 1) {
            $this->errors->add('tag', 'May only contain word characters');
        }

        if (!$this->errors->has('tag')) {
            $this->validated->tag = strtolower($tag);
        }
    }
}