Passed
Pull Request — master (#240)
by Wilmer
19:20 queued 06:41
created

DatabaseFactory::connection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
ccs 1
cts 1
cp 1
crap 1
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