Completed
Pull Request — develop (#3570)
by Jonathan
155:39 queued 152:58
created

AbstractPostgreSQLDriver::convertException()   C

Complexity

Conditions 15
Paths 15

Size

Total Lines 47
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 15.0102

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 47
ccs 27
cts 28
cp 0.9643
rs 5.9166
c 0
b 0
f 0
cc 15
nc 15
nop 2
crap 15.0102

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\Driver;
9
use Doctrine\DBAL\Driver\DriverException as DriverExceptionInterface;
10
use Doctrine\DBAL\Exception;
11
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...
12
use Doctrine\DBAL\Platforms\AbstractPlatform;
13
use Doctrine\DBAL\Platforms\Exception\InvalidPlatformVersion;
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 1323
    public function convertException(string $message, DriverExceptionInterface $exception) : DriverException
35
    {
36 1323
        switch ($exception->getSQLState()) {
37 1323
            case '40001':
38 1323
            case '40P01':
39 1116
                return new Exception\DeadlockException($message, $exception);
40 1323
            case '0A000':
41
                // Foreign key constraint violations during a TRUNCATE operation
42
                // are considered "feature not supported" in PostgreSQL.
43 727
                if (strpos($exception->getMessage(), 'truncate') !== false) {
44 727
                    return new Exception\ForeignKeyConstraintViolationException($message, $exception);
45
                }
46
47
                break;
48 1323
            case '23502':
49 1231
                return new Exception\NotNullConstraintViolationException($message, $exception);
50
51 1323
            case '23503':
52 1300
                return new Exception\ForeignKeyConstraintViolationException($message, $exception);
53
54 1323
            case '23505':
55 1139
                return new Exception\UniqueConstraintViolationException($message, $exception);
56
57 1323
            case '42601':
58 1208
                return new Exception\SyntaxErrorException($message, $exception);
59
60 1323
            case '42702':
61 1254
                return new Exception\NonUniqueFieldNameException($message, $exception);
62
63 1323
            case '42703':
64 1277
                return new Exception\InvalidFieldNameException($message, $exception);
65
66 1323
            case '42P01':
67 1162
                return new Exception\TableNotFoundException($message, $exception);
68
69 1323
            case '42P07':
70 1323
                return new Exception\TableExistsException($message, $exception);
71
        }
72
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 1323
        if ($exception->getCode() === 7 && strpos($exception->getMessage(), 'SQLSTATE[08006]') !== false) {
77 1323
            return new Exception\ConnectionException($message, $exception);
78
        }
79
80 1070
        return new DriverException($message, $exception);
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86 1047
    public function createDatabasePlatformForVersion(string $version) : AbstractPlatform
87
    {
88 1047
        if (! preg_match('/^(?P<major>\d+)(?:\.(?P<minor>\d+)(?:\.(?P<patch>\d+))?)?/', $version, $versionParts)) {
89 1024
            throw InvalidPlatformVersion::new(
90 1024
                $version,
91 1024
                '<major_version>.<minor_version>.<patch_version>'
92
            );
93
        }
94
95 1047
        $majorVersion = $versionParts['major'];
96 1047
        $minorVersion = $versionParts['minor'] ?? 0;
97 1047
        $patchVersion = $versionParts['patch'] ?? 0;
98 1047
        $version      = $majorVersion . '.' . $minorVersion . '.' . $patchVersion;
99
100
        switch (true) {
101 1047
            case version_compare($version, '10.0', '>='):
102 1047
                return new PostgreSQL100Platform();
103 1047
            case version_compare($version, '9.4', '>='):
104 1047
                return new PostgreSQL94Platform();
105
            default:
106 1047
                return new PostgreSqlPlatform();
107
        }
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113 1346
    public function getDatabase(Connection $conn) : ?string
114
    {
115 1346
        $params = $conn->getParams();
116
117 1346
        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...
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123 1001
    public function getDatabasePlatform() : AbstractPlatform
124
    {
125 1001
        return new PostgreSqlPlatform();
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131 978
    public function getSchemaManager(Connection $conn) : AbstractSchemaManager
132
    {
133 978
        return new PostgreSqlSchemaManager($conn);
134
    }
135
}
136