Completed
Pull Request — master (#16)
by Flo
07:29
created

DbServiceFactory::createService()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 39
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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