diff options
| author | David T. Sadler <davidtsadler@googlemail.com> | 2021-10-20 20:59:55 +0100 |
|---|---|---|
| committer | David T. Sadler <davidtsadler@googlemail.com> | 2021-10-20 20:59:55 +0100 |
| commit | d4122f116c937e0ec509d8cefe540146ec27a0cd (patch) | |
| tree | 481f90c4d774d32c89e612594158fe4a2d7328a4 /src/DTS/Validator.php | |
| parent | 1a112ab14becaf6d41cd34c176cbe563d4ca9742 (diff) | |
Validate fields
Diffstat (limited to 'src/DTS/Validator.php')
| -rw-r--r-- | src/DTS/Validator.php | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/src/DTS/Validator.php b/src/DTS/Validator.php new file mode 100644 index 0000000..7629e3b --- /dev/null +++ b/src/DTS/Validator.php @@ -0,0 +1,81 @@ +<?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->validateUrl($request['url'], 8, 512); + + $this->validateTitle($request['title'], 8, 256); + + $this->validateTag($request['tag'], 2, 8); + } + + private function validateUrl(string $url, int $minLength, int $maxLength): void + { + $url = trim($url); + + if (filter_var($url, FILTER_VALIDATE_URL) === false) { + $this->errors->add('url', 'Must be a URL'); + } + + if (strlen($url) < $minLength || strlen($url) > $maxLength) { + $this->errors->add('url', "Must be between $minLength and $maxLength in characters in length"); + } + + if (!$this->errors->has('url')) { + $this->validated->url = $url; + } + } + + private function validateTitle(string $title, int $minLength, int $maxLength): void + { + $title = trim($title); + + if ($title === '') { + return; + } + + if (strlen($title) < $minLength || strlen($title) > $maxLength) { + $this->errors->add('title', "Must be between $minLength and $maxLength in characters in length"); + } + + if (!$this->errors->has('tite')) { + $this->validated->title = $title; + } + } + + 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); + } + } +} |
