Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
14 / 14 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
PDOConnection | |
100.00% |
14 / 14 |
|
100.00% |
4 / 4 |
7 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 | |||
create | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
parseAttributes | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
4 | |||
name | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace Projom\Storage\Engine\Driver\Connection; |
6 | |
7 | use PDO; |
8 | |
9 | use Projom\Storage\Engine\Driver\Connection\ConnectionInterface; |
10 | |
11 | class PDOConnection extends PDO implements ConnectionInterface |
12 | { |
13 | const DEFAULT_ATTRIBUTES = [ |
14 | PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, |
15 | PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION |
16 | ]; |
17 | |
18 | private int|string $name; |
19 | |
20 | public function __construct( |
21 | int|string $name, |
22 | string $dsn, |
23 | null|string $username = null, |
24 | null|string $password = null, |
25 | null|array $options = null |
26 | ) { |
27 | |
28 | $this->name = $name; |
29 | |
30 | $options = $this->parseAttributes($options); |
31 | $options = $options + self::DEFAULT_ATTRIBUTES; |
32 | parent::__construct($dsn, $username, $password, $options); |
33 | } |
34 | |
35 | public static function create( |
36 | int|string $name, |
37 | string $dsn, |
38 | null|string $username = null, |
39 | null|string $password = null, |
40 | null|array $options = null |
41 | ): PDOConnection { |
42 | return new PDOConnection($name, $dsn, $username, $password, $options); |
43 | } |
44 | |
45 | private function parseAttributes(array $attributes): array |
46 | { |
47 | $parsedAttributes = []; |
48 | foreach ($attributes as $key => $value) { |
49 | |
50 | // An effort to make constant detection less error-prone. |
51 | $key = strtoupper(trim($key)); |
52 | $value = strtoupper(trim($value)); |
53 | |
54 | if (!defined($key) || !defined($value)) |
55 | throw new \Exception("The attribute $key or value $value is not a defined constant.", 400); |
56 | |
57 | $parsedAttributes[constant($key)] = constant($value); |
58 | } |
59 | |
60 | return $parsedAttributes; |
61 | } |
62 | |
63 | public function name(): int|string |
64 | { |
65 | return $this->name; |
66 | } |
67 | } |