Passed
Push — master ( 2635eb...63381f )
by Sébastien
04:45
created

LazyChoice::build()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 10
cc 3
nc 3
nop 0
crap 3
1
<?php
2
3
namespace Bdf\Form\Choice;
4
5
/**
6
 * Proxy choice using a callback for generate the choices array
7
 *
8
 * @template T
9
 * @implements ChoiceInterface<T>
10
 *
11
 * @final
12
 */
13
/*final*/ class LazyChoice implements ChoiceInterface
14
{
15
    /**
16
     * The lazy callback with returns choices
17
     *
18
     * @var callable():(T[]|ChoiceInterface<T>)
19
     */
20
    private $resolver;
21
22
    /**
23
     * The choice object
24
     *
25
     * @var ChoiceInterface<T>|null
26
     */
27
    private $choices;
28
29
    /**
30
     * LazyChoice constructor.
31
     *
32
     * @param callable():(T[]|ChoiceInterface<T>) $resolver
33
     */
34 2
    public function __construct(callable $resolver)
35
    {
36 2
        $this->resolver = $resolver;
37 2
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 2
    public function values(): array
43
    {
44 2
        return $this->build()->values();
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 1
    public function view(?callable $configuration = null): array
51
    {
52 1
        return $this->build()->view($configuration);
53
    }
54
55
    /**
56
     * Resolve the lazy choice list
57
     */
58 2
    private function build(): ChoiceInterface
59
    {
60 2
        if ($this->choices !== null) {
61 1
            return $this->choices;
62
        }
63
64 2
        $choices = ($this->resolver)();
65
66 2
        if (!$choices instanceof ChoiceInterface) {
67 1
            $choices = new ArrayChoice((array) $choices);
68
        }
69
70 2
        return $this->choices = $choices;
71
    }
72
}
73