Passed
Pull Request — master (#3)
by Aleksei
11:35
created

ClosureContainer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 29
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A has() 0 10 3
A get() 0 6 2
A __construct() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Test\Support\Container;
6
7
use Closure;
8
use Psr\Container\ContainerInterface;
9
10
final class ClosureContainer implements ContainerInterface
11
{
12
    private Closure $factory;
13
    private array $definitions;
14
15
    public function __construct(Closure $factory, array $definitions = [])
16
    {
17
        $this->factory = $factory;
18
        $this->definitions = $definitions;
19
    }
20
21
    public function get($id)
22
    {
23
        if (!$this->has($id)) {
24
            $this->definitions[$id] = ($this->factory)($id);
25
        }
26
        return $this->definitions[$id];
27
    }
28
29
    public function has($id)
30
    {
31
        if (array_key_exists($id, $this->definitions)) {
32
            return true;
33
        }
34
        try {
35
            $this->get($id);
36
            return true;
37
        } catch (\Throwable $e) { // @phan-suppress-current-line PhanUnusedVariableCaughtException
38
            return false;
39
        }
40
    }
41
}
42