Ajde_Db   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 162
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 162
rs 10
c 0
b 0
f 0
wmc 26
lcom 2
cbo 4

13 Methods

Rating   Name   Duplication   Size   Complexity  
A getInstance() 0 6 2
A __construct() 0 14 1
A getAdapter() 0 4 1
A getConnection() 0 4 1
A getTable() 0 8 2
C executeFile() 0 42 8
A version() 0 9 2
A update() 0 8 1
A installFromVersion() 0 11 3
A versionSort() 0 4 1
A updateVersion() 0 4 1
A install() 0 11 2
A isInstalled() 0 4 1
1
<?php
2
3
class Ajde_Db extends Ajde_Object_Singleton
4
{
5
    protected $_adapter = null;
6
    protected $_tables = null;
7
8
    const FIELD_TYPE_NUMERIC = 'numeric';
9
    const FIELD_TYPE_TEXT = 'text';
10
    const FIELD_TYPE_ENUM = 'enum';
11
    const FIELD_TYPE_DATE = 'date';
12
    const FIELD_TYPE_SPATIAL = 'spatial';
13
14
    /**
15
     * @return Ajde_Db
16
     */
17
    public static function getInstance()
18
    {
19
        static $instance;
20
21
        return $instance === null ? $instance = new self() : $instance;
22
    }
23
24
    protected function __construct()
25
    {
26
        $adapterName = 'Ajde_Db_Adapter_'.ucfirst(config('database.adapter'));
27
        $host = config('database.host');
28
        $db = config('database.db');
29
        $user = config('database.user');
30
        $password = config('database.password');
31
32
        // TODO Move DSN template to adapter
33
        $this->_adapter = new $adapterName([
34
            'host'   => $host,
35
            'dbname' => $db,
36
        ], $user, $password);
37
    }
38
39
    /**
40
     * @return Ajde_Db_Adapter_Abstract
41
     */
42
    public function getAdapter()
43
    {
44
        return $this->_adapter;
45
    }
46
47
    /**
48
     * @return Ajde_Db_PDO
49
     */
50
    public function getConnection()
51
    {
52
        return $this->_adapter->getConnection();
53
    }
54
55
    public function getTable($tableName)
56
    {
57
        if (!isset($this->_tables[$tableName])) {
58
            $this->_tables[$tableName] = new Ajde_Db_Table($tableName);
59
        }
60
61
        return $this->_tables[$tableName];
62
    }
63
64
    public function executeFile($filename)
65
    {
66
        // @see http://stackoverflow.com/a/10209702/938297
67
68
        // time limit
69
        @set_time_limit(5 * 60);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
70
71
        // load file
72
        $commands = file_get_contents($filename);
73
74
        // delete comments
75
        $lines = explode("\n", $commands);
76
        $commands = '';
77
        foreach ($lines as $line) {
78
            $line = trim($line);
79
            if ($line && !(substr($line, 0, 2) === '--')) {
80
                $commands .= $line."\n";
81
            }
82
        }
83
84
        // convert to array
85
        $commands = explode(';'.PHP_EOL, $commands);
86
87
        // run commands
88
        $total = $success = 0;
89
        foreach ($commands as $command) {
90
            if (trim($command)) {
91
                try {
92
                    $success += ($this->getConnection()->query($command) === false ? 0 : 1);
93
                } catch (Exception $e) {
94
                    echo $e->getMessage().'<br/>';
95
                }
96
                $total += 1;
97
            }
98
        }
99
100
        // return number of successful queries and total number of queries found
101
        return [
102
            'success' => $success,
103
            'total'   => $total,
104
        ];
105
    }
106
107
    public function version()
108
    {
109
        $results = $this->getConnection()->query("SELECT v FROM ajde WHERE k = 'version' LIMIT 1");
110
        foreach ($results as $result) {
0 ignored issues
show
Bug introduced by
The expression $results of type null|object<PDOStatement> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
111
            $version = $result[0];
112
        }
113
114
        return $version;
0 ignored issues
show
Bug introduced by
The variable $version does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
115
    }
116
117
    public function update()
118
    {
119
        $dbVersion = $this->version();
120
        $this->installFromVersion($dbVersion);
121
        $this->updateVersion();
122
123
        return true;
124
    }
125
126
    private function installFromVersion($version = 'v0')
127
    {
128
        $sqlFiles = Ajde_Fs_Find::findFiles(DEV_DIR.'db'.DIRECTORY_SEPARATOR, 'v*.sql');
129
        usort($sqlFiles, [$this, 'versionSort']);
130
        foreach ($sqlFiles as $sqlFile) {
131
            $sqlFileVersion = pathinfo($sqlFile, PATHINFO_FILENAME);
132
            if (version_compare($sqlFileVersion, $version) > 0) {
133
                $this->executeFile($sqlFile);
134
            }
135
        }
136
    }
137
138
    private function versionSort($a, $b)
139
    {
140
        return version_compare($a, $b);
141
    }
142
143
    private function updateVersion($version = AJDE_VERSION)
144
    {
145
        $this->getConnection()->query("UPDATE ajde SET v = '".$version."' WHERE k = 'version' LIMIT 1");
146
    }
147
148
    public function install()
149
    {
150
        if ($this->isInstalled()) {
151
            die('DB already installed');
152
        }
153
154
        $this->installFromVersion();
155
        $this->updateVersion();
156
157
        die('DB installed. <a href="index.php">Proceed to homepage</a>');
158
    }
159
160
    private function isInstalled()
161
    {
162
        return $this->getConnection()->query("SHOW TABLES LIKE 'ajde'")->rowCount() > 0;
163
    }
164
}
165