DbServiceFactory::createService()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 9.296
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Faulancer\Service\Factory;
4
5
use Faulancer\Service\DbService;
6
use ORM\DbConfig;
7
use ORM\EntityManager;
8
use Faulancer\Service\Config;
9
use Faulancer\ServiceLocator\FactoryInterface;
10
use Faulancer\ServiceLocator\ServiceLocatorInterface;
11
use ORM\Exception\InvalidConfiguration;
12
13
/**
14
 * Class DbServiceFactory | DbServiceFactory.php
15
 *
16
 * @package Faulancer\Service\Factory
17
 * @author  Florian Knapp <[email protected]>
18
 */
19
class DbServiceFactory implements FactoryInterface
20
{
21
22
    /**
23
     * Create an entity manager
24
     *
25
     * @param ServiceLocatorInterface $serviceLocator
26
     * @return DbService
27
     *
28
     * @throws InvalidConfiguration
29
     */
30
    public function createService(ServiceLocatorInterface $serviceLocator)
31
    {
32
        /** @var Config $config */
33
        $config = $serviceLocator->get(Config::class);
34
35
        $port = 3306;
36
        $type = $config->get('db:type') ?? 'config-key-not-found';
37
        $name = $config->get('db:name') ?? 'config-key-not-found';
38
        $user = $config->get('db:username') ?? 'config-key-not-found';
39
        $pass = $config->get('db:password') ?? 'config-key-not-found';
40
        $host = $config->get('db:host') ?? 'localhost';
41
42
        $attributes = [];
43
44
        if ($type === 'mysql') {
45
46
            $attributes = [
47
                \PDO::MYSQL_ATTR_INIT_COMMAND => "SET sql_mode ='ANSI_QUOTES', NAMES utf8",
48
                \PDO::ATTR_EMULATE_PREPARES   => false,
49
            ];
50
51
            $port = $config->get('db:port');
52
53
        }
54
55
        $dbConf = new DbConfig(
56
            $type,
57
            $name,
58
            $user,
59
            $pass,
60
            $host,
61
            $port,
62
            $attributes
63
        );
64
65
        $entityManager = new EntityManager([EntityManager::OPT_CONNECTION => $dbConf]);
66
67
        return new DbService($entityManager);
68
    }
69
70
}