Passed
Pull Request — main (#13)
by Jeremy
02:09
created

SizeValidator   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 15
eloc 35
c 2
b 0
f 0
dl 0
loc 66
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getPercentValue() 0 7 2
A __construct() 0 3 1
C valid() 0 40 12
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
        $percent_value = (int)$this->getPercentValue($value);
43
44
        if ($isPercent) {
45
            if ($percent_value == 0 || $percent_value < 1) {
46
                throw new BadRequestException("Size $value is invalid.");
47
            }
48
            if ($this->upscale) {
49
                return true;
50
            }
51
            if ($percent_value > 100) {
52
                throw new BadRequestException("Size $value is invalid.");
53
            }
54
55
            if ($percent_value <= 100) {
56
                return true;
57
            }
58
        }
59
60
        $all_regex = implode('|', $this->regex);
61
        if (preg_match('/' . $all_regex . '/', $value)) {
62
            return true;
63
        }
64
65
        throw new BadRequestException("Size $value is invalid.");
66
    }
67
68
    protected function getPercentValue($value)
69
    {
70
        if ($this->upscale) {
71
            return preg_replace('/^\^pct:/', '', $value);
72
        }
73
74
        return preg_replace('/pct:/', '', $value);
75
    }
76
}
77