Passed
Pull Request — main (#22)
by
unknown
04:18 queued 02:08
created

SizeValidator   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
eloc 29
c 1
b 0
f 0
dl 0
loc 58
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getPercentValue() 0 7 2
A valid() 0 28 6
A isValidPercent() 0 8 4
1
<?php
2
3
namespace Conlect\ImageIIIF\Validators;
4
5
use Conlect\ImageIIIF\Exceptions\BadRequestException;
6
use Conlect\ImageIIIF\Exceptions\NotImplementedException;
7
use Conlect\ImageIIIF\Validators\Contracts\ValidatorInterface;
8
9
class SizeValidator extends ValidatorAbstract implements ValidatorInterface
10
{
11
    protected $upscale;
12
    protected $regex = [
13
        ',[0-9]+',
14
        '\^,[0-9]+',
15
        '[0-9]+,',
16
        '\^[0-9]+,',
17
        '{!}?[0-9]+,[0-9]+',
18
    ];
19
20
    public function valid($value)
21
    {
22
        if ($value === 'max') {
23
            return true;
24
        }
25
26
        if ($value === '^max') {
27
            throw new NotImplementedException("Maximum size is not implemented.");
28
        }
29
30
        $this->upscale = str_starts_with($value, '^');
31
32
        if ($this->upscale) {
33
            throw new NotImplementedException("Upscaling is not allowed.");
34
        }
35
36
        $isPercent = str_contains($value, 'pct:');
37
38
        if ($isPercent) {
39
            return $this->isValidPercent($value);
40
        }
41
42
        $all_regex = implode('|', $this->regex);
43
        if (preg_match('/' . $all_regex . '/', $value)) {
44
            return true;
45
        }
46
47
        throw new BadRequestException("Size $value is invalid.");
48
    }
49
50
    protected function getPercentValue($value)
51
    {
52
        if ($this->upscale) {
53
            return preg_replace('/^\^pct:/', '', $value);
54
        }
55
56
        return preg_replace('/pct:/', '', $value);
57
    }
58
59
    protected function isValidPercent($value)
60
    {
61
        $percent_value = (int) $this->getPercentValue($value);
62
        if ($percent_value < 1 || ($percent_value > 100 && ! $this->upscale)) {
63
            throw new BadRequestException("Size $value is invalid.");
64
        }
65
66
        return true;
67
    }
68
}
69