Passed
Pull Request — master (#42)
by Aleksei
15:25
created

DbalFactory::prepareLogger()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Factory;
6
7
use InvalidArgumentException;
8
use Psr\Container\ContainerInterface;
9
use Psr\Log\LoggerInterface;
10
use Spiral\Database\Config\DatabaseConfig;
11
use Spiral\Database\DatabaseManager;
12
use Spiral\Database\Driver\Driver;
13
use Yiisoft\Aliases\Aliases;
14
15
final class DbalFactory
16
{
17
    /** @var array|DatabaseConfig */
18
    private $dbalConfig;
19
    /** @var null|string|LoggerInterface */
20
    private $logger = null;
21
    private ?ContainerInterface $container = null;
22
23
    /**
24
     * @param array|DatabaseConfig $config
25
     */
26
    public function __construct($config)
27
    {
28
        if (is_array($config) && array_key_exists('query-logger', $config)) {
29
            $this->logger = $config['query-logger'];
30
            unset($config['query-logger']);
31
        }
32
        $this->dbalConfig = $config;
33
    }
34
35
    public function __invoke(ContainerInterface $container)
36
    {
37
        $this->container = $container;
38
        $conf = $this->prepareConfig($this->dbalConfig);
39
        $dbal = new DatabaseManager($conf);
40
41
        if ($this->logger !== null) {
42
            $logger = $this->prepareLogger($this->logger);
43
            $dbal->setLogger($logger);
44
            /** Remove when issue is resolved {@link https://github.com/cycle/orm/issues/60} */
45
            $drivers = $dbal->getDrivers();
46
            array_walk($drivers, static fn (Driver $driver) => $driver->setLogger($logger));
47
        }
48
49
        return $dbal;
50
    }
51
52
    /**
53
     * @param string|LoggerInterface $logger
54
     * @return LoggerInterface
55
     * @throws InvalidArgumentException
56
     */
57
    private function prepareLogger($logger): LoggerInterface
58
    {
59
        if ($logger instanceof LoggerInterface) {
60
            return $logger;
61
        }
62
        if (is_string($logger)) {
0 ignored issues
show
introduced by
The condition is_string($logger) is always true.
Loading history...
63
            return $this->container->get($logger);
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

63
            return $this->container->/** @scrutinizer ignore-call */ get($logger);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
64
        }
65
        throw new InvalidArgumentException('Invalid logger.');
66
    }
67
68
    /**
69
     * @param array|DatabaseConfig $config
70
     * @return DatabaseConfig
71
     */
72
    private function prepareConfig($config): DatabaseConfig
73
    {
74
        if ($config instanceof DatabaseConfig) {
75
            return $config;
76
        }
77
        if (isset($config['connections'])) {
78
            // prepare connections
79
            foreach ($config['connections'] as &$connection) {
80
                $connection = $this->prepareConnection($connection);
81
            }
82
        }
83
84
        return new DatabaseConfig($config);
85
    }
86
87
    private function prepareConnection(array $connection): array
88
    {
89
        // if connection option contain alias in path
90
        if (isset($connection['connection']) && preg_match('/^(?<proto>\w+:)?@/', $connection['connection'], $m)) {
91
            $proto = $m['proto'];
92
            $path = $this->getAlias(substr($connection['connection'], strlen($proto)));
93
            $connection['connection'] = $proto . $path;
94
        }
95
        return $connection;
96
    }
97
98
    private function getAlias(string $alias): string
99
    {
100
        return $this->container->get(Aliases::class)->get($alias);
101
    }
102
}
103