Passed
Push — master ( 96eda9...4e4eee )
by Petr
07:51
created

Multiton   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 11
c 1
b 0
f 0
dl 0
loc 38
ccs 11
cts 11
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A paramsToKey() 0 3 1
A __construct() 0 4 1
A lookup() 0 8 2
1
<?php
2
3
namespace kalanis\kw_storage\Access;
4
5
6
use kalanis\kw_storage\Interfaces;
7
use kalanis\kw_storage\Interfaces\IStorage;
8
use kalanis\kw_storage\StorageException;
9
use kalanis\kw_storage\Traits\TLang;
10
11
12
/**
13
 * Class Multiton
14
 * @package kalanis\kw_storage\Access
15
 * Multiple storages via one access point; just use different params to get correct one
16
 */
17
class Multiton
18
{
19
    use TLang;
20
21
    /** @var Factory */
22
    protected $factory = null;
23
    /** @var array<string, IStorage> */
24
    protected $instances = [];
25
26 3
    public function __construct(?Interfaces\IStTranslations $lang = null)
27
    {
28 3
        $this->setStLang($lang);
29 3
        $this->factory = new Factory($this->getStLang());
30 3
    }
31
32
    /**
33
     * @param array<string|int, string|int|float|object|bool|array<string|int|float|object>>|string|object|int|bool|null $params
34
     * @param string|null $alias
35
     * @throws StorageException
36
     * @return IStorage
37
     */
38 2
    public function lookup($params, ?string $alias = null): IStorage
39
    {
40 2
        $key = $alias ?? $this->paramsToKey($params);
41 2
        if (!isset($this->instances[$key])) {
42 2
            $this->instances[$key] = $this->factory->getStorage($params);
43
        }
44
45 2
        return $this->instances[$key];
46
    }
47
48
    /**
49
     * @param array<string|int, string|int|float|object|bool|array<string|int|float|object>>|string|object|int|bool|null $params
50
     * @return string
51
     */
52 1
    public function paramsToKey($params): string
53
    {
54 1
        return md5(base64_encode(serialize($params)));
55
    }
56
}
57