Completed
Push — master ( d628a7...51001e )
by Kirill
03:08
created

CallbackDictionary::has()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\Reflection\Dictionary;
11
12
use Railt\Reflection\Contracts\Definition;
13
use Railt\Reflection\Contracts\Definition\TypeDefinition;
14
15
/**
16
 * Class CallbackDictionary
17
 */
18
class CallbackDictionary extends SimpleDictionary
19
{
20
    /**
21
     * @var array|\Closure[]
22
     */
23
    private $callbacks = [];
24
25
    /**
26
     * @param \Closure $then
27
     */
28
    public function onTypeNotFound(\Closure $then): void
29
    {
30
        $this->callbacks[] = $then;
31
    }
32
33
    /**
34
     * @param string $name
35
     * @param Definition|null $from
36
     * @return TypeDefinition
37
     * @throws \Railt\Reflection\Exception\TypeNotFoundException
38
     */
39
    public function get(string $name, Definition $from = null): TypeDefinition
40
    {
41
        $this->invoke($name, $from);
42
43
        return parent::get($name, $from);
44
    }
45
46
    /**
47
     * @param string $name
48
     * @param Definition|null $from
49
     */
50
    private function invoke(string $name, Definition $from = null): void
51
    {
52
        foreach ($this->callbacks as $callback) {
53
            if (! $this->has($name)) {
54
                $callback($name, $from, function (TypeDefinition $type): void {
55
                    $this->add($type);
56
                });
57
            }
58
        }
59
    }
60
61
    /**
62
     * @param string $name
63
     * @return null|TypeDefinition
64
     */
65
    public function find(string $name): ?TypeDefinition
66
    {
67
        $this->invoke($name);
68
69
        return parent::find($name);
70
    }
71
}
72