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

ConnectionFactory   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 162
Duplicated Lines 16.05 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 5
dl 26
loc 162
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A createConnection() 0 21 5
A getDatabasePlatform() 0 15 2
A initializeTypes() 0 12 3
B markTypesCommented() 26 69 8

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
        if (! empty($this->typesConfig)) {
60
            $this->markTypesCommented($this->getDatabasePlatform($connection));
61
        }
62
63
        return $connection;
64
    }
65
66
    /**
67
     * Try to get the database platform.
68
     *
69
     * This could fail if types should be registered to an predefined/unused connection
70
     * and the platform version is unknown.
71
     * For details have a look at DoctrineBundle issue #673.
72
     *
73
     * @return AbstractPlatform
74
     *
75
     * @throws DBALException
76
     */
77
    private function getDatabasePlatform(Connection $connection)
78
    {
79
        try {
80
            return $connection->getDatabasePlatform();
81
        } catch (DriverException $driverException) {
82
            throw new DBALException(
83
                'An exception occured while establishing a connection to figure out your platform version.' . PHP_EOL .
84
                "You can circumvent this by setting a 'server_version' configuration value" . PHP_EOL . PHP_EOL .
85
                'For further information have a look at:' . PHP_EOL .
86
                'https://github.com/doctrine/DoctrineBundle/issues/673',
87
                0,
88
                $driverException
89
            );
90
        }
91
    }
92
93
    /**
94
     * initialize the types
95
     */
96
    private function initializeTypes()
97
    {
98
        foreach ($this->typesConfig as $typeName => $typeConfig) {
99
            if (Type::hasType($typeName)) {
100
                Type::overrideType($typeName, $typeConfig['class']);
101
            } else {
102
                Type::addType($typeName, $typeConfig['class']);
103
            }
104
        }
105
106
        $this->initialized = true;
107
    }
108
109
    private function markTypesCommented(AbstractPlatform $platform) : void
110
    {
111
        if (! $this->initialized) {
112
            $this->initializeTypes();
113
        }
114
115
        foreach ($this->typesConfig as $typeName => $typeConfig) {
116
            $type                   = Type::getType($typeName);
117
            $requiresSQLCommentHint = $type->requiresSQLCommentHint($platform);
118
119
            // Attribute is missing, make sure a type that doesn't require a comment is marked as commented
120
            // This is deprecated behaviour that will be dropped in 2.0.
121
            if ($typeConfig['commented'] === null) {
122 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...
123
                    @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...
124
                        sprintf(
125
                            '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()."',
126
                            $typeName,
127
                            get_class($type)
128
                        ),
129
                        E_USER_DEPRECATED
130
                    );
131
132
                    $platform->markDoctrineTypeCommented($type);
133
                }
134
135
                continue;
136
            }
137
138
            // The following logic generates appropriate deprecation notices telling the user how to update their type configuration.
139
            if ($typeConfig['commented']) {
140 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...
141
                    @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...
142
                        sprintf(
143
                            '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()."',
144
                            $typeName,
145
                            get_class($type)
146
                        ),
147
                        E_USER_DEPRECATED
148
                    );
149
150
                    $platform->markDoctrineTypeCommented($type);
151
152
                    continue;
153
                }
154
155
                @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...
156
                    sprintf(
157
                        '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.',
158
                        $typeName
159
                    ),
160
                    E_USER_DEPRECATED
161
                );
162
163
                continue;
164
            }
165
166
            if ($requiresSQLCommentHint) {
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
}
179