Completed
Pull Request — master (#2776)
by Alessandro
04:59
created

DBALException   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 243
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 78.26%

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 0
dl 0
loc 243
ccs 54
cts 69
cp 0.7826
rs 10
c 0
b 0
f 0

18 Methods

Rating   Name   Duplication   Size   Complexity  
A notSupported() 0 4 1
A invalidPlatformSpecified() 0 6 1
A invalidPlatformVersionSpecified() 0 11 1
A invalidPdoInstance() 0 7 1
A driverRequired() 0 15 2
A unknownDriver() 0 5 1
A driverExceptionDuringQuery() 0 10 2
A driverException() 0 4 1
A wrapException() 0 11 4
A formatParameters() 0 13 4
A invalidWrapperClass() 0 5 1
A invalidDriverClass() 0 5 1
A invalidTableName() 0 4 1
A noColumnsSpecifiedForTable() 0 4 1
A limitOffsetInvalid() 0 4 1
A typeExists() 0 4 1
A typeNotFound() 0 4 1
A unknownColumnType() 0 11 1
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\DBAL;
21
22
use Doctrine\DBAL\Exception;
23
use Doctrine\DBAL\Driver;
24
use Doctrine\DBAL\Driver\ExceptionConverterDriver;
25
26
class DBALException extends \Exception
27
{
28
    /**
29
     * @param string $method
30
     *
31
     * @return \Doctrine\DBAL\DBALException
32
     */
33 49
    public static function notSupported($method)
34
    {
35 49
        return new self("Operation '$method' is not supported by platform.");
36
    }
37
38
    /**
39
     * @return \Doctrine\DBAL\DBALException
40
     */
41
    public static function invalidPlatformSpecified()
42
    {
43
        return new self(
44
            "Invalid 'platform' option specified, need to give an instance of ".
45
            "\Doctrine\DBAL\Platforms\AbstractPlatform.");
46
    }
47
48
    /**
49
     * Returns a new instance for an invalid specified platform version.
50
     *
51
     * @param string $version        The invalid platform version given.
52
     * @param string $expectedFormat The expected platform version format.
53
     *
54
     * @return DBALException
55
     */
56 10
    public static function invalidPlatformVersionSpecified($version, $expectedFormat)
57
    {
58 10
        return new self(
59 10
            sprintf(
60
                'Invalid platform version "%s" specified. ' .
61 10
                'The platform version has to be specified in the format: "%s".',
62 10
                $version,
63 10
                $expectedFormat
64
            )
65
        );
66
    }
67
68
    /**
69
     * @return \Doctrine\DBAL\DBALException
70
     */
71 1
    public static function invalidPdoInstance()
72
    {
73 1
        return new self(
74
            "The 'pdo' option was used in DriverManager::getConnection() but no ".
75 1
            "instance of PDO was given."
76
        );
77
    }
78
79
    /**
80
     * @param string|null $url The URL that was provided in the connection parameters (if any).
81
     *
82
     * @return \Doctrine\DBAL\DBALException
83
     */
84 5
    public static function driverRequired($url = null)
85
    {
86 5
        if ($url) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $url of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
87 4
            return new self(
88 4
                sprintf(
89
                    "The options 'driver' or 'driverClass' are mandatory if a connection URL without scheme " .
90 4
                    "is given to DriverManager::getConnection(). Given URL: %s",
91 4
                    $url
92
                )
93
            );
94
        }
95
96 1
        return new self("The options 'driver' or 'driverClass' are mandatory if no PDO ".
97 1
            "instance is given to DriverManager::getConnection().");
98
    }
99
100
    /**
101
     * @param string $unknownDriverName
102
     * @param array  $knownDrivers
103
     *
104
     * @return \Doctrine\DBAL\DBALException
105
     */
106 1
    public static function unknownDriver($unknownDriverName, array $knownDrivers)
107
    {
108 1
        return new self("The given 'driver' ".$unknownDriverName." is unknown, ".
109 1
            "Doctrine currently supports only the following drivers: ".implode(", ", $knownDrivers));
110
    }
111
112
    /**
113
     * @param \Doctrine\DBAL\Driver     $driver
114
     * @param \Exception $driverEx
115
     * @param string     $sql
116
     * @param array      $params
117
     *
118
     * @return \Doctrine\DBAL\DBALException
119
     */
120 69
    public static function driverExceptionDuringQuery(Driver $driver, \Exception $driverEx, $sql, array $params = array())
121
    {
122 69
        $msg = "An exception occurred while executing '".$sql."'";
123 69
        if ($params) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $params of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
124 9
            $msg .= " with params " . self::formatParameters($params);
125
        }
126 69
        $msg .= ":\n\n".$driverEx->getMessage();
127
128 69
        return static::wrapException($driver, $driverEx, $msg);
0 ignored issues
show
Bug introduced by
Since wrapException() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of wrapException() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
129
    }
