Failed Conditions
Pull Request — develop (#3348)
by Sergei
10:40
created

AbstractPostgreSQLDriver::convertException()   C

Complexity

Conditions 15
Paths 15

Size

Total Lines 50
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 15.0083

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 50
ccs 29
cts 30
cp 0.9667
rs 5.9166
c 0
b 0
f 0
cc 15
nc 15
nop 2
crap 15.0083

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Driver;
6
7
use Doctrine\DBAL\Connection;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Doctrine\DBAL\Driver\Connection. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
use Doctrine\DBAL\DBALException;
9
use Doctrine\DBAL\Driver;
10
use Doctrine\DBAL\Driver\DriverException as DriverExceptionInterface;
11
use Doctrine\DBAL\Exception;
12
use Doctrine\DBAL\Exception\DriverException;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Doctrine\DBAL\Driver\DriverException. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
13
use Doctrine\DBAL\Platforms\AbstractPlatform;
14
use Doctrine\DBAL\Platforms\PostgreSQL100Platform;
15
use Doctrine\DBAL\Platforms\PostgreSQL94Platform;
16
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
17
use Doctrine\DBAL\Schema\AbstractSchemaManager;
18
use Doctrine\DBAL\Schema\PostgreSqlSchemaManager;
19
use Doctrine\DBAL\VersionAwarePlatformDriver;
20
use function preg_match;
21
use function strpos;
22
use function version_compare;
23
24
/**
25
 * Abstract base implementation of the {@link Doctrine\DBAL\Driver} interface for PostgreSQL based drivers.
26
 */
27
abstract class AbstractPostgreSQLDriver implements Driver, ExceptionConverterDriver, VersionAwarePlatformDriver
28
{
29
    /**
30
     * {@inheritdoc}
31
     *
32
     * @link http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html
33
     */
34 1021
    public function convertException(string $message, DriverExceptionInterface $exception) : DriverException
35
    {
36 1021
        switch ($exception->getSQLState()) {
37 1021
            case '40001':
38 1021
            case '40P01':
39 1021
                return new Exception\DeadlockException($message, $exception);
40 1021
            case '0A000':
41
                // Foreign key constraint violations during a TRUNCATE operation
42
                // are considered "feature not supported" in PostgreSQL.
43 586
                if (strpos($exception->getMessage(), 'truncate') !== false) {
44 586
                    return new Exception\ForeignKeyConstraintViolationException($message, $exception);
45
                }
46
47
                break;
48 1021
            case '23502':
49 1021
                return new Exception\NotNullConstraintViolationException($message, $exception);
50
51 1021
            case '23503':
52 1021
                return new Exception\ForeignKeyConstraintViolationException($message, $exception);
53
54 1021
            case '23505':
55 1021
                return new Exception\UniqueConstraintViolationException($message, $exception);
56
57 1021
            case '42601':
58 1021
                return new Exception\SyntaxErrorException($message, $exception);
59
60 1021
            case '42702':
61 1021
                return new Exception\NonUniqueFieldNameException($message, $exception);
62
63 1021
            case '42703':
64 1021
                return new Exception\InvalidFieldNameException($message, $exception);
65
66 1021
            case '42P01':
67 1021
                return new Exception\TableNotFoundException($message, $exception);
68
69 1021
            case '42P07':
70 1021
                return new Exception\TableExistsException($message, $exception);
71
72 1021
            case '7':
73
                // In some case (mainly connection errors) the PDO exception does not provide a SQLSTATE via its code.
74
                // The exception code is always set to 7 here.
75
                // We have to match against the SQLSTATE in the error message in these cases.
76 1021
                if (strpos($exception->getMessage(), 'SQLSTATE[08006]') !== false) {
77 1021
                    return new Exception\ConnectionException($message, $exception);
78
                }
79
80 1019
                break;
81
        }
82
83 1021
        return new DriverException($message, $exception);
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89 997
    public function createDatabasePlatformForVersion(string $version) : AbstractPlatform
90
    {
91 997
        if (! preg_match('/^(?P<major>\d+)(?:\.(?P<minor>\d+)(?:\.(?P<patch>\d+))?)?/', $version, $versionParts)) {
92 969
            throw DBALException::invalidPlatformVersionSpecified(
93 969
                $version,
94 969
                '<major_version>.<minor_version>.<patch_version>'
95
            );
96
        }
97
98 995
        $majorVersion = $versionParts['major'];
99 995
        $minorVersion = $versionParts['minor'] ?? 0;
100 995
        $patchVersion = $versionParts['patch'] ?? 0;
101 995
        $version      = $majorVersion . '.' . $minorVersion . '.' . $patchVersion;
102
103
        switch (true) {
104 995
            case version_compare($version, '10.0', '>='):
105 995
                return new PostgreSQL100Platform();
106 995
            case version_compare($version, '9.4', '>='):
107 995
                return new PostgreSQL94Platform();
108
            default:
109 995
                return new PostgreSqlPlatform();
110
        }
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     */
116 1047
    public function getDatabase(Connection $conn) : ?string
117
    {
118 1047
        $params = $conn->getParams();
119
120 1047
        return $params['dbname'] ?? $conn->query('SELECT CURRENT_DATABASE()')->fetchColumn();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $params['dbname']...BASE()')->fetchColumn() could return the type false which is incompatible with the type-hinted return null|string. Consider adding an additional type-check to rule them out.
Loading history...
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126 943
    public function getDatabasePlatform() : AbstractPlatform
127
    {
128 943
        return new PostgreSqlPlatform();
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134 917
    public function getSchemaManager(Connection $conn) : AbstractSchemaManager
135
    {
136 917
        return new PostgreSqlSchemaManager($conn);
137
    }
138
}
139