Completed
Push — master ( 19d4fc...09bb07 )
by Gabriel
03:42
created

HasDatabaseRecordsTrait::checkDB()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.1481

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
ccs 2
cts 3
cp 0.6667
crap 2.1481
rs 10
c 0
b 0
f 0
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 7
    public function getDB()
24
    {
25 7
        if ($this->connection == null) {
26 3
            $this->initDB();
27
        }
28
29 7
        $this->checkDB();
30
31 7
        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 24
    public function setDB($connection)
44
    {
45 24
        $this->connection = $connection;
46
47 24
        return $this;
48
    }
49
50
    /**
51
     * @return Connection
52
     */
53 3
    protected function newDbConnection()
54
    {
55 3
        if (function_exists('app')) {
56
            return app('db.connection');
57
        }
58 3
        return Container::getInstance()->get('db.connection');
59
    }
60
61 7
    public function checkDB()
62
    {
63 7
        if (!$this->hasDB()) {
64
            trigger_error("Database connection missing for [" . get_class($this) . "]", E_USER_ERROR);
65
        }
66 7
    }
67
68
    /**
69
     * @return bool
70
     */
71 7
    public function hasDB()
72
    {
73 7
        return $this->connection instanceof Connection;
74
    }
75
}
76