130
131
    /**
132
     * @param \Doctrine\DBAL\Driver     $driver
133
     * @param \Exception $driverEx
134
     *
135
     * @return \Doctrine\DBAL\DBALException
136
     */
137 1
    public static function driverException(Driver $driver, \Exception $driverEx)
138
    {
139 1
        return static::wrapException($driver, $driverEx, "An exception occurred in driver: " . $driverEx->getMessage());
0 ignored issues
show
Bug introduced by
Since wrapException() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of wrapException() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
140
    }
141
142
    /**
143
     * @param \Doctrine\DBAL\Driver     $driver
144
     * @param \Exception $driverEx
145
     *
146
     * @return \Doctrine\DBAL\DBALException
147
     */
148 70
    private static function wrapException(Driver $driver, \Exception $driverEx, $msg)
149
    {
150 70
        if ($driverEx instanceof Exception\DriverException) {
151 1
            return $driverEx;
152
        }
153 69
        if ($driver instanceof ExceptionConverterDriver && $driverEx instanceof Driver\DriverException) {
154 63
            return $driver->convertException($msg, $driverEx);
155
        }
156
157 6
        return new self($msg, 0, $driverEx);
158
    }
159
160
    /**
161
     * Returns a human-readable representation of an array of parameters.
162
     * This properly handles binary data by returning a hex representation.
163
     *
164
     * @param array $params
165
     *
166
     * @return string
167
     */
168
    private static function formatParameters(array $params)
169
    {
170 9
        return '[' . implode(', ', array_map(function ($param) {
171 9
            $json = @json_encode($param);
172
173 9
            if (! is_string($json) || $json == 'null' && is_string($param)) {
174
                // JSON encoding failed, this is not a UTF-8 string.
175 1
                return '"\x' . implode('\x', str_split(bin2hex($param), 2)) . '"';
176
            }
177
178 9
            return $json;
179 9
        }, $params)) . ']';
180
    }
181
182
    /**
183
     * @param string $wrapperClass
184
     *
185
     * @return \Doctrine\DBAL\DBALException
186
     */
187 1
    public static function invalidWrapperClass($wrapperClass)
188
    {
189 1
        return new self("The given 'wrapperClass' ".$wrapperClass." has to be a ".
190 1
            "subtype of \Doctrine\DBAL\Connection.");
191
    }
192
193
    /**
194
     * @param string $driverClass
195
     *
196
     * @return \Doctrine\DBAL\DBALException
197
     */
198 1
    public static function invalidDriverClass($driverClass)
199
    {
200 1
        return new self("The given 'driverClass' ".$driverClass." has to implement the ".
201 1
            "\Doctrine\DBAL\Driver interface.");
202
    }
203
204
    /**
205
     * @param string $tableName
206
     *
207
     * @return \Doctrine\DBAL\DBALException
208
     */
209 1
    public static function invalidTableName($tableName)
210
    {
211 1
        return new self("Invalid table name specified: ".$tableName);
212
    }
213
214
    /**
215
     * @param string $tableName
216
     *
217
     * @return \Doctrine\DBAL\DBALException
218
     */
219 16
    public static function noColumnsSpecifiedForTable($tableName)
220
    {
221 16
        return new self("No columns specified for table ".$tableName);
222
    }
223
224
    /**
225
     * @return \Doctrine\DBAL\DBALException
226
     */
227
    public static function limitOffsetInvalid()
228
    {
229
        return new self("Invalid Offset in Limit Query, it has to be larger than or equal to 0.");
230
    }
231
232
    /**
233
     * @param string $name
234
     *
235
     * @return \Doctrine\DBAL\DBALException
236
     */
237
    public static function typeExists($name)
238
    {
239
        return new self('Type '.$name.' already exists.');
240
    }
241
242
    /**
243
     * @param string $name
244
     *
245
     * @return \Doctrine\DBAL\DBALException
246
     */
247
    public static function unknownColumnType($name)
248
    {
249
        return new self('Unknown column type "'.$name.'" requested. Any Doctrine type that you use has ' .
250
            'to be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a list of all the ' .
251
            'known types with \Doctrine\DBAL\Types\Type::getTypesMap(). If this error occurs during database ' .
252
            'introspection then you might have forgotten to register all database types for a Doctrine Type. Use ' .
253
            'AbstractPlatform#registerDoctrineTypeMapping() or have your custom types implement ' .
254
            'Type#getMappedDatabaseTypes(). If the type name is empty you might ' .
255
            'have a problem with the cache or forgot some mapping information.'
256
        );
257
    }
258
259
    /**
260
     * @param string $name
261
     *
262
     * @return \Doctrine\DBAL\DBALException
263
     */
264 16
    public static function typeNotFound($name)
265
    {
266 16
        return new self('Type to be overwritten '.$name.' does not exist.');
267
    }
268
}
269