Passed
Push — master ( e889ab...9bcc67 )
by Mathieu
13:08
created

DBCollectionOneMany::save()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
c 2
b 0
f 0
nc 2
nop 0
dl 0
loc 15
ccs 0
cts 3
cp 0
crap 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Suricate;
6
7
class DBCollectionOneMany extends DBCollection
8
{
9
    /* @var string Name of parent identifier field */
10
    protected $parentIdField = 'parent_id';
11
12
    /* @var mixed parent identifier */
13
    protected $parentId;
14
15
    /* @var string parent field filter name */
16
    protected $parentFilterName;
17
18
    /* @var mixed parent filtering value */
19
    protected $parentFilterType;
20
21 1
    public function getParentIdField(): string
22
    {
23 1
        return $this->parentIdField;
24
    }
25
26 1
    public function getParentId()
27
    {
28 1
        return $this->parentId;
29
    }
30
31
    public function getParentFilterName()
32
    {
33
        return $this->parentFilterName;
34
    }
35
36
    public function getParentFilterType()
37
    {
38
        return $this->parentFilterType;
39
    }
40
41
    /**
42
     * Load entire table into collection
43
     * @return Collection Loaded collection
44
     */
45
    public static function loadAll()
46
    {
47
        $calledClass = get_called_class();
48
        $collection = new $calledClass();
49
        if ($collection->getParentFilterType()) {
50
            $sql = "SELECT *";
51
            $sql .= "   FROM `" . $collection->getTableName() . "`";
52
            $sql .= "WHERE " . $collection->parentFilterName . "=:type";
53
54
            $sqlParams = ['type' => $collection->parentFilterType];
55
56
            $collection->loadFromSql($sql, $sqlParams);
57
58
            return $collection;
59
        }
60
        return parent::loadAll();
61
    }
62
63
    /**
64
     * Load items linked to a parentId
65
     * @param mixed        $parentId       Parent id description
66
     * @param string       $parentIdField  Name of parent id referencing field
67
     * @param \Closure|null $validate       Callback use to validate add to items collection
68
     * @param string|null   $orderByField  Field name to order by
69
     * @param string|null   $orderByWay    Order way (ASC|DESC)
70
     */
71
    public static function loadForParentId(
72
        $parentId,
73
        $parentIdField = null,
74
        $validate = null,
75
        $orderByField = null,
76
        $orderByWay = null,
77
    ) {
78
        $calledClass = get_called_class();
79
        $collection = new $calledClass();
80
81
        if ($parentId != '') {
82
            $sqlParams = [];
83
            $dbHandler = Suricate::Database(true);
84
85
            if ($collection->getDBConfig() !== '') {
86
                $dbHandler->setConfig($collection->getDBConfig());
87
            }
88
89
            $sql = "SELECT *";
90
            $sql .= " FROM `" . $collection->getTableName() . "`";
91
            $sql .= " WHERE";
92
            if ($parentIdField !== null) {
93
                $sql .= "`" . $parentIdField . "`=:parent_id";
94
            } else {
95
                $sql .= "`" . $collection->getParentIdField() . "`=:parent_id";
96
            }
97
98
            if ($collection->parentFilterType !== null) {
99
                $sql .=
100
                    "   AND " . $collection->parentFilterName . "=:parent_type";
101
                $sqlParams['parent_type'] = $collection->parentFilterType;
102
            }
103
104
            if ($orderByField !== null) {
105
                $way = 'ASC';
106
                if ($orderByWay !== null && in_array(strtoupper($orderByWay), ['ASC', 'DESC'])) {
107
                    $way = strtoupper($orderByWay);
108
                }
109
                $sql .= " ORDER BY `" . $orderByField . "` " . $way;
110
            }
111
            $sqlParams['parent_id'] = $parentId;
112
            $results = $dbHandler->query($sql, $sqlParams)->fetchAll();
113
114
            if ($results !== false) {
115
                foreach ($results as $currentResult) {
116
                    $itemName = $collection->getItemsType();
117
                    $item = $itemName::instanciate($currentResult);
118
                    $item->setLoaded();
119
                    if ($validate === null || $validate($item)) {
120
                        $collection->addItem($item);
121
                    }
122
                }
123
            }
124
125
            $collection->parentId = $parentId;
126
        }
127
128
        return $collection;
129
    }
130
131
    public function setParentIdForAll($parentId)
132
    {
133
        $this->parentId = $parentId;
134
        foreach (array_keys($this->items) as $key) {
135
            $this->items[$key]->{$this->parentIdField} = $parentId;
136
        }
137
        return $this;
138
    }
139
140
    public function craftItem($itemData)
141
    {
142
        $itemName = $this->itemsType;
143
144
        foreach ($itemData as $data) {
145
            $newItem = new $itemName();
146
            $newItem->{$this->parentIdField} = $this->parentId;
147
            $hasData = false;
148
            foreach ($data as $field => $value) {
149
                $newItem->$field = $value;
150
                if ($value != '') {
151
                    $hasData = true;
152
                }
153
            }
154
155
            // Only add item if there's data inside
156
            if ($hasData) {
157
                $this->addItem($newItem);
158
            }
159
        }
160
    }
161
162
    public function save()
163
    {
164
        // 1st step : delete all records for current parentId
165
        $sql = "DELETE FROM `" . $this->tableName . "`";
166
        $sql .= " WHERE";
167
        $sql .= "   `" . $this->parentIdField . "`=:parent_id";
168
169
        $sqlParams = ['parent_id' => $this->parentId];
170
171
        $this->connectDB();
172
        $this->dbLink->query($sql, $sqlParams);
173
174
        // 2nd step : save all current items
175
        foreach ($this->items as $currentItem) {
176
            $currentItem->save(true); // Force insert
177
        }
178
    }
179
}
180