Completed
Push — master ( 178b4a...1f981d )
by Richard
06:19
created

DBFactory::get_result_db()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 5
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\DriverManager;
14
15
class DBFactory {
16
    /**
17
     * Create a new database for index at path.
18
     *
19
     * @param   string  $path
20
     * @throws  \RuntimeException   if database already exists.
21
     * @return  IndexDB
22
     */
23 1
    public function build_index_db($path) {
24 1
        if (file_exists($path)) {
25 1
            throw new \RuntimeException("File at '$path' already exists, can't build database.");
26
        }
27
        $connection = $this->build_connection($path);
28
        $db = new IndexDB($connection);
29
        $db->init_sqlite_regexp();
30
        $db->init_database_schema();
31
        return $db;
32
    }
33
34
    /**
35
     * Check if an index database exists.
36
     *
37
     * @param   string  $path
38
     * @return  bool
39
     */
40 4
    public function index_db_exists($path) {
41 4
        return file_exists($path);
42
    }
43
44
    /**
45
     * Load existing index database. 
46
     *
47
     * @param   string  $path
48
     * @throws  \RuntimeException   if file does not exist
49
     * @return  IndexDB 
50
     */
51 2
    public function load_index_db($path) {
52 2
        if (!$this->index_db_exists($path)) {
53 1
            throw new \RuntimeException("There is no index database at '$path'");
54
        }
55 1
        $connection = $this->build_connection($path);
56 1
        $db = new IndexDB($connection);
57 1
        $db->init_sqlite_regexp();
58 1
        return $db;
59
    }
60
61
    /**
62
     * Get a database for results.
63
     *
64
     * @param   string  $path
65
     * @return  ResultDB
66
     */
67 5
    public function get_result_db($path) {
68 5
        $connection = $this->build_connection($path);
69 5
        $db = new ResultDB($connection);
70 5
        $db->maybe_init_database_schema();
71 5
        return $db;
72
    }
73
74 6
    protected function build_connection($path) {
75 6
        assert('is_string($path)');
76
        return DriverManager::getConnection
77 6
            ( array
78
                ( "driver" => "pdo_sqlite"
79 6
                , "memory" => false
80 6
                , "path" => $path
81 6
                )
82 6
            );
83
    }
84
}
85