This repository was archived by the owner on Apr 26, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathValidateArrayClass.php
More file actions
53 lines (43 loc) · 1.37 KB
/
Copy pathValidateArrayClass.php
File metadata and controls
53 lines (43 loc) · 1.37 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
<?php
declare(strict_types=1);
namespace Hsnfirdaus\ClassValidator\Attribute;
use Attribute;
use Hsnfirdaus\ClassValidator\Error\PropertyError;
use Hsnfirdaus\ClassValidator\Validator;
use ReflectionProperty;
use Throwable;
use function is_array;
/**
* Validate nested array of class
*/
#[Attribute(Attribute::TARGET_PROPERTY)]
class ValidateArrayClass implements ValidationAttribute
{
/** @param string|null $type Class type namespace (example: MyClass::class) **/
public function __construct(
private string|null $type = null,
) {
}
public function validateProperty(ReflectionProperty $property, object $object): void
{
$value = $property->getValue($object);
if (! is_array($value)) {
throw new PropertyError($property, 'VALIDATE_ARRAY_CLASS_INVALID');
}
$idx = 0;
foreach ($value as $item) {
if (isset($this->type)) {
if (! $item instanceof $this->type) {
throw new PropertyError($property, 'VALIDATE_ARRAY_CLASS_INVALID');
}
}
try {
Validator::validate($item);
} catch (Throwable $th) {
$msg = $th->getMessage();
throw new PropertyError($property, 'VALIDATE_ARRAY_CLASS_INDEX_INVALID', $idx, $msg);
}
$idx++;
}
}
}