Completed
Push — master ( f5c10e...5c79bb )
by Andreas
02:13
created

ConnectionFactory::createConnection()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.2728
c 0
b 0
f 0
cc 5
nc 8
nop 4
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle;
4
5
use Doctrine\Common\EventManager;
6
use Doctrine\DBAL\Configuration;
7
use Doctrine\DBAL\Connection;
8
use Doctrine\DBAL\DBALException;
9
use Doctrine\DBAL\DriverManager;
10
use Doctrine\DBAL\Exception\DriverException;
11
use Doctrine\DBAL\Platforms\AbstractPlatform;
12
use Doctrine\DBAL\Types\Type;
13
use const E_USER_DEPRECATED;
14
use function get_class;
15
use function trigger_error;
16
17
class ConnectionFactory
18
{
19
    /** @var mixed[][] */
20
    private $typesConfig = [];
21
22
    /** @var bool */
23
    private $initialized = false;
24
25
    /**
26
     * @param mixed[][] $typesConfig
27
     */
28
    public function __construct(array $typesConfig)
29
    {
30
        $this->typesConfig = $typesConfig;
31
    }
32
33
    /**
34
     * Create a connection by name.
35
     *
36
     * @param mixed[]         $params
37
     * @param string[]|Type[] $mappingTypes
38
     *
39
     * @return Connection
40
     */
41
    public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = [])
42
    {
43
        if (! $this->initialized) {
44
            $this->initializeTypes();
45
        }
46
47
        $connection = DriverManager::getConnection($params, $config, $eventManager);
48
49
        if (! empty($mappingTypes)) {
50
            $platform = $this->getDatabasePlatform($connection);
51
            foreach ($mappingTypes as $dbType => $doctrineType) {
52
                $platform->registerDoctrineTypeMapping($dbType, $doctrineType);
0 ignored issues
show
Bug introduced by
It seems like $doctrineType defined by $doctrineType on line 51 can also be of type object<Doctrine\DBAL\Types\Type>; however, Doctrine\DBAL\Platforms\...erDoctrineTypeMapping() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
53
            }
54
        }
55
56
        if (! empty($this->typesConfig)) {
57
            $this->markTypesCommented($this->getDatabasePlatform($connection));
58
        }
59
60
        return $connection;
61
    }
62
63
    /**
64
     * Try to get the database platform.
65
     *
66
     * This could fail if types should be registered to an predefined/unused connection
67
     * and the platform version is unknown.
68
     * For details have a look at DoctrineBundle issue #673.
69
     *
70
     * @return AbstractPlatform
71
     *
72
     * @throws DBALException
73
     */
74
    private function getDatabasePlatform(Connection $connection)
75
    {
76
        try {
77
            return $connection->getDatabasePlatform();
78
        } catch (DriverException $driverException) {
79
            throw new DBALException(
80
                'An exception occured while establishing a connection to figure out your platform version.' . PHP_EOL .
81
                "You can circumvent this by setting a 'server_version' configuration value" . PHP_EOL . PHP_EOL .
82
                'For further information have a look at:' . PHP_EOL .
83
                'https://github.com/doctrine/DoctrineBundle/issues/673',
84
                0,
85
                $driverException
86
            );
87
        }
88
    }
89
90
    /**
91
     * initialize the types
92
     */
93
    private function initializeTypes()
94
    {
95
        foreach ($this->typesConfig as $typeName => $typeConfig) {
96
            if (Type::hasType($typeName)) {
97
                Type::overrideType($typeName, $typeConfig['class']);
98
            } else {
99
                Type::addType($typeName, $typeConfig['class']);
100
            }
101
        }
102
103
        $this->initialized = true;
104
    }
105
106
    private function markTypesCommented(AbstractPlatform $platform) : void
107
    {
108
        foreach ($this->typesConfig as $typeName => $typeConfig) {
109
            $type                   = Type::getType($typeName);
110
            $requiresSQLCommentHint = $type->requiresSQLCommentHint($platform);
111
112
            // Attribute is missing, make sure a type that doesn't require a comment is marked as commented
113
            // This is deprecated behaviour that will be dropped in 2.0.
114
            if ($typeConfig['commented'] === null) {
115 View Code Duplication
                if (! $requiresSQLCommentHint) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
116
                    @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
117
                        sprintf(
118
                            'The type "%s" was implicitly marked as commented due to the configuration. This is deprecated and will be removed in DoctrineBundle 2.0. Either set the "commented" attribute in the configuration to "false" or mark the type as commented in "%s::requiresSQLCommentHint()."',
119
                            $typeName,
120
                            get_class($type)
121
                        ),
122
                        E_USER_DEPRECATED
123
                    );
124
125
                    $platform->markDoctrineTypeCommented($type);
126
                }
127
128
                continue;
129
            }
130
131
            // The following logic generates appropriate deprecation notices telling the user how to update their type configuration.
132
            if ($typeConfig['commented']) {
133 View Code Duplication
                if (! $requiresSQLCommentHint) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
                    @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
135
                        sprintf(
136
                            'The type "%s" was marked as commented in its configuration but not in the type itself. This is deprecated and will be removed in DoctrineBundle 2.0. Please update the return value of "%s::requiresSQLCommentHint()."',
137
                            $typeName,
138
                            get_class($type)
139
                        ),
140
                        E_USER_DEPRECATED
141
                    );
142
143
                    $platform->markDoctrineTypeCommented($type);
144
145
                    continue;
146
                }
147
148
                @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
149
                    sprintf(
150
                        'The type "%s" was explicitly marked as commented in its configuration. This is no longer necessary and will be removed in DoctrineBundle 2.0. Please remove the "commented" attribute from the type configuration.',
151
                        $typeName
152
                    ),
153
                    E_USER_DEPRECATED
154
                );
155
156
                continue;
157
            }
158
159
            if (! $requiresSQLCommentHint) {
160
                continue;
161
            }
162
163
            @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
164
                sprintf(
165
                    'The type "%s" was marked as uncommented in its configuration but commented in the type itself. This is deprecated and will be removed in DoctrineBundle 2.0. Please update the return value of "%s::requiresSQLCommentHint()" or remove the "commented" attribute from the type configuration.',
166
                    $typeName,
167
                    get_class($type)
168
                ),
169
                E_USER_DEPRECATED
170
            );
171
        }
172
    }
173
}
174