HasDatabaseRecordsTrait::hasDB()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Nip\Records\Traits\HasDatabase;
4
5
use Nip\Container\Container;
6
use Nip\Database\Connections\Connection;
7
8
/**
9
 * Trait HasDatabaseRecordsTrait
10
 * @package Nip\Records\Traits\HasDatabase
11
 */
12
trait HasDatabaseRecordsTrait
13
{
14
15
    /**
16
     * @var Connection
17
     */
18
    protected $connection = null;
19
20
    /**
21
     * @return Connection
22
     */
23 8
    public function getDB()
24
    {
25 8
        if ($this->connection == null) {
26 3
            $this->initDB();
27
        }
28
29 8
        $this->checkDB();
30
31 8
        return $this->connection;
32
    }
33
34 3
    protected function initDB()
35
    {
36 3
        $this->setDB($this->newDbConnection());
37 3
    }
38
39
    /**
40
     * @param Connection $connection
41
     * @return $this
42
     */
43 42
    public function setDB($connection)
44
    {
45 42
        $this->connection = $connection;
46
47 42
        return $this;
48
    }
49
50
    /**
51
     * @return Connection
52
     */
53 3
    protected function newDbConnection()
54
    {
55 3
        if (function_exists('app')) {
56 3
            return app('db.connection');
57
        }
58
        return Container::getInstance()->get('db.connection');
59
    }
60
61 8
    public function checkDB()
62
    {
63 8
        if (!$this->hasDB()) {
64
            trigger_error("Database connection missing for [" . get_class($this) . "]", E_USER_ERROR);
65
        }
66 8
    }
67
68
    /**
69
     * @return bool
70
     */
71 8
    public function hasDB()
72
    {
73 8
        return $this->connection instanceof Connection;
74
    }
75
}
76