Passed
Pull Request — master (#240)
by Wilmer
15:05
created

DatabaseFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 60%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 8
dl 0
loc 42
ccs 6
cts 10
cp 0.6
rs 10
c 2
b 0
f 0
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 0 3 1
A connection() 0 3 1
A createClass() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Factory;
6
7
use Psr\Container\ContainerInterface;
8
use RuntimeException;
9
use Yiisoft\Definitions\Exception\CircularReferenceException;
10
use Yiisoft\Definitions\Exception\InvalidConfigException;
11
use Yiisoft\Definitions\Exception\NotFoundException;
12
use Yiisoft\Definitions\Exception\NotInstantiableException;
13
use Yiisoft\Factory\Factory;
14
15
final class DatabaseFactory
16
{
17
    private static ?Factory $factory = null;
18
19 2060
    /**
20
     * @throws InvalidConfigException
21 2060
     */
22 2060
    public static function initialize(ContainerInterface $container = null, array $definitions = []): void
23
    {
24
        self::$factory = new Factory($container, $definitions);
25
    }
26
27
    /**
28
     * Get `Connection` instance.
29
     *
30
     * @param array $config
31
     *
32
     * @throws CircularReferenceException|InvalidConfigException|NotFoundException|NotInstantiableException
33 19
     *
34
     * @return object
35 19
     */
36
    public static function connection(array $config): object
37
    {
38
        return self::createClass($config);
39
    }
40
41 19
    /**
42
     * Creates a Class defined by config passed.
43
     *
44
     * @param array|string $config parameters for creating a class.
45
     *
46
     * @throws CircularReferenceException|InvalidConfigException|NotFoundException|NotInstantiableException
47
     */
48
    private static function createClass($config): object
49
    {
50
        if (self::$factory === null) {
51
            throw new RuntimeException(
52
                'Database factory should be initialized with DatabaseFactory::initialize() call.'
53
            );
54
        }
55
56
        return self::$factory->create($config);
57
    }
58
}
59