Completed
Push — master ( f7852e...e666ea )
by Richard
06:08
created

DB::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/******************************************************************************
3
 * An implementation of dicto (scg.unibe.ch/dicto) in and for PHP.
4
 *
5
 * Copyright (c) 2016, 2015 Richard Klees <[email protected]>
6
 *
7
 * This software is licensed under The MIT License. You should have received
8
 * a copy of the license along with the code.
9
 */
10
11
namespace Lechimp\Dicto\App;
12
13
use Doctrine\DBAL\Connection;
14
15
abstract class DB {
16
    /**
17
     * @var Connection
18
     */
19
    protected $connection;
20
21 19
    public function __construct(Connection $connection) {
22 19
        $this->connection = $connection;
23 19
    }
24
25
    /**
26
     * @return \Doctrine\DBAL\Query\Builder
27
     */
28 19
    public function builder() {
29 19
        return $this->connection->createQueryBuilder();
30
    }
31
32
    /**
33
     * Initialize REGEXP for sqlite.
34
     */
35
    public function init_sqlite_regexp() {
36
        $pdo = $this->connection->getWrappedConnection();
37
        if (!($pdo instanceof \PDO)) {
38
            throw new \RuntimeException(
39
                "Expected wrapped connection to be PDO-object.");
40
        }
41
        $pdo->sqliteCreateFunction("regexp", function($pattern, $data) {
42
            return preg_match("%$pattern%", $data) > 0;
43
        });
44
    }
45
46
    // Creation of database.
47
48 5
    public function is_inited() {
49 5
        $res = $this->builder()
50 5
            ->select("COUNT(*)")
51 5
            ->from("sqlite_master")
52 5
            ->where("type = 'table'")
53 5
            ->execute()
54 5
            ->fetchColumn();
55 5
        return $res > 0;
56
    }
57
58 4
    public function maybe_init_database_schema() {
59 4
        if (!$this->is_inited()) {
60 4
            $this->init_database_schema();
61 4
        }
62 4
    }
63
64
    abstract public function init_database_schema();
65
}
66