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

DB   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 66.67%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 51
ccs 18
cts 27
cp 0.6667
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A builder() 0 3 1
A init_sqlite_regexp() 0 10 2
A is_inited() 0 9 1
A maybe_init_database_schema() 0 5 2
init_database_schema() 0 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