-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringDenormalizer.php
More file actions
71 lines (59 loc) · 2.07 KB
/
StringDenormalizer.php
File metadata and controls
71 lines (59 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
declare(strict_types=1);
namespace Flaksp\UserInputProcessor\Denormalizer;
use Flaksp\UserInputProcessor\ConstraintViolation\ConstraintViolationCollection;
use Flaksp\UserInputProcessor\ConstraintViolation\StringIsTooLong;
use Flaksp\UserInputProcessor\ConstraintViolation\StringIsTooShort;
use Flaksp\UserInputProcessor\ConstraintViolation\ValueDoesNotMatchRegex;
use Flaksp\UserInputProcessor\ConstraintViolation\WrongPropertyType;
use Flaksp\UserInputProcessor\Exception\ValidationError;
use Flaksp\UserInputProcessor\Pointer;
use LogicException;
final class StringDenormalizer
{
/**
* @throws ValidationError If $data has invalid parameters
*/
public function denormalize(
mixed $data,
Pointer $pointer,
int $minLength = null,
int $maxLength = null,
string $pattern = null,
): string {
if (null !== $minLength && null !== $maxLength && $minLength > $maxLength) {
throw new LogicException('Min length constraint can not be bigger than max length');
}
$violations = new ConstraintViolationCollection();
if (!\is_string($data)) {
$violations[] = WrongPropertyType::guessGivenType(
$pointer,
$data,
[WrongPropertyType::JSON_TYPE_STRING]
);
throw new ValidationError($violations);
}
if (null !== $minLength && mb_strlen($data) < $minLength) {
$violations[] = new StringIsTooShort(
$pointer,
$minLength
);
}
if (null !== $maxLength && mb_strlen($data) > $maxLength) {
$violations[] = new StringIsTooLong(
$pointer,
$maxLength
);
}
if (null !== $pattern && 1 !== preg_match($pattern, $data)) {
$violations[] = new ValueDoesNotMatchRegex(
$pointer,
$pattern
);
}
if ($violations->isNotEmpty()) {
throw new ValidationError($violations);
}
return $data;
}
}