Completed
Push — master ( 512542...4d85fd )
by Jan-Petter
02:22
created

SQLTrait::tableExists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
namespace vipnytt\RobotsTxtParser\SQL;
3
4
use PDO;
5
use PDOException;
6
7
/**
8
 * Class SQLTrait
9
 *
10
 * @package vipnytt\RobotsTxtParser\SQL
11
 */
12
trait SQLTrait
13
{
14
    /**
15
     * Initialize PDO connection
16
     *
17
     * @param PDO $pdo |null
18
     * @return PDO
19
     */
20
    private function pdoInitialize(PDO $pdo = null)
21
    {
22
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
0 ignored issues
show
Bug introduced by
It seems like $pdo is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
23
        $pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
24
        $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
25
        return $pdo;
26
    }
27
28
    /**
29
     * Create table
30
     *
31
     * @param PDO $pdo
32
     * @param string $table
33
     * @param string $query
34
     * @return bool
35
     */
36
    private function createTable(PDO $pdo, $table, $query)
37
    {
38
        if ($this->tableExists($pdo, $table)) {
39
            return true;
40
        }
41
        try {
42
            $pdo->query($query);
43
        } catch (PDOException $e) {
44
            return FALSE;
45
        }
46
        return $this->tableExists($pdo, $table);
47
    }
48
49
    /**
50
     * Check if the table exists
51
     *
52
     * @param PDO $pdo
53
     * @param string $table
54
     * @return bool
55
     */
56
    private function tableExists(PDO $pdo, $table)
57
    {
58
        try {
59
            $result = $pdo->query("SELECT 1 FROM $table LIMIT 1;");
60
        } catch (\Exception $e) {
61
            return FALSE;
62
        }
63
        return $result !== FALSE;
64
    }
65
}
66