-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.php
More file actions
585 lines (511 loc) · 14.2 KB
/
code.php
File metadata and controls
585 lines (511 loc) · 14.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
<?php
/**
* @package Joomla.Component.Builder
*
* @created 4th September, 2022
* @author Llewellyn van der Merwe <https://dev.vdm.io>
* @git Joomla Component Builder <https://git.vdm.dev/joomla/Component-Builder>
* @copyright Copyright (C) 2015 Vast Development Method. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace VDM\Joomla\Database;
use Joomla\CMS\Date\Date;
use VDM\Joomla\Database\DefaultTrait;
use VDM\Joomla\Interfaces\Database\UpdateInterface;
use VDM\Joomla\Abstraction\Versioning;
/**
* Database Update Class
*
* @since 3.2.0
*/
final class Update extends Versioning implements UpdateInterface
{
/**
* Default Switch
*
* @since 5.1.1
*/
use DefaultTrait;
/**
* The updated multiple
*
* @var bool
* @since 5.1.4
**/
protected bool $multiple = false;
/**
* The updated id tracker bucket
*
* @var array
* @since 5.1.4
**/
protected array $updateids = [];
/**
* Get the IDs affected by the most recent UPDATE batch.
*
* This method returns the ordered list of entity IDs that were affected
* by the last UPDATE operation or batch of UPDATE operations.
*
* Behavioral notes:
* - IDs are resolved deterministically (ID, GUID, or WHERE-clause fallback).
* - The order of IDs reflects the order in which they were resolved.
* - IDs may represent one or many rows, depending on the UPDATE scope.
* - When `$reset` is enabled, the internal update ID bucket is cleared
* after the values are retrieved.
*
* @param bool $reset Whether to reset the internal update ID bucket
* after retrieval.
*
* @return array<int|string> The affected entity IDs.
*
* @since 5.1.4
*/
public function updateids(bool $reset = false): array
{
$ids = $this->updateids;
if ($reset && $ids !== [])
{
$this->updateids = [];
}
return $ids;
}
/**
* Update rows in the database (with remapping and filtering columns option)
*
* @param array $data Dataset to update in database [array of arrays (key => value)]
* @param string $key Dataset key column to use in updating the values in the Database
* @param string $table The table where the data is being updated
* @param array $columns Data columns for remapping and filtering
*
* @return bool
* @since 3.2.0
**/
public function rows(array $data, string $key, string $table, array $columns = []): bool
{
// set the update columns
if ($data === [] || $key === '')
{
return false;
}
// reset update ids bucket
$this->updateids = [];
$this->multiple = true;
// set the update values
foreach ($data as $values)
{
if ($columns !== [])
{
// load only what is part of the columns set
$row = [];
foreach ($columns as $column => $key_)
{
if (isset($values[$key_]))
{
$row[$column] = $values[$key_];
}
}
// update the row
$this->row($row, $key, $table);
}
else
{
// update the row
$this->row((array) $values, $key, $table);
}
}
if ($this->updateids !== [])
{
$this->trackHistory($this->updateids);
}
// always reset the switch's
$this->defaults()->history();
$this->multiple = false;
return true;
}
/**
* Update items in the database (with remapping and filtering columns option)
*
* @param array $data Data to updated in database (array of objects)
* @param string $key Dataset key column to use in updating the values in the Database
* @param string $table The table where the data is being update
* @param array $columns Data columns for remapping and filtering
*
* @return bool
* @since 3.2.0
**/
public function items(array $data, string $key, string $table, array $columns = []): bool
{
// set the update columns
if ($data === [] || $key === '')
{
return false;
}
// reset update ids bucket
$this->updateids = [];
$this->multiple = true;
// set the update values
foreach ($data as $nr => $values)
{
if ($columns !== [])
{
// load only what is part of the columns set
$row = [];
foreach ($columns as $column => $key_)
{
if (isset($values->{$key_}))
{
$row[$column] = $values->{$key_};
}
}
// update the row
$this->row($row, $key, $table);
}
else
{
// update the row
$this->row((array) $values, $key, $table);
}
}
if ($this->updateids !== [])
{
$this->trackHistory($this->updateids);
}
// always reset the switch's
$this->defaults()->history();
$this->multiple = false;
return true;
}
/**
* Update row in the database.
*
* Notes on ID tracking (critical for dependency + history workflows):
* - This method ALWAYS tracks the affected ID(s) in `$this->updateids`, even when history tracking is disabled.
* - ID resolution order (only fall back when the previous fails):
* 1) Use `id` from the provided dataset (if present).
* 2) Use `guid` from the provided dataset and resolve to ID(s).
* 3) Resolve ID(s) via the UPDATE WHERE clause (based on `$key` and its value).
*
* Multi-row safety:
* - If the WHERE clause matches more than one row, all matching IDs are tracked.
*
* @param array $data Dataset to update in database (key => value).
* @param string $key Dataset key column to use in updating the values in the Database.
* @param string $table The table where the data is being updated.
*
* @return bool
* @since 3.2.0
**/
public function row(array $data, string $key, string $table): bool
{
// basic validation
if ($data === [] || $key === '')
{
return false;
}
if (!$this->multiple)
{
// reset update ids bucket
$this->updateids = [];
}
// set history vars
$this->entity = $this->getTableEntityName($table);
$table = $this->getTable($table);
// extract identifier values from payload (id/guid/key value)
[$keyValue, $id, $guid] = $this->extractUpdateIdentifiers($data, $key);
// must have a WHERE key value
if ($keyValue === null)
{
return false;
}
// build the UPDATE query (keep original structure + quoting behaviour)
$query = $this->db->createQuery();
$query->update($this->db->quoteName($table));
foreach ($data as $column => $value)
{
// do not set the key column; it is used in WHERE
if ($column === $key)
{
continue;
}
$query->set($this->db->quoteName($column) . ' = ' . $this->quote($value));
}
// apply modified defaults exactly when needed
$this->applyUpdateDefaults($query, $data);
// build WHERE clause once (used for UPDATE and (if needed) fallback SELECT)
$where = $this->db->quoteName($key) . ' = ' . $this->quote($keyValue);
$query->where($where);
$resolvedIds = $this->resolveUpdateIds($id, $guid, $table, $where);
// execute the update
$this->db->setQuery($query);
$result = $this->db->execute();
if ($result && $resolvedIds !== [])
{
$this->updateids = array_values(
array_unique(
array_merge($this->updateids, $resolvedIds)
)
);
if (!$this->multiple)
{
$this->trackHistory($resolvedIds);
}
}
if (!$this->multiple)
{
// always reset the switch's
$this->defaults()->history();
}
return (bool) $result;
}
/**
* Update item in the database
*
* @param object $data Dataset to update in database (key => value)
* @param string $key Dataset key column to use in updating the values in the Database
* @param string $table The table where the data is being updated
*
* @return bool
* @since 3.2.0
**/
public function item(object $data, string $key, string $table): bool
{
// convert to an array
return $this->row((array) get_object_vars($data), $key, $table);
}
/**
* Update a single column value for all rows in the table
*
* @param mixed $value The value to assign to the column
* @param string $key Dataset key column to use in updating the values in the Database
* @param string $table The table where the update should be applied
*
* @return bool True on success, false on failure
* @since 5.1.1
*/
public function column(mixed $value, string $key, string $table): bool
{
// Ensure valid input
if ($key === '' || $table === '')
{
return false;
}
// Get a query object
$query = $this->db->createQuery();
// Prepare the update statement
$query->update($this->db->quoteName($this->getTable($table)))
->set($this->db->quoteName($key) . ' = ' . $this->quote($value));
// Apply the query
$this->db->setQuery($query);
return $this->db->execute();
}
/**
* Extract update identifiers from the dataset.
*
* Identifier resolution inputs:
* - `$keyValue` is always required to build the WHERE clause.
* - `$id` and `$guid` are optional and are used to avoid the fallback WHERE lookup.
*
* @param array $data The update dataset.
* @param string $key The WHERE key column name.
*
* @return array{0:mixed,1:?int,2:?string} Key value, id, guid.
* @since 5.1.4
*/
protected function extractUpdateIdentifiers(array $data, string $key): array
{
$keyValue = null;
$id = null;
$guid = null;
foreach ($data as $column => $value)
{
if (empty($value))
{
continue;
}
if ($column === $key)
{
$keyValue = $value;
continue;
}
// capture identifiers if present
if ($column === 'id')
{
$id = (int) $value;
}
elseif ($column === 'guid')
{
$guid = (string) $value;
}
}
return [$keyValue, $id, $guid];
}
/**
* Apply Joomla update defaults (modified / modified_by) if enabled and missing.
*
* This preserves the original behaviour:
* - Only applied when `$this->defaults` is enabled.
* - Only applied when the caller did not provide the columns already.
*
* @param object $query The update query object.
* @param array $data The update dataset.
*
* @return void
* @since 5.1.4
*/
protected function applyUpdateDefaults($query, array $data): void
{
if (!$this->defaults)
{
return;
}
$add_modified = !isset($data['modified']);
$add_modified_by = !isset($data['modified_by']);
if ($add_modified)
{
$query->set(
$this->db->quoteName('modified') . ' = ' . $this->quote((new Date())->toSql())
);
}
if ($add_modified_by)
{
$query->set(
$this->db->quoteName('modified_by') . ' = ' . (int) $this->userId
);
}
}
/**
* Resolve the affected ID(s) for an UPDATE operation.
*
* Resolution order (only fall back when the previous fails):
* 1) Use the provided `$id` if present and valid (>0).
* 2) Resolve by `$guid` if provided (returns one or multiple IDs).
* 3) Resolve by the WHERE clause (returns one or multiple IDs).
*
* @param int|null $id The entity ID if provided.
* @param string|null $guid The entity GUID if provided.
* @param string $table The full table name.
* @param string $where The WHERE clause used by the UPDATE.
*
* @return array<int> The resolved ID(s).
* @since 5.1.4
*/
protected function resolveUpdateIds(?int $id, ?string $guid, string $table, string $where): array
{
// 1) Direct ID
if (!empty($id) && $id > 0)
{
return [$id];
}
// 2) GUID -> ID(s)
if (!empty($guid))
{
$ids = $this->lookupIdsByGuid($guid, $table);
if ($ids !== [])
{
return $ids;
}
}
// 3) WHERE clause -> ID(s)
return $this->lookupIdsByWhere($where, $table);
}
/**
* Lookup ID(s) by GUID.
*
* @param string $guid The entity GUID.
* @param string $table The full table name.
*
* @return array<int> Matching ID(s), empty array if none found.
* @since 5.1.4
*/
protected function lookupIdsByGuid(string $guid, string $table): array
{
try
{
$query = $this->db->createQuery()
->select($this->db->quoteName('id'))
->from($this->db->quoteName($table))
->where($this->db->quoteName('guid') . ' = ' . $this->quote($guid));
$this->db->setQuery($query);
$this->db->execute();
if ($this->db->getNumRows())
{
return $this->db->loadColumn();
}
}
catch (\Throwable $e)
{
// Silently ignore all errors
}
return [];
}
/**
* Lookup ID(s) by an UPDATE WHERE clause.
*
* This is the final fallback and must only be used when:
* - no valid `$id` was provided, and
* - no `$guid` was provided or it could not be resolved.
*
* @param string $where The WHERE clause string.
* @param string $table The full table name.
*
* @return array<int> Matching ID(s), empty array if none found.
* @since 5.1.4
*/
protected function lookupIdsByWhere(string $where, string $table): array
{
if ($where === '')
{
return [];
}
try
{
$query = $this->db->createQuery()
->select($this->db->quoteName('id'))
->from($this->db->quoteName($table))
->where($where);
$this->db->setQuery($query);
$this->db->execute();
if ($this->db->getNumRows())
{
return $this->db->loadColumn();
}
}
catch (\Throwable $e)
{
// Silently ignore all errors
}
return [];
}
/**
* Apply history tracking for updated IDs.
*
* History is optional.
* - If history tracking is enabled and entity context exists, history is recorded.
*
* @param array<int> $ids The affected IDs.
*
* @return void
* @since 5.1.4
*/
protected function trackHistory(array $ids): void
{
if (!$this->history || empty($this->entity) || $ids === [])
{
return;
}
try
{
// Use the most efficient history call available
if (count($ids) === 1)
{
$this->setHistory((int) $ids[0]);
return;
}
$this->setMultipleHistory($ids);
}
catch (\Throwable $e)
{
// Silently ignore all errors
}
}
}