Completed
Push — master ( d4f070...1ddfcf )
by Jan-Petter
05:06
created

TableConstructor   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 64
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A create() 0 14 4
A exists() 0 9 2
1
<?php
2
namespace vipnytt\RobotsTxtParser\SQL;
3
4
use PDO;
5
use vipnytt\RobotsTxtParser\Exceptions\SQLException;
6
7
/**
8
 * Class TableConstructor
9
 *
10
 * @package vipnytt\RobotsTxtParser\SQL
11
 */
12
class TableConstructor
13
{
14
    /**
15
     * Database connection
16
     * @var PDO
17
     */
18
    private $pdo;
19
20
    /**
21
     * Table name
22
     * @var string
23
     */
24
    private $table;
25
26
    /**
27
     * TableConstructor constructor.
28
     *
29
     * @param PDO $pdo
30
     * @param string $tableName
31
     */
32
    public function __construct(PDO $pdo, $tableName)
33
    {
34
        $this->pdo = $pdo;
35
        $this->table = $tableName;
36
    }
37
38
    /**
39
     * Create table
40
     *
41
     * @param string $sql
42
     * @param string $readme
43
     * @return bool
44
     * @throws SQLException
45
     */
46
    public function create($sql, $readme)
47
    {
48
        if ($this->exists()) {
49
            return true;
50
        }
51
        try {
52
            $this->pdo->query($sql);
53
        } catch (\PDOException $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
54
        }
55
        if ($this->exists()) {
56
            return true;
57
        }
58
        throw new SQLException('Automatic setup failed, please create table `' . $this->table . '` manually. Setup instructions: ' . $readme);
59
    }
60
61
    /**
62
     * Check if the table exists
63
     *
64
     * @return bool
65
     */
66
    public function exists()
67
    {
68
        try {
69
            $result = $this->pdo->query("SELECT 1 FROM " . $this->table . " LIMIT 1;");
70
        } catch (\PDOException $e) {
71
            return false;
72
        }
73
        return $result !== false;
74
    }
75
}
76