Passed
Push — main ( b94a81...f6c2a3 )
by Pranjal
02:29
created

DatabaseFactory::build()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
/*
3
 * This file is part of the Scrawler package.
4
 *
5
 * (c) Pranjal Pandey <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Scrawler\Arca\Factory;
12
13
use Doctrine\DBAL\Connection;
14
use Doctrine\DBAL\DriverManager;
15
use Scrawler\Arca\Config;
16
use Scrawler\Arca\Database;
17
use Scrawler\Arca\Manager\ModelManager;
18
19
class DatabaseFactory
20
{
21
    private \Di\Container $container;
22
23
    public function __construct(?\DI\ContainerBuilder $container = null)
24
    {
25
        if (is_null($container)) {
26
            $builder = new \DI\ContainerBuilder();
27
        } else {
28
            $builder = $container;
29
        }
30
        $this->container = $builder->build();
31
    }
32
33
    /**
34
     * Create a new Database instance.
35
     *
36
     * @param array<mixed> $connectionParams
37
     */
38
    public function build(array $connectionParams): Database
39
    {
40
        $this->wireContainer($connectionParams);
41
42
        return $this->container->make(Database::class);
43
    }
44
45
    /**
46
     * Create a new Database instance.
47
     *
48
     * @param array<mixed> $connectionParams
49
     */
50
    public function wireContainer(array $connectionParams): void
51
    {
52
        $this->createConfig($connectionParams['useUUID'] ?? false, $connectionParams['frozen'] ?? false);
53
        unset($connectionParams['use_uuid']);
54
        unset($connectionParams['frozen']);
55
        $this->createConnection($connectionParams);
56
        $this->createModelManager();
57
    }
58
59
    /**
60
     * Create a new connection.
61
     *
62
     * @param array<mixed> $connectionParams
63
     */
64
    private function createConnection(array $connectionParams): void
65
    {
66
        $this->container->set(Connection::class, function () use ($connectionParams): Connection {
67
            return DriverManager::getConnection($connectionParams);
68
        });
69
    }
70
71
    private function createModelManager(): void
72
    {
73
        $this->container->set(ModelManager::class, function (): ModelManager {
74
            return new ModelManager($this->container);
75
        });
76
    }
77
78
    private function createConfig(bool $useUUID = false, bool $frozen = false): void
79
    {
80
        $this->container->set(Config::class, function () use ($useUUID, $frozen): Config {
81
            return new Config($useUUID, $frozen);
82
        });
83
    }
84
}
85