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
|
|
|
|