-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathItemListBlockController.php
More file actions
368 lines (312 loc) · 10.2 KB
/
ItemListBlockController.php
File metadata and controls
368 lines (312 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<?php
namespace Xanweb\C5\Block;
use Concrete\Core\Block\BlockController as CoreBlockController;
use Concrete\Core\Cache\Level\ExpensiveCache;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\Editor\LinkAbstractor;
use Concrete\Core\Error\ErrorList\ErrorList;
use Concrete\Core\Support\Facade\Application;
use Doctrine\DBAL\Types\Type;
use Illuminate\Support\Collection;
abstract class ItemListBlockController extends CoreBlockController
{
/**
* Item List table: list of fields and other list prepared of insert query.
*
* @var array
*/
private $itemListTableFields = [];
/**
* @var \Illuminate\Support\Collection
*/
protected $items;
/**
* @var Connection
*/
private $connection;
/**
* @var ExpensiveCache
*/
private $cache;
/**
* Return Items table name.
*/
abstract protected function getItemListTable(): string;
/**
* {@inheritdoc}
*
* @see CoreBlockController::load()
*/
protected function load()
{
parent::load();
$this->loadItems();
}
/**
* Load items.
*/
protected function loadItems(): void
{
$app = Application::getFacadeApplication();
$cache = $this->cache();
$cacheItem = $cache->getItem(sprintf('block/%s/items', $this->bID));
$isCacheEnabled = $this->cacheBlockRecord() && $app['config']->get('concrete.cache.blocks');
if ($isCacheEnabled && $this->btCachedBlockRecord && !$cacheItem->isMiss()) {
$this->items = $cacheItem->get();
} else {
$db = $this->database();
$qb = $db->createQueryBuilder()->select('*')->from($this->getItemListTable());
$qb->where($qb->expr()->eq('bID', ':bID'))->setParameter('bID', $this->bID);
$this->items = Collection::make($qb->execute()->fetchAll());
if ($isCacheEnabled) {
$cacheItem->setTTL($this->btCacheBlockOutputLifetime ?? (60 * 60 * 24 * 90)); // 3 months if no cache lifetime is defined
$cache->save($cacheItem->set($this->items));
}
}
$this->set('items', $this->items);
}
/**
* Items table: load and get list of fields and other list prepared of insert query.
*
* @param string $prop (optional) can be FIELD_TYPE, DEFAULT, NOTNULL, QUERY_PLACE_HOLDER,
*/
private function getItemListTableProps(string $prop = ''): array
{
$cache = $this->cache();
if (empty($this->itemListTableFields)) {
$item = $cache->getItem(sprintf('block/%s/2nd-table-cols', $this->btHandle));
if (!$item->isMiss()) {
$this->itemListTableFields = $item->get();
} else {
$db = $this->database();
$columns = $db->getSchemaManager()->listTableColumns($this->getItemListTable());
foreach ($columns as $column) {
if (!$column->getAutoincrement()) {
$this->itemListTableFields[$column->getName()] = [
'FIELD_TYPE' => $column->getType()->getName(),
'DEFAULT' => $column->getDefault(),
'NOTNULL' => $column->getNotnull(),
'QUERY_PLACE_HOLDER' => ":{$column->getName()}",
];
}
}
$item->setTTL(60 * 60 * 24 * 30); // 30 Days
$cache->save($item->set($this->itemListTableFields));
}
}
if (!empty($prop)) {
return array_combine(
array_keys($this->itemListTableFields),
array_column($this->itemListTableFields, $prop)
);
}
return $this->itemListTableFields;
}
/**
* {@inheritdoc}
*
* @see CoreBlockController::duplicate()
*/
public function duplicate($newBID)
{
parent::duplicate($newBID);
$insertFields = $this->getItemListTableProps('QUERY_PLACE_HOLDER');
$this->database()->transactional(function (Connection $db) use ($insertFields, $newBID) {
$qb = $db->createQueryBuilder()
->insert($this->getItemListTable())
->values($insertFields);
foreach ($this->items as $item) {
$item['bID'] = $newBID;
(clone $qb)->setParameters($item)->execute();
}
});
}
/**
* {@inheritdoc}
*
* @see CoreBlockController::delete()
*/
public function delete()
{
$this->deleteItems();
parent::delete();
}
/**
* Delete second table items.
*/
protected function deleteItems(): void
{
$qb = $this->database()->createQueryBuilder();
$qb->delete($this->getItemListTable())
->where($qb->expr()->eq('bID', ':bID'))
->setParameter('bID', $this->bID)->execute();
$this->cache()->delete(sprintf('block/%s/items', $this->bID));
unset($this->items);
}
/**
* {@inheritdoc}
* Automatically save second table data.
*
* @see CoreBlockController::save()
*/
public function save($args)
{
parent::save($args);
$this->deleteItems();
if (empty($sanitizedData = $this->sanitizeData($args))) {
return;
}
$this->performSaveItems($sanitizedData);
}
protected function performSaveItems(array $sanitizedData): void
{
$insertFields = $this->getItemListTableProps('QUERY_PLACE_HOLDER');
$this->database()->transactional(function (Connection $db) use ($sanitizedData, $insertFields) {
$qb = $db->createQueryBuilder()
->insert($this->getItemListTable())
->values($insertFields);
foreach ($sanitizedData as $item) {
(clone $qb)->setParameters($item)->execute();
}
});
$this->loadItems();
}
public function validate($args)
{
$e = $this->app->make(ErrorList::class);
$this->_validate($args, $e);
$this->validateItems($args, $e);
return $e;
}
protected function _validate(?array $args, ErrorList $e): void
{
}
protected function validateItems(?array $args, ErrorList $e): void
{
$sanitizedData = $this->sanitizeData($args);
foreach ($sanitizedData as $i => $item) {
$this->validateItem($i + 1, $item, $e);
}
}
/**
* Check if the item is valid.
*
* @param int $itemNbr
* @param array $item
* @param ErrorList $e
*
* @return void
*/
protected function validateItem(int $itemNbr, array $item, ErrorList $e)
{
}
/**
* Prepare Second Table Fields Data before saving them to database.
*
* @param $data
*
* @return array sanitized array
*/
private function sanitizeData($data): array
{
$sanitizedData = [];
$itemDefaults = $this->getItemDefaults();
$fieldsTypes = $this->getItemListTableProps('FIELD_TYPE');
foreach ($fieldsTypes as $field => $type) {
if ($field === 'bID' || !isset($data[$field])) {
continue;
}
foreach ($data[$field] as $i => $v) {
if (!isset($sanitizedData[$i])) {
// Init Row with defaults data
$sanitizedData[$i] = $itemDefaults;
}
$sanitizedData[$i][$field] = $this->sanitizeVal($field, $type, $v);
}
}
return $sanitizedData;
}
/**
* Get Row default Values from Table Schema.
*/
protected function getItemDefaults(): array
{
$itemDefaults = ['bID' => $this->bID];
foreach ($this->getItemListTableProps() as $field => $properties) {
if ($field === 'bID') {
continue;
}
$itemDefaults[$field] = $this->sanitizeVal($field, $properties['FIELD_TYPE'], $properties['DEFAULT']);
}
return $itemDefaults;
}
/**
* Prepare Second Table Field Value before saving it to database.
*
* @param $field
* @param $type
* @param $value
*
* @return mixed sanitized value
*/
protected function sanitizeVal($field, $type, $value)
{
switch ($type) {
case Type::INTEGER:
case Type::SMALLINT:
$sanitizedVal = (int) $value;
break;
case Type::STRING:
$sanitizedVal = trim((string) $value);
break;
case Type::TEXT:
$sanitizedVal = (string) $value;
// Check if is Html
if ($sanitizedVal !== strip_tags($sanitizedVal)) {
$sanitizedVal = LinkAbstractor::translateTo($sanitizedVal);
}
break;
case Type::BOOLEAN:
$sanitizedVal = $value ? 1 : 0;
break;
default:
$sanitizedVal = $value;
}
return $sanitizedVal;
}
/**
* Get list of items sorted by given fields.
*
* @param array $sort ['col1' => 'ASC', 'col2' => 'DESC']
*/
public function getItems(array $sort = []): array
{
if (!$this->items) {
return [];
}
if (!empty($sort)) {
$sortedItems = $this->items;
foreach ($sort as $col => $dir) {
$sortedItems = $sortedItems->sortBy($col, SORT_REGULAR, strtoupper($dir) === 'DESC');
}
return array_values($sortedItems->toArray());
}
return array_values($this->items->toArray());
}
private function database(): Connection
{
if (!$this->connection) {
$app = $this->app ?? Application::getFacadeApplication();
$this->connection = $app->make('database/connection');
}
return $this->connection;
}
private function cache(): ExpensiveCache
{
if (!$this->cache) {
$app = $this->app ?? Application::getFacadeApplication();
$this->cache = $app->make('cache/expensive');
}
return $this->cache;
}
}