Completed
Push — master ( b3f30b...261de6 )
by Dominik
02:25
created

LazyModelReference::jsonSerialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Model\Reference;
6
7
use Chubbyphp\Model\ModelInterface;
8
9
final class LazyModelReference implements ModelReferenceInterface
10
{
11
    /**
12
     * @var \Closure
13
     */
14
    private $resolver;
15
16
    /**
17
     * @var ModelInterface|null
18
     */
19
    private $initialModel;
20
21
    /**
22
     * @var ModelInterface|null
23
     */
24
    private $model;
25
26
    /**
27
     * @param \Closure $resolver
28
     */
29
    public function __construct(\Closure $resolver)
30
    {
31
        $this->resolver = $resolver;
32
    }
33
34
    private function resolveModel()
35
    {
36
        if (null === $this->resolver) {
37
            return;
38
        }
39
40
        $resolver = $this->resolver;
41
42
        $this->resolver = null;
43
44
        $this->model = $resolver();
45
        $this->initialModel = $this->model;
46
    }
47
48
    /**
49
     * @param ModelInterface|null $model
50
     * @return ModelReferenceInterface
51
     */
52
    public function setModel(ModelInterface $model = null): ModelReferenceInterface
53
    {
54
        $this->resolveModel();
55
56
        $this->model = $model;
57
58
        return $this;
59
    }
60
61
    /**
62
     * @return ModelInterface|null
63
     */
64
    public function getModel()
65
    {
66
        $this->resolveModel();
67
68
        return $this->model;
69
    }
70
71
    /**
72
     * @return null|string
73
     */
74
    public function getId()
75
    {
76
        $this->resolveModel();
77
78
        if (null === $this->model) {
79
            return null;
80
        }
81
82
        return $this->model->getId();
83
    }
84
85
    /**
86
     * @return ModelInterface|null
87
     */
88
    public function getInitialModel()
89
    {
90
        $this->resolveModel();
91
92
        return $this->initialModel;
93
    }
94
95
    /**
96
     * @return array|null
97
     */
98
    public function jsonSerialize()
99
    {
100
        $this->resolveModel();
101
102
        if (null === $this->model) {
103
            return null;
104
        }
105
106
        return $this->model->jsonSerialize();
107
    }
108
}
109