Completed
Push — master ( 04d817...fb8d74 )
by Sébastien
01:58
created

AdapterFactory::getAdapterFromPdo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.2622

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 17
ccs 9
cts 13
cp 0.6923
rs 9.4286
cc 3
eloc 13
nc 3
nop 1
crap 3.2622
1
<?php
2
3
namespace Soluble\DbWrapper;
4
5
class AdapterFactory
6
{
7
8
    /**
9
     * Create adapter from an existing connection resource
10
     *
11
     * @param mixed $resource database connection object (mysqli, pdo_mysql,...)
12
     * @throws Exception\InvalidArgumentException
13
     * @throws Exception\UnsupportedDriverException
14
     * @return Adapter\AdapterInterface
15
     */
16 5
    public static function createAdapterFromResource($resource)
17
    {
18 5
        if (is_scalar($resource) || is_array($resource)) {
19 1
            throw new Exception\InvalidArgumentException("Resource param must be a valid 'resource' link (mysqli, pdo)");
20 4
        } if ($resource instanceof \PDO) {
21 2
            $adapter = self::getAdapterFromPdo($resource);
22 4
        } elseif (extension_loaded('mysqli') && $resource instanceof \mysqli) {
23 1
            $adapter = new Adapter\MysqliAdapter($resource);
24 1
        } else {
25 1
            throw new Exception\InvalidArgumentException("Resource must be a valid connection link, like PDO or mysqli");
26
        }
27 3
        return $adapter;
28
    }
29
30
31
    /**
32
     * Get an adapter from an existing connection resource
33
     *
34
     * @param \PDO $resource database connection object
35
     * @throws Exception\UnsupportedDriverException
36
     * @return Adapter\AdapterInterface
37
     */
38 2
    protected static function getAdapterFromPdo(\PDO $resource)
39
    {
40
41 2
        $driver = strtolower($resource->getAttribute(\PDO::ATTR_DRIVER_NAME));
42
        switch ($driver) {
43 2
            case 'mysql':
44 1
                $adapter = new Adapter\PdoMysqlAdapter($resource);
45 1
                break;
46 1
            case 'sqlite':
47 1
                $adapter = new Adapter\PdoSqliteAdapter($resource);
48 1
                break;
49
            default:
50
                $msg = "Driver 'PDO_$driver' is not currently supported.";
51
                throw new Exception\UnsupportedDriverException($msg);
52
        }
53 2
        return $adapter;
54
    }
55
}
56