Passed
Pull Request — master (#240)
by Wilmer
13:14
created

DatabaseFactory::createClass()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 3
b 0
f 0
nc 3
nop 1
dl 0
loc 19
rs 9.9332
ccs 0
cts 0
cp 0
crap 20
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
    private function __construct()
20
    {
21 2060
    }
22 2060
23
    /**
24
     * @throws InvalidConfigException
25
     */
26
    public static function initialize(ContainerInterface $container = null, array $definitions = []): void
27
    {
28
        self::$factory = new Factory($container, $definitions);
29
    }
30
31
    /**
32
     * Get `Connection` instance.
33 19
     *
34
     * @param array $config
35 19
     *
36
     * @throws CircularReferenceException|InvalidConfigException|NotFoundException|NotInstantiableException
37
     *
38
     * @return object
39
     */
40
    public static function connection(array $config): object
41 19
    {
42
        return self::createClass($config);
43
    }
44
45
    /**
46
     * Creates a Class defined by config passed.
47
     *
48
     * @param array $config parameters for creating a class.
49
     *
50
     * @throws CircularReferenceException|InvalidConfigException|NotFoundException|NotInstantiableException
51
     */
52
    private static function createClass(array $config): object
53
    {
54
        if (self::$factory === null) {
55
            throw new RuntimeException(
56
                'Database factory should be initialized with DatabaseFactory::initialize() call.'
57
            );
58
        }
59
60
        $instance = self::$factory->create($config);
61
62
        if (!($instance instanceof $config['class'])) {
63
            throw new RuntimeException(sprintf(
64
                'The "%s" is not an instance of the "%s".',
65
                (is_object($instance) ? get_class($instance) : gettype($instance)),
66
                $config['class'],
67
            ));
68
        }
69
70
        return $instance;
71
    }
72
}
73