Passed
Push — develop ( f570a6...49a79e )
by Mathieu
01:37
created

DBCollection::save()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 7
ccs 0
cts 5
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Suricate;
4
5
class DBCollection extends Collection
6
{
7
    /* @var string SQL table name */
8
    protected $tableName        = '';
9
    /* @var string Item type stored in collection */
10
    protected $itemsType        = '';
11
    /* @var string Database configuration identifier */
12
    protected $DBConfig         = '';
13
14
    protected $mapping          = [];
15
    protected $lazyLoad = false;
16
17
    protected $dbLink               = false;
18
    protected $itemOffset           = 0;
19
20
    /**
21
     * Get table name
22
     *
23
     * @return string
24
     */
25 2
    public function getTableName(): string
26
    {
27 2
        return $this->tableName;
28
    }
29
30 4
    public function getItemsType(): string
31
    {
32 4
        return $this->itemsType;
33
    }
34
35 1
    public function getDBConfig(): string
36
    {
37 1
        return $this->DBConfig;
38
    }
39
40
    /**
41
     * Set lazyload flag
42
     *
43
     * @param bool $lazyLoad
44
     * @return DBCollection
45
     */
46 1
    public function setLazyLoad($lazyLoad)
47
    {
48 1
        $this->lazyLoad = $lazyLoad;
49
50 1
        return $this;
51
    }
52
53
    /**
54
     * Get lazyload flag
55
     *
56
     * @return boolean
57
     */
58 1
    public function getLazyLoad(): bool
59
    {
60 1
        return $this->lazyLoad;
61
    }
62
63
    public function purgeItems()
64
    {
65
        $this->items        = [];
66
        $this->mapping      = [];
67
        $this->itemOffset   = 0;
68
    }
69
70
    /**
71
     * Load entire table into collection
72
     * @return Collection Loaded collection
73
     */
74 1
    public static function loadAll()
75
    {
76 1
        $calledClass    = get_called_class();
77 1
        $collection     = new $calledClass;
78
79 1
        $sqlParams      = [];
80
81 1
        $sql  = "SELECT *";
82 1
        $sql .= "   FROM `" . $collection->getTableName() . "`";
83
84 1
        $collection->loadFromSql($sql, $sqlParams);
85
86 1
        return $collection;
87
    }
88
89
    /**
90
     * Static wrapper for loadFromSql
91
     * @param  string     $sql       SQL Statement
92
     * @param  array      $sqlParams SQL Parameters
93
     * @return Collection Loaded collection
94
     */
95 1
    public static function buildFromSql($sql, $sqlParams = [])
96
    {
97 1
        $calledClass = get_called_class();
98 1
        $collection = new $calledClass;
99
100 1
        $collection->loadFromSql($sql, $sqlParams);
101
102 1
        return $collection;
103
    }
104
105
    /**
106
     * Load collection from SQL query
107
     *
108
     * @param string $sql       SQL query
109
     * @param array  $sqlParams associative array of SQL params
110
     * @return DBCollection
111
     */
112 3
    public function loadFromSql($sql, $sqlParams = [])
113
    {
114 3
        if (!in_array(Interfaces\IDBObject::class, class_implements($this->itemsType))) {
115
            throw new \BadMethodCallException('Item type does not implement IDBObject interface');
116
        }
117
118 3
        $this->connectDB();
119 3
        $results = $this->dbLink->query($sql, $sqlParams)->fetchAll();
120
121 3
        if ($results !== false) {
122 3
            foreach ($results as $currentResult) {
123 3
                $itemName = $this->getItemsType();
124 3
                $this->addItem($itemName::instanciate($currentResult));
125
            }
126
        }
127
128 3
        return $this;
129
    }
130
131
    public function addItemLink($linkId)
132
    {
133
         $this->items[$this->itemOffset] = $linkId;
134
         // add mapping between item->index and $position in items pool
135
         $this->mapping[$this->itemOffset] = $linkId;
136
         $this->itemOffset++;
137
    }
138
139
    public function lazyLoadFromSql($sql, $sqlParams = array())
140
    {
141
        $dbLink = Suricate::Database();
0 ignored issues
show
Bug introduced by
The method Database() does not exist on Suricate\Suricate. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

141
        /** @scrutinizer ignore-call */ 
142
        $dbLink = Suricate::Database();
Loading history...
142
        if ($this->DBConfig !== '') {
143
            $dbLink->setConfig($this->DBConfig);
144
        }
145
146
        $results = $dbLink
147
            ->query($sql, $sqlParams)
148
            ->fetchAll();
149
150
        if ($results !== false) {
151
            foreach ($results as $currentResult) {
152
                $this->addItemLink(current($currentResult));
153
            }
154
        }
155
156
        return $this;
157
    }
158
159
    public function craftItem($itemData)
160
    {
161
        $itemName = $this->itemsType;
162
163
        foreach ($itemData as $data) {
164
            $newItem = new $itemName();
165
            $hasData = false;
166
            foreach ($data as $field => $value) {
167
                $newItem->$field = $value;
168
                if ($value != '') {
169
                    $hasData = true;
170
                }
171
            }
172
173
            // Only add item if there's data inside
174
            if ($hasData) {
175
                $this->addItem($newItem);
176
            }
177
        }
178
    }
179
180
    public function save()
181
    {
182
        $this->connectDB();
183
        $this->dbLink->query($sql, $sqlParams);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sqlParams seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $sql seems to be never defined.
Loading history...
184
185
        foreach ($this->items as $currentItem) {
186
            $currentItem->save(true); // Force insert
187
        }
188
    }
189
190 3
    public function addItem(Interfaces\IDBObject $item)
191
    {
192 3
        $key = $item->getTableIndex();
193
        // Add item to items pool
194 3
        $this->items[$this->itemOffset] = $item;
195
196
        // add mapping between item->index and $position in items pool
197 3
        $this->mapping[$this->itemOffset] = $item->$key;
198
199 3
        $this->itemOffset++;
200
201 3
        return $this;
202
    }
203
204 3
    protected function connectDB()
205
    {
206 3
        if (!$this->dbLink) {
207
            $this->dbLink = Suricate::Database();
208
            if ($this->getDBConfig() !== '') {
209
                $this->dbLink->setConfig($this->getDBConfig());
210
            }
211
        }
212 3
    }
213
}
214