Passed
Pull Request — master (#210)
by Evgeniy
11:38 queued 09:41
created

ConnectionFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 1
b 0
f 0
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\Connection\ConnectionInterface;
10
use Yiisoft\Factory\Definitions\DefinitionInterface;
11
use Yiisoft\Factory\Definitions\Normalizer;
12
use Yiisoft\Factory\Exceptions\InvalidConfigException;
13
14
use function is_object;
15
use function get_class;
16
use function gettype;
17
use function sprintf;
18
19
/**
20
 * ConnectionFactory creates a database connection instance.
21
 *
22
 * Provides lazy loading of the "Yiisoft\Db\Connection\ConnectionInterface" instance
23
 * to prevent a circular reference to the connection when building container definitions.
24
 */
25
final class ConnectionFactory
26
{
27
    /**
28
     * @var ContainerInterface Container for creating a database connection instance.
29
     */
30
    private ContainerInterface $container;
31
32
    /**
33
     * @var DefinitionInterface Definition for creating a database connection instance.
34
     */
35
    private DefinitionInterface $definition;
36
37
    /**
38
     * @param ContainerInterface $container Container for creating a database connection instance.
39
     * @param mixed $config The configuration for creating a database connection instance.
40
     * For more information, see {@see Normalizer::normalize()}.
41
     *
42
     * @throws InvalidConfigException If the configuration is invalid.
43
     */
44
    public function __construct(ContainerInterface $container, $config)
45
    {
46
        $this->container = $container;
47
        $this->definition = Normalizer::normalize($config);
48
    }
49
50
    /**
51
     * Creates a database connection instance.
52
     *
53
     * @throws RuntimeException If the created object is not an instance of the `ConnectionInterface`.
54
     *
55
     * @return ConnectionInterface The database connection instance.
56
     *
57
     * @psalm-suppress RedundantConditionGivenDocblockType
58
     * @psalm-suppress DocblockTypeContradiction
59
     */
60
    public function create(): ConnectionInterface
61
    {
62
        $сonnection = $this->definition->resolve($this->container);
63
64
        if (!($сonnection instanceof ConnectionInterface)) {
65
            throw new RuntimeException(sprintf(
66
                'The "%s" is not an instance of the "Yiisoft\Db\Connection\ConnectionInterface".',
67
                (is_object($сonnection) ? get_class($сonnection) : gettype($сonnection))
68
            ));
69
        }
70
71
        return $сonnection;
72
    }
73
}
74