Completed
Pull Request — master (#947)
by Andreas
01:50
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
        if (! $this->initialized) {
109
            $this->initializeTypes();
110
        }
111
112
        foreach ($this->typesConfig as $typeName => $typeConfig) {
113
            $type                   = Type::getType($typeName);
114
            $requiresSQLCommentHint = $type->requiresSQLCommentHint($platform);
115
116
            // Attribute is missing, make sure a type that doesn't require a comment is marked as commented
117
            // This is deprecated behaviour that will be dropped in 2.0.
118
            if ($typeConfig['commented'] === null) {
119 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...
120
                    @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...
121
                        sprintf(
122
                            '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()."',
123
                            $typeName,
124
                            get_class($type)
125
                        ),
126
                        E_USER_DEPRECATED
127
                    );
128
129
                    $platform->markDoctrineTypeCommented($type);
130
                }
131
132
                continue;
133
            }
134
135
            // The following logic generates appropriate deprecation notices telling the user how to update their type configuration.
136
            if ($typeConfig['commented']) {
137 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...
138
                    @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...
139
                        sprintf(
140
                            '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()."',
141
                            $typeName,
142
                            get_class($type)
143
                        ),
144
                        E_USER_DEPRECATED
145
                    );
146
147
                    $platform->markDoctrineTypeCommented($type);
148
149
                    continue;
150
                }
151
152
                @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...
153
                    sprintf(
154
                        '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.',
155
                        $typeName
156
                    ),
157
                    E_USER_DEPRECATED
158
                );
159
160
                continue;
161
            }
162
163
            if (! $requiresSQLCommentHint) {
164
                continue;
165
            }
166
167
            @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...
168
                sprintf(
169
                    'Disabling type commenting for the commented type "%s" is deprecated and will be removed in DoctrineBundle 2.0. Please remove the "commented" attribute from the configuration and instead disable type commenting in "%s::requiresSQLCommentHint()" if you no longer want the type to be commented.',
170
                    $typeName,
171
                    get_class($type)
172
                ),
173
                E_USER_DEPRECATED
174
            );
175
        }
176
    }
177
}
178