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
|
|
|
final class ConnectionFactory |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* @var ContainerInterface Container for creating a database connection instance. |
26
|
|
|
*/ |
27
|
|
|
private ContainerInterface $container; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var DefinitionInterface Definition for creating a database connection instance. |
31
|
|
|
*/ |
32
|
|
|
private DefinitionInterface $definition; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param ContainerInterface $container Container for creating a database connection instance. |
36
|
|
|
* @param mixed $config The configuration for creating a database connection instance. |
37
|
|
|
* For more information, see {@see Normalizer::normalize()}. |
38
|
|
|
* |
39
|
|
|
* @throws InvalidConfigException If the configuration is invalid. |
40
|
|
|
*/ |
41
|
|
|
public function __construct(ContainerInterface $container, $config) |
42
|
|
|
{ |
43
|
|
|
$this->container = $container; |
44
|
|
|
$this->definition = Normalizer::normalize($config); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Creates a database connection instance. |
49
|
|
|
* |
50
|
|
|
* @throws RuntimeException If the created object is not an instance of the `ConnectionInterface`. |
51
|
|
|
* |
52
|
|
|
* @return ConnectionInterface The database connection instance. |
53
|
|
|
* |
54
|
|
|
* @psalm-suppress RedundantConditionGivenDocblockType |
55
|
|
|
* @psalm-suppress DocblockTypeContradiction |
56
|
|
|
*/ |
57
|
|
|
public function create(): ConnectionInterface |
58
|
|
|
{ |
59
|
|
|
$сonnection = $this->definition->resolve($this->container); |
60
|
|
|
|
61
|
|
|
if (!($сonnection instanceof ConnectionInterface)) { |
62
|
|
|
throw new RuntimeException(sprintf( |
63
|
|
|
'The "%s" is not an instance of the "Yiisoft\Db\Connection\ConnectionInterface".', |
64
|
|
|
(is_object($сonnection) ? get_class($сonnection) : gettype($сonnection)) |
65
|
|
|
)); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $сonnection; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|