Completed
Pull Request — master (#947)
by Andreas
01:49
created

ConnectionFactory::getDatabasePlatform()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 2
nc 2
nop 1
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 string[] */
23
    private $commentedTypes = [];
24
25
    /** @var bool */
26
    private $initialized = false;
27
28
    /**
29
     * @param mixed[][] $typesConfig
30
     */
31
    public function __construct(array $typesConfig)
32
    {
33
        $this->typesConfig = $typesConfig;
34
    }
35
36
    /**
37
     * Create a connection by name.
38
     *
39
     * @param mixed[]         $params
40
     * @param string[]|Type[] $mappingTypes
41
     *
42
     * @return Connection
43
     */
44
    public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = [])
45
    {
46
        if (! $this->initialized) {
47
            $this->initializeTypes();
48
        }
49
50
        $connection = DriverManager::getConnection($params, $config, $eventManager);
51
52
        if (! empty($mappingTypes)) {
53
            $platform = $this->getDatabasePlatform($connection);
54
            foreach ($mappingTypes as $dbType => $doctrineType) {
55
                $platform->registerDoctrineTypeMapping($dbType, $doctrineType);
0 ignored issues
show
Bug introduced by
It seems like $doctrineType defined by $doctrineType on line 54 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...
56
            }
57
        }
58
59
        $this->markTypesCommented($this->getDatabasePlatform($connection));
60
61
        return $connection;
62
    }
63
64
    /**
65
     * Try to get the database platform.
66
     *
67
     * This could fail if types should be registered to an predefined/unused connection
68
     * and the platform version is unknown.
69
     * For details have a look at DoctrineBundle issue #673.
70
     *
71
     * @return AbstractPlatform
72
     *
73
     * @throws DBALException
74
     */
75
    private function getDatabasePlatform(Connection $connection)
76
    {
77
        try {
78
            return $connection->getDatabasePlatform();
79
        } catch (DriverException $driverException) {
80
            throw new DBALException(
81
                'An exception occured while establishing a connection to figure out your platform version.' . PHP_EOL .
82
                "You can circumvent this by setting a 'server_version' configuration value" . PHP_EOL . PHP_EOL .
83
                'For further information have a look at:' . PHP_EOL .
84
                'https://github.com/doctrine/DoctrineBundle/issues/673',
85
                0,
86
                $driverException
87
            );
88
        }
89
    }
90
91
    /**
92
     * initialize the types
93
     */
94
    private function initializeTypes()
95
    {
96
        foreach ($this->typesConfig as $typeName => $typeConfig) {
97
            if (Type::hasType($typeName)) {
98
                Type::overrideType($typeName, $typeConfig['class']);
99
            } else {
100
                Type::addType($typeName, $typeConfig['class']);
101
            }
102
        }
103
104
        $this->initialized = true;
105
    }
106
107
    private function markTypesCommented(AbstractPlatform $platform) : void
108
    {
109
        if (! $this->initialized) {
110
            $this->initializeTypes();
111
        }
112
113
        foreach ($this->typesConfig as $typeName => $typeConfig) {
114
            $type                   = Type::getType($typeName);
115
            $requiresSQLCommentHint = $type->requiresSQLCommentHint($platform);
116
117
            // Attribute is missing, make sure a type that doesn't require a comment is marked as commented
118
            // This is deprecated behaviour that will be dropped in 2.0.
119
            if ($typeConfig['commented'] === null) {
120 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...
121
                    @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...
122
                        sprintf(
123
                            '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()."',
124
                            $typeName,
125
                            get_class($type)
126
                        ),
127
                        E_USER_DEPRECATED
128
                    );
129
130
                    $platform->markDoctrineTypeCommented($type);
131
                }
132
133
                continue;
134
            }
135
136
            // The following logic generates appropriate deprecation notices telling the user how to update their type configuration.
137
            if ($typeConfig['commented']) {
138 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...
139
                    @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...
140
                        sprintf(
141
                            '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()."',
142
                            $typeName,
143
                            get_class($type)
144
                        ),
145
                        E_USER_DEPRECATED
146
                    );
147
148
                    $platform->markDoctrineTypeCommented($type);
149
150
                    continue;
151
                }
152
153
                @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...
154
                    sprintf(
155
                        '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.',
156
                        $typeName
157
                    ),
158
                    E_USER_DEPRECATED
159
                );
160
161
                continue;
162
            }
163
164
            if ($requiresSQLCommentHint) {
165
                @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...
166
                    sprintf(
167
                        '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.',
168
                        $typeName,
169
                        get_class($type)
170
                    ),
171
                    E_USER_DEPRECATED
172
                );
173
            }
174
        }
175
    }
176
}
177