RegionValidator::validateFullOrSquare()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Conlect\ImageIIIF\Validators;
4
5
use function array_filter;
6
7
use Conlect\ImageIIIF\Exceptions\BadRequestException;
8
use Conlect\ImageIIIF\Validators\Contracts\ValidatorInterface;
9
10
use function count;
11
use function explode;
12
use function in_array;
13
use function str_starts_with;
14
15
class RegionValidator extends ValidatorAbstract implements ValidatorInterface
16
{
17
    public function valid($value)
18
    {
19
        $options = explode(',', $value);
20
21
        if (count($options) == 1) {
22
            return $this->validateFullOrSquare($options[0]);
23
        }
24
25
        if (count($options) !== 4) {
26
            return $this->valueException($value);
27
        }
28
29
        if ($options[2] == 0 || $options[3] == 0) {
30
            return $this->zeroException();
31
        }
32
33
        if (str_starts_with($options[0], 'pct:')) {
34
            $options[0] = \substr($options[0], 4);
35
        }
36
37
        if (4 === count(array_filter($options, 'is_numeric'))) {
38
            $validator = new ValidatorShared();
39
            foreach ($options as $option) {
40
                $validator->floatingPointValidator($option);
41
            }
42
43
            return true;
44
        }
45
46
47
        return $this->valueException($value);
48
    }
49
50
    protected function validateFullOrSquare($value)
51
    {
52
        if (in_array($value, ['full', 'square'])) {
53
            return true;
54
        }
55
56
        return $this->valueException($value);
57
    }
58
59
    protected function valueException($value)
60
    {
61
        throw new BadRequestException("Region $value is invalid.");
62
    }
63
64
    protected function zeroException()
65
    {
66
        throw new BadRequestException('Region width and height should be greater than zero.');
67
    }
68
}
69