Passed
Pull Request — master (#240)
by Wilmer
12:51
created

DatabaseFactory::connection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 1
cp 0
crap 2
rs 10
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\Db\Cache\SchemaCache;
10
use Yiisoft\Definitions\Exception\CircularReferenceException;
11
use Yiisoft\Definitions\Exception\InvalidConfigException;
12
use Yiisoft\Definitions\Exception\NotFoundException;
13
use Yiisoft\Definitions\Exception\NotInstantiableException;
14
use Yiisoft\Factory\Factory;
15
16
final class DatabaseFactory
17
{
18
    private static ?Factory $factory = null;
19 2060
20
    /**
21 2060
     * @throws InvalidConfigException
22 2060
     */
23
    public static function initialize(ContainerInterface $container = null, array $definitions = []): void
24
    {
25
        self::$factory = new Factory($container, $definitions);
26
    }
27
28
    /**
29
     * Get `SchemaCache` instance.
30
     *
31
     * @param array $config
32
     *
33 19
     * @throws CircularReferenceException|InvalidConfigException|NotFoundException|NotInstantiableException
34
     *
35 19
     * @return object
36
     */
37
    public static function connection(array $config): object
38
    {
39
        return self::createClass($config);
40
    }
41 19
42
    /**
43
     * Get `SchemaCache` instance.
44
     *
45
     * @throws CircularReferenceException|InvalidConfigException|NotFoundException|NotInstantiableException
46
     *
47
     * @return object
48
     */
49
    public static function schemaCache(): object
50
    {
51
        return self::createClass(SchemaCache::class);
52
    }
53
54
    /**
55
     * Creates a Class defined by config passed.
56
     *
57
     * @param array|string $config parameters for creating a class.
58
     *
59
     * @throws CircularReferenceException|InvalidConfigException|NotFoundException|NotInstantiableException
60
     */
61
    private static function createClass($config): object
62
    {
63
        if (self::$factory === null) {
64
            throw new RuntimeException(
65
                'Database factory should be initialized with DatabaseFactory::initialize() call.'
66
            );
67
        }
68
69
        return self::$factory->create($config);
70
    }
71
}
72