Multiton   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
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 37
ccs 10
cts 10
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
    protected Factory $factory;
22
    /** @var array<string, IStorage> */
23
    protected array $instances = [];
24
25 4
    public function __construct(?Interfaces\IStTranslations $lang = null)
26
    {
27 4
        $this->setStLang($lang);
28 4
        $this->factory = new Factory($this->getStLang());
29
    }
30
31
    /**
32
     * @param array<string|int, string|int|float|object|bool|array<string|int|float|object>>|string|object|int|bool|null $params
33
     * @param string|null $alias
34
     * @throws StorageException
35
     * @return IStorage
36
     */
37 3
    public function lookup($params, ?string $alias = null): IStorage
38
    {
39 3
        $key = $alias ?? $this->paramsToKey($params);
40 3
        if (!isset($this->instances[$key])) {
41 3
            $this->instances[$key] = $this->factory->getStorage($params);
42
        }
43
44 3
        return $this->instances[$key];
45
    }
46
47
    /**
48
     * @param array<string|int, string|int|float|object|bool|array<string|int|float|object>>|string|object|int|bool|null $params
49
     * @return string
50
     */
51 1
    public function paramsToKey($params): string
52
    {
53 1
        return md5(base64_encode(serialize($params)));
54
    }
55
}
56