|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace PrinsFrank\PhpStrictModels; |
|
5
|
|
|
|
|
6
|
|
|
use PrinsFrank\PhpStrictModels\Exception\InvalidModelException; |
|
7
|
|
|
use PrinsFrank\PhpStrictModels\Exception\NonExistingPropertyException; |
|
8
|
|
|
use PrinsFrank\PhpStrictModels\Exception\ValidationException; |
|
9
|
|
|
use PrinsFrank\PhpStrictModels\Validation\ModelValidator; |
|
10
|
|
|
use PrinsFrank\PhpStrictModels\Validation\PropertyValidator; |
|
11
|
|
|
use ReflectionClass; |
|
12
|
|
|
use ReflectionException; |
|
13
|
|
|
|
|
14
|
|
|
trait WithValidatedProperties |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @throws InvalidModelException |
|
18
|
|
|
*/ |
|
19
|
4 |
|
public function __construct() |
|
20
|
|
|
{ |
|
21
|
4 |
|
$validationResult = ModelValidator::validateModel(new ReflectionClass(static::class)); |
|
22
|
4 |
|
if ($validationResult->passes() === false) { |
|
23
|
2 |
|
throw new InvalidModelException('Model is invalid: "' . implode('","', $validationResult->getErrors()) . '"'); |
|
24
|
|
|
} |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
1 |
|
public function __isset(string $name): bool |
|
28
|
|
|
{ |
|
29
|
1 |
|
return property_exists($this, $name) && isset($this->{$name}); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @throws NonExistingPropertyException |
|
34
|
|
|
* @throws ReflectionException |
|
35
|
|
|
* @throws ValidationException |
|
36
|
|
|
*/ |
|
37
|
3 |
|
public function __set(string $name, mixed $value): void |
|
38
|
|
|
{ |
|
39
|
3 |
|
if (property_exists($this, $name) === false) { |
|
40
|
1 |
|
throw new NonExistingPropertyException('Property with name "' . $name . '" does not exist'); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
2 |
|
$validationResult = PropertyValidator::validateProperty((new ReflectionClass(static::class))->getProperty($name), $value); |
|
44
|
2 |
|
if ($validationResult->passes() === false) { |
|
45
|
1 |
|
throw new ValidationException('Value "' . $value . '" for property "' . $name . '" is invalid: "' . implode('","', $validationResult->getErrors()) . '"'); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
1 |
|
$this->{$name} = $value; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
1 |
|
public function __get(string $name): mixed |
|
52
|
|
|
{ |
|
53
|
1 |
|
return $this->{$name}; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|