-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFieldtypeObjectDimensions.module
More file actions
632 lines (573 loc) · 22.2 KB
/
Copy pathFieldtypeObjectDimensions.module
File metadata and controls
632 lines (573 loc) · 22.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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
<?php
/**
* Fieldtype ObjectDimensions
*
* Stores length, width and height of an object and the calculated area (L * W) and volume (L * W * H) in the
* database. Area and volume are stored too, so they can be used in selectors (e.g. "dimensions.volume>1000").
*
* Created by Jürgen K.
* https://github.com/juergenweb
* File name: FieldtypeObjectDimensions.module
* Created: 02.02.2022
*/
declare(strict_types=1);
namespace ProcessWire;
use Exception;
use PDO;
// phpcs:disable PSR1.Files.SideEffects -- ProcessWire does not autoload the helper class ObjectDimensions
require_once __DIR__ . '/ObjectDimensions.php';
// phpcs:enable
/**
* Fieldtype to store the dimensions of an object
*
* The configuration (type, size unit, number of decimals) is stored in the field and affects the database schema.
* The value of a page is an ObjectDimensions object.
*/
class FieldtypeObjectDimensions extends Fieldtype
{
/**
* Max number of decimals for the dimensions (the volume needs 3 times the decimals and MySQL allows max 30)
*/
public const MAX_DECIMALS = 10;
/**
* Default number of decimals
*/
public const DEFAULT_DECIMALS = 2;
/**
* Number of integer digits (digits before the decimal point) for each database column
*/
public const INTEGER_DIGITS = [
'length' => 12,
'width' => 12,
'height' => 12,
'area' => 24,
'volume' => 35
];
/**
* Factor for the number of decimals of each database column (area = decimals * 2, volume = decimals * 3)
*/
public const DECIMALS_FACTOR = [
'length' => 1,
'width' => 1,
'height' => 1,
'area' => 2,
'volume' => 3
];
/**
* Get the module information for ProcessWire
*
* @return array
*/
public static function getModuleInfo(): array
{
return array(
'title' => 'Fieldtype Object Dimensions',
'summary' => 'Fieldtype to store length, width, height, volume and area of an object.',
'version' => '1.3.0',
'href' => 'https://github.com/juergenweb/FieldtypeObjectDimensions',
'icon' => 'cube',
'installs' => 'InputfieldObjectDimensions',
'requires' => [
'PHP>=8.0',
'ProcessWire>=3.0.212'
],
'author' => 'Jürgen Kern'
);
}
/**
* Get the inputfield used by this fieldtype
*
* @param Page $page
* @param Field $field
* @return null|_Module|Inputfield|Module
* @throws WirePermissionException
*/
public function getInputfield(Page $page, Field $field): null|_Module|Inputfield|Module
{
return $this->modules->get('InputfieldObjectDimensions');
}
/* ---------------------------------------------------------------------------------------------------------------
* Field configuration
* ------------------------------------------------------------------------------------------------------------ */
/**
* Get the number of decimals set in the field configuration (0 - MAX_DECIMALS)
*
* Uses the default (2 decimals) if no value has been set yet (e.g. on a newly created field).
*
* @param Field $field
* @return int
*/
public function getDecimals(Field $field): int
{
if ($field->input_decimals === null || $field->input_decimals === '') {
return self::DEFAULT_DECIMALS;
}
return min(max(0, intval($field->input_decimals)), self::MAX_DECIMALS);
}
/**
* Get the type set in the field configuration (2d or 3d)
*
* @param Field $field
* @return string "2d" or "3d" (default)
*/
public function getType(Field $field): string
{
return ($field->input_type === '2d') ? '2d' : '3d';
}
/**
* Get the size unit set in the field configuration
*
* @param Field $field
* @return string the size unit (default: cm)
*/
public function getUnit(Field $field): string
{
return $field->input_sizeunit ? (string)$field->input_sizeunit : 'cm';
}
/**
* Get the configuration fields of the fieldtype
*
* These settings affect the database schema and the calculation, so they are part of the fieldtype and
* cannot be changed per template (context).
*
* @param Field $field
* @return InputfieldWrapper
* @throws WireException
* @throws WirePermissionException
*/
public function ___getConfigInputfields(Field $field): InputfieldWrapper
{
$inputfields = parent::___getConfigInputfields($field);
// type: 2 or 3 dimensions
$f = $this->modules->get('InputfieldSelect');
$f->label = $this->_('Type');
$f->attr('name+id', 'input_type');
$f->addOptions([
'3d' => $this->_('3 dimensions'),
'2d' => $this->_('2 dimensions')
]);
$f->attr('value', $this->getType($field));
$f->required(true);
$f->description = $this->_('3 dimensions: length, width and height; 2 dimensions: length and width.');
// phpcs:ignore Generic.Files.LineLength -- translatable strings must be a single string literal
$f->notes = $this->_('If you change the type to 2 dimensions, height and volume of all pages will be set to 0.');
$inputfields->append($f);
// size unit for the dimensions (e.g. cm, inch, m)
$f = $this->modules->get('InputfieldText');
$f->label = $this->_('Size unit');
$f->attr('name+id', 'input_sizeunit');
$f->attr('value', $this->getUnit($field));
$f->attr('size', 10);
$f->required(true);
$f->description = $this->_('The size unit for the dimensions (e.g. cm, mm, m, inch).');
$inputfields->append($f);
// number of decimals
$f = $this->modules->get('InputfieldInteger');
$f->label = $this->_('Number of decimals');
$f->attr('name+id', 'input_decimals');
$f->attr('value', $this->getDecimals($field));
$f->attr('min', 0);
$f->attr('max', self::MAX_DECIMALS);
$f->required(true);
$f->description = $this->_('The number of decimals that can be entered in the dimension fields.');
$f->notes = sprintf(
// phpcs:ignore Generic.Files.LineLength -- translatable strings must be a single string literal
$this->_('A value of 0 means that the dimension values are integers. Max value is %d. Area and volume will be stored with 2 and 3 times the number of decimals. Reducing the number of decimals rounds all existing values.'),
self::MAX_DECIMALS
);
$inputfields->append($f);
return $inputfields;
}
/**
* Sanitize the configuration values before the field will be saved
*
* Limits the number of decimals to MAX_DECIMALS (with a warning) and normalizes the type.
*
* @param Field $field
* @return void
*/
public function ___saveFieldReady(Field $field): void
{
parent::___saveFieldReady($field);
if (
$field->input_decimals !== null && $field->input_decimals !== ''
&& intval($field->input_decimals) !== $this->getDecimals($field)
) {
$this->warning(sprintf(
$this->_('The number of decimals of field "%1$s" has been set to %2$d (allowed: 0 - %3$d).'),
$field->name,
$this->getDecimals($field),
self::MAX_DECIMALS
));
}
$field->input_decimals = $this->getDecimals($field);
$field->input_type = $this->getType($field);
}
/**
* Sync the database schema and the calculated values after the field has been saved (via admin or API)
*
* Errors are shown as error messages instead of exceptions, because the field has already been saved.
*
* @param Field $field
* @return void
*/
public function ___savedField(Field $field): void
{
parent::___savedField($field);
try {
if ($this->syncSchema($field)) {
$this->message($this->_('Database schema was updated.'));
}
$this->updateCalculatedValues($field);
} catch (Exception $e) {
$this->error(sprintf(
$this->_('Error while updating the database table of field "%1$s": %2$s'),
$field->name,
$e->getMessage()
));
}
}
/* ---------------------------------------------------------------------------------------------------------------
* Values
* ------------------------------------------------------------------------------------------------------------ */
/**
* Pass the field configuration (unit, decimals, type) to the dimension object
*
* @param ObjectDimensions $value
* @param Field $field
* @return ObjectDimensions the same object
*/
protected function applyConfig(ObjectDimensions $value, Field $field): ObjectDimensions
{
return $value->setConfig($this->getUnit($field), $this->getDecimals($field), $this->getType($field));
}
/**
* Sanitize the value
*
* Values which are not an ObjectDimensions object are replaced by a blank value. Changes of the dimensions are
* tracked on the page.
*
* @param Page $page
* @param Field $field
* @param int|object|WireArray|string $value
* @return int|null|ObjectDimensions|WireArray|string
*/
public function sanitizeValue(Page $page, Field $field, $value): int|null|ObjectDimensions|WireArray|string
{
if (!$value instanceof ObjectDimensions) {
$value = $this->getBlankValue($page, $field);
} else {
// objects created via the API do not know the field configuration
$this->applyConfig($value, $field);
}
// track changes of the dimension values
if ($value->isChanged('length') || $value->isChanged('width') || $value->isChanged('height')) {
$page->trackChange($field->name);
}
return $value;
}
/**
* Convert the value from the database to the API value
*
* Only length, width and height will be loaded, area and volume are calculated by the object itself.
*
* @param Page $page
* @param Field $field
* @param string|int|array $value
* @return ObjectDimensions
*/
public function wakeupValue(Page $page, Field $field, $value): ObjectDimensions
{
// instantiate a new object with blank values
$dim = $this->getBlankValue($page, $field);
if (is_array($value)) {
foreach (ObjectDimensions::INPUT_KEYS as $key) {
if (isset($value[$key])) {
$dim->set($key, (float)$value[$key]);
}
}
}
return $dim;
}
/**
* Format the value for the output on the frontend
*
* The dimension properties (length, width, ...) of the returned copy output strings including the unit.
*
* @param Page $page
* @param Field $field
* @param mixed $value
* @return mixed
*/
public function ___formatValue(Page $page, Field $field, $value)
{
// nothing to format if the value is not a dimension object
if (!$value instanceof ObjectDimensions) {
return $value;
}
// work on a copy, so that the unformatted value stored inside the page will not be modified
$value = clone $value;
$this->applyConfig($value, $field);
return $value->setFormatted(true);
}
/**
* Get a new ObjectDimensions object without values
*
* @param Page $page
* @param Field $field
* @return ObjectDimensions
*/
public function getBlankValue(Page $page, Field $field): ObjectDimensions
{
return $this->applyConfig(new ObjectDimensions(), $field);
}
/**
* Convert the API value to the value stored in the database
*
* @param Page $page
* @param Field $field
* @param string|int|array|object $value
* @return array column name => value
* @throws Exception if the value is not an ObjectDimensions object
*/
public function sleepValue(Page $page, Field $field, $value): array
{
if (!$value instanceof ObjectDimensions) {
throw new Exception($this->_('Expecting an instance of ObjectDimensions'));
}
$this->applyConfig($value, $field);
// store the raw values - area and volume will always be calculated by the object itself, so they are always
// up to date and stored in the database for the usage in selectors
$sleepValue = [];
foreach (ObjectDimensions::ALL_KEYS as $key) {
$sleepValue[$key] = (float)$value->raw($key);
}
// the column "data" (created by ProcessWire for every field) is not used by this fieldtype, but it has no
// default value -> it must be written, otherwise inserts fail in MySQL strict mode
$sleepValue['data'] = 0;
return $sleepValue;
}
/**
* Get the compatible fieldtypes
*
* The fieldtype of an existing field cannot be changed to another fieldtype.
*
* @param Field $field
* @return Fieldtypes|null
*/
public function ___getCompatibleFieldtypes(Field $field): ?Fieldtypes
{
return null;
}
/* ---------------------------------------------------------------------------------------------------------------
* Database schema
* ------------------------------------------------------------------------------------------------------------ */
/**
* Get the database schema for this field
*
* @param Field $field
* @return array
*/
public function getDatabaseSchema(Field $field): array
{
$schema = parent::getDatabaseSchema($field);
foreach ($this->getColumnTypes($field) as $col => $type) {
$schema[$col] = $type . ' NOT NULL DEFAULT 0';
}
return $schema;
}
/**
* Get the MySQL column types for all dimension columns as set in the field configuration
*
* E.g. with 2 decimals: length/width/height = decimal(14,2), area = decimal(28,4), volume = decimal(41,6)
*
* @param Field $field
* @return array column name => type
*/
public function getColumnTypes(Field $field): array
{
$decimals = $this->getDecimals($field);
$types = [];
foreach (self::INTEGER_DIGITS as $col => $integerDigits) {
$scale = $decimals * self::DECIMALS_FACTOR[$col];
$types[$col] = 'decimal(' . ($integerDigits + $scale) . ',' . $scale . ')';
}
return $types;
}
/**
* Get the column types which are currently used in the database table
*
* @param Field $field
* @return array column name => type
* @throws Exception if the table does not exist or has no columns
*/
public function getActiveColumnTypes(Field $field): array
{
$database = $this->database;
$query = $database->query("SHOW COLUMNS FROM `" . $database->escapeTable($field->getTable()) . "`");
$types = [];
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$types[$row['Field']] = $row['Type'];
}
if (!$types) {
throw new Exception($this->_('Cannot determine the type of the field'));
}
return $types;
}
/**
* Normalize a MySQL column type for the comparison
*
* Removes the display width from integer types, because MySQL >= 8.0.19 does not output it anymore
* (e.g. "int(11)" -> "int"), and removes all whitespaces (e.g. "decimal(65, 2)" -> "decimal(65,2)").
*
* @param string $type
* @return string
*/
protected function normalizeType(string $type): string
{
$type = strtolower(preg_replace('/\s+/', '', $type));
return preg_replace('/^(tinyint|smallint|mediumint|int|bigint)\(\d+\)/', '$1', $type);
}
/**
* Get the columns whose type in the database differs from the configuration
*
* @param Field $field
* @return array column name => configured type
* @throws Exception
*/
public function getChangedColumns(Field $field): array
{
$active = $this->getActiveColumnTypes($field);
$changed = [];
foreach ($this->getColumnTypes($field) as $col => $type) {
if (!isset($active[$col]) || $this->normalizeType($active[$col]) !== $this->normalizeType($type)) {
$changed[$col] = $type;
}
}
return $changed;
}
/**
* Sync the column types in the database with the field configuration
*
* Missing columns will be added. The schema will not be changed if an existing value is too large for the new
* column type, because MySQL would cut it silently.
*
* @param Field $field
* @return bool true if the schema has been changed
* @throws Exception if a value is too large for the new column type
*/
public function syncSchema(Field $field): bool
{
$changed = $this->getChangedColumns($field);
if (!$changed) {
return false;
}
$database = $this->database;
$table = $database->escapeTable($field->getTable());
$active = $this->getActiveColumnTypes($field);
// make sure that no existing value is too large for the new column type (MySQL would cut it silently)
foreach ($changed as $col => $type) {
if (!isset($active[$col])) {
continue;
}
$maxAllowed = pow(10, self::INTEGER_DIGITS[$col]);
$max = $database->query("SELECT MAX(ABS(`$col`)) FROM `$table`")->fetchColumn();
if ($max !== null && $max !== false && (float)$max >= $maxAllowed) {
throw new Exception(sprintf(
$this->_('Column "%1$s" contains values which are too large for the new type %2$s.'),
$col,
$type
));
}
}
// alter all changed columns within one query (add missing columns)
$modify = [];
foreach ($changed as $col => $type) {
$modify[] = (isset($active[$col]) ? 'MODIFY' : 'ADD') . " `$col` $type NOT NULL DEFAULT 0";
}
$database->exec("ALTER TABLE `$table` " . implode(', ', $modify));
return true;
}
/**
* Recalculate area and volume inside the database (e.g. after changing the number of decimals or the type)
*
* On 2 dimensions height and volume will be set to 0. Only rows with wrong values will be updated.
*
* @param Field $field
* @return int number of updated rows
*/
public function updateCalculatedValues(Field $field): int
{
$database = $this->database;
$table = $database->escapeTable($field->getTable());
if ($this->getType($field) === '2d') {
$sql = "UPDATE `$table` SET `height` = 0, `area` = `length` * `width`, `volume` = 0 " .
"WHERE `height` <> 0 OR `volume` <> 0 OR `area` <> `length` * `width`";
} else {
$sql = "UPDATE `$table` SET `area` = `length` * `width`, `volume` = `length` * `width` * `height` " .
"WHERE `area` <> `length` * `width` OR `volume` <> `length` * `width` * `height`";
}
return (int)$database->exec($sql);
}
/* ---------------------------------------------------------------------------------------------------------------
* Upgrade / migration
* ------------------------------------------------------------------------------------------------------------ */
/**
* Run the migrations if the module version changes (called by ProcessWire)
*
* @param int|string $fromVersion
* @param int|string $toVersion
* @return void
*/
public function ___upgrade($fromVersion, $toVersion): void
{
$from = $this->modules->formatVersion((string)$fromVersion);
if (version_compare($from, '1.3.0', '<')) {
$this->migrateTo130();
}
}
/**
* Migrate all fields of this fieldtype to version 1.3.0
*
* - The type (2d/3d) cannot be changed per template anymore -> remove it from all template contexts
* (if different types are used, 3d will be used, because it contains all values).
* - The number of decimals is limited to MAX_DECIMALS.
* - New column types (more decimals for area and volume) and recalculation of area and volume.
*
* The migration can run multiple times without changing already migrated fields.
*
* @return void
*/
public function migrateTo130(): void
{
foreach ($this->wire()->fields as $field) {
if (!$field->type instanceof FieldtypeObjectDimensions) {
continue;
}
// 1. remove the type from all template contexts
$types = [$this->getType($field)];
foreach ($this->wire()->fieldgroups as $fieldgroup) {
$context = $fieldgroup->getFieldContextArray($field->id);
if (!is_array($context) || !array_key_exists('input_type', $context)) {
continue;
}
$types[] = ($context['input_type'] === '2d') ? '2d' : '3d';
unset($context['input_type']);
$fieldgroup->setFieldContextArray($field->id, $context);
$fieldgroup->saveContext();
}
if (count(array_unique($types)) > 1) {
$field->input_type = '3d';
$this->warning(sprintf(
// phpcs:ignore Generic.Files.LineLength -- translatable strings must be a single string literal
$this->_('Field "%s" used different types (2d/3d) in the templates. It has been set to 3 dimensions for all templates.'),
$field->name
));
}
// 2. + 3. save the field -> saveFieldReady() limits the decimals, savedField() updates the schema and
// recalculates area and volume
$this->wire()->fields->save($field);
$this->message(sprintf($this->_('Field "%s" has been migrated to version 1.3.0.'), $field->name));
}
}
}