|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Part of the Fusion.Collection package. |
|
5
|
|
|
* |
|
6
|
|
|
* @license MIT |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
declare(strict_types=1); |
|
10
|
|
|
|
|
11
|
|
|
namespace Fusion\Collection; |
|
12
|
|
|
|
|
13
|
|
|
use Fusion\Collection\Contracts\AbstractCollection; |
|
14
|
|
|
use Fusion\Collection\Contracts\CollectionValidationInterface; |
|
15
|
|
|
use Fusion\Collection\Exceptions\CollectionException; |
|
16
|
|
|
|
|
17
|
|
|
class CollectionValidator implements CollectionValidationInterface |
|
18
|
|
|
{ |
|
19
|
1 |
|
public function validateNonNullValue($value): void |
|
20
|
|
|
{ |
|
21
|
1 |
|
if ($value === null) |
|
22
|
|
|
{ |
|
23
|
1 |
|
throw new CollectionException('Collection operations will not accept null values.'); |
|
24
|
|
|
} |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
1 |
|
public function validateOffsetExists($offset, AbstractCollection $collection): void |
|
28
|
|
|
{ |
|
29
|
1 |
|
if ($collection->offsetExists($offset) === false) |
|
30
|
|
|
{ |
|
31
|
1 |
|
throw new CollectionException("The key or index '$offset' does not exist in the collection."); |
|
32
|
|
|
} |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
1 |
|
public function validateIntValue($value): void |
|
36
|
|
|
{ |
|
37
|
1 |
|
if (is_int($value) === false) |
|
38
|
|
|
{ |
|
39
|
1 |
|
$message = sprintf( |
|
40
|
1 |
|
'Collection offset type must be an integer. %s given.', |
|
41
|
1 |
|
gettype($value) |
|
42
|
|
|
); |
|
43
|
|
|
|
|
44
|
1 |
|
throw new CollectionException($message); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
1 |
|
public function validateStringValue($value): void |
|
49
|
|
|
{ |
|
50
|
1 |
|
if (is_string($value) === false) |
|
51
|
|
|
{ |
|
52
|
1 |
|
throw new CollectionException('Offset to access must be a string.'); |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
1 |
|
public function validateNonEmptyAcceptedType(string $acceptedType): void |
|
57
|
|
|
{ |
|
58
|
1 |
|
if ($acceptedType == '') |
|
59
|
|
|
{ |
|
60
|
1 |
|
throw new CollectionException('Accepted type string cannot be empty.'); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
1 |
|
public function validateValueIsAcceptedType($value, string $acceptedType): void |
|
65
|
|
|
{ |
|
66
|
1 |
|
if ($this->notAcceptedType($value, $acceptedType)) |
|
67
|
|
|
{ |
|
68
|
1 |
|
$message = sprintf( |
|
69
|
1 |
|
'Unable to modify collection. Only instances of type "%s" are allowed. Type "%s" given.', |
|
70
|
1 |
|
$acceptedType, |
|
71
|
1 |
|
is_object($value) ? get_class($value) : gettype($value) |
|
72
|
|
|
); |
|
73
|
|
|
|
|
74
|
1 |
|
throw new CollectionException($message); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
1 |
|
private function notAcceptedType($value, string $acceptedType) |
|
79
|
|
|
{ |
|
80
|
1 |
|
return ($value instanceof $acceptedType) === false; |
|
81
|
|
|
} |
|
82
|
|
|
} |