Passed
Push — main ( ef8132...1c2de8 )
by Jeremy
02:20 queued 12s
created

SizeValidator::valid()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 28
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 28
rs 8.8333
cc 7
nc 6
nop 1
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 $allow_upscaling;
12
    protected $upscale;
13
    protected $regex = [
14
        ',[0-9]+',
15
        '\^,[0-9]+',
16
        '[0-9]+,',
17
        '\^[0-9]+,',
18
        '{!}?[0-9]+,[0-9]+',
19
    ];
20
21
    public function __construct($config)
22
    {
23
        $this->allow_upscaling = $config['allow_upscaling'];
24
    }
25
26
    public function valid($value)
27
    {
28
        if ($value === 'max') {
29
            return true;
30
        }
31
32
        if ($value === '^max') {
33
            throw new NotImplementedException("Maximum size is not implemented.");
34
        }
35
36
        if (! $this->allow_upscaling && $this->upscale) {
37
            throw new NotImplementedException("Upscaling is not allowed.");
38
        }
39
40
        $this->upscale = str_starts_with($value, '^');
41
        $isPercent = str_contains($value, 'pct:');
42
43
44
        if ($isPercent) {
45
            return $this->isValidPercent($value);
46
        }
47
48
        $all_regex = implode('|', $this->regex);
49
        if (preg_match('/' . $all_regex . '/', $value)) {
50
            return true;
51
        }
52
53
        throw new BadRequestException("Size $value is invalid.");
54
    }
55
56
    protected function getPercentValue($value)
57
    {
58
        if ($this->upscale) {
59
            return preg_replace('/^\^pct:/', '', $value);
60
        }
61
62
        return preg_replace('/pct:/', '', $value);
63
    }
64
65
    protected function isValidPercent($value)
66
    {
67
        $percent_value = (int) $this->getPercentValue($value);
68
        if ($percent_value < 1 || ($percent_value > 100 && ! $this->upscale)) {
69
            throw new BadRequestException("Size $value is invalid.");
70
        }
71
72
        return true;
73
    }
74
}
75