WithValidatedProperties   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 12
c 1
b 0
f 0
dl 0
loc 40
ccs 15
cts 15
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
A __set() 0 12 3
A __get() 0 3 1
A __isset() 0 3 2
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