-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectDimensions.php
More file actions
466 lines (428 loc) · 13.8 KB
/
Copy pathObjectDimensions.php
File metadata and controls
466 lines (428 loc) · 13.8 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
<?php
/**
* ObjectDimensions
*
* Value object of the fieldtype FieldtypeObjectDimensions.
*
* Created by Jürgen K.
* https://github.com/juergenweb
* File name: ObjectDimensions.php
* Created: 02.02.2022
*/
declare(strict_types=1);
namespace ProcessWire;
/**
* Value object which holds the dimensions of an object
*
* Only the raw values of length, width and height are stored inside this object. All other values (area, volume,
* formatted values, labels) are calculated on the fly, so they are always up to date - also if a dimension value
* has been changed via the API.
*
* Available properties:
* - length, width, height, area, volume: raw number (unformatted) or string including the unit (formatted)
* - lengthUnformatted, widthUnformatted, ...: always the raw number
* - lengthLabel, widthLabel, ...: always the label and the formatted value (e.g. "Length: 2 cm")
* - unit: the size unit (e.g. cm)
*
* @property int|float|string|null $length
* @property int|float|string|null $width
* @property int|float|string|null $height
* @property int|float|string|null $area
* @property int|float|string|null $volume
* @property string $unit
*/
class ObjectDimensions extends WireData
{
/**
* Dimensions which are entered by the user and stored as raw values
*/
public const INPUT_KEYS = ['length', 'width', 'height'];
/**
* Dimensions which are calculated from the input dimensions
*/
public const CALCULATED_KEYS = ['area', 'volume'];
/**
* All dimensions
*/
public const ALL_KEYS = ['length', 'width', 'height', 'area', 'volume'];
/**
* Max number of decimals for the output (more is not possible with the precision of floats)
*/
public const MAX_OUTPUT_DECIMALS = 14;
/**
* The size unit (e.g. cm)
*/
protected string $dimUnit = 'cm';
/**
* The number of decimals of the dimensions
*/
protected int $dimDecimals = 2;
/**
* The type: "2d" or "3d"
*/
protected string $dimType = '3d';
/**
* Whether the dimension properties return formatted strings (true) or raw numbers (false)
*/
protected bool $isFormatted = false;
/**
* Create an object without values
*/
public function __construct()
{
parent::__construct();
foreach (self::INPUT_KEYS as $key) {
$this->set($key, null);
}
}
/**
* Set the configuration of the field (will be set by the fieldtype)
*
* @param string $unit the size unit (e.g. cm)
* @param int $decimals the number of decimals
* @param string $type "2d" or "3d"
* @return $this
*/
public function setConfig(string $unit, int $decimals, string $type): self
{
$this->dimUnit = $unit;
$this->dimDecimals = max(0, $decimals);
$this->dimType = ($type === '2d') ? '2d' : '3d';
return $this;
}
/**
* Set whether the dimension properties (length, width, ...) return formatted strings or raw numbers
*
* @param bool $formatted true: formatted strings including the unit, false: raw numbers
* @return $this
*/
public function setFormatted(bool $formatted = true): self
{
$this->isFormatted = $formatted;
return $this;
}
/**
* Check whether the dimension properties return formatted strings
*
* @return bool
*/
public function isFormatted(): bool
{
return $this->isFormatted;
}
/**
* Get a property value
*
* Handles the dimensions, the unit and the virtual properties (...Unformatted, ...Label). All other properties
* are handled by WireData.
*
* @param object|string $key
* @return mixed
*/
public function get($key)
{
if (is_string($key)) {
if ($key === 'unit') {
return $this->dimUnit;
}
// length, width, height, area, volume
if (in_array($key, self::ALL_KEYS, true)) {
return $this->isFormatted ? $this->format($key) : $this->raw($key);
}
// e.g. lengthUnformatted
if (str_ends_with($key, 'Unformatted')) {
$name = substr($key, 0, -strlen('Unformatted'));
if (in_array($name, self::ALL_KEYS, true)) {
return $this->raw($name);
}
}
// e.g. lengthLabel
if (str_ends_with($key, 'Label')) {
$name = substr($key, 0, -strlen('Label'));
if (in_array($name, self::ALL_KEYS, true)) {
return $this->label($name);
}
}
}
return parent::get($key);
}
/**
* Set a property value
*
* Calculated values (area, volume, ...Label, ...Unformatted) cannot be set and will be ignored.
*
* @param string $key
* @param mixed $value
* @return $this
*/
public function set($key, $value)
{
if ($key === 'unit') {
$this->dimUnit = (string)$value;
return $this;
}
if (is_string($key) && $this->isCalculatedKey($key)) {
return $this;
}
return parent::set($key, $value);
}
/**
* Check if a property is set (including the virtual properties)
*
* @param string $key
* @return bool
*/
public function __isset($key)
{
if (
is_string($key)
&& ($key === 'unit' || in_array($key, self::ALL_KEYS, true) || $this->isCalculatedKey($key))
) {
return true;
}
return parent::__isset($key);
}
/**
* Check if the key is a calculated value (area, volume, ...Label, ...Unformatted)
*
* @param string $key
* @return bool
*/
protected function isCalculatedKey(string $key): bool
{
if (in_array($key, self::CALCULATED_KEYS, true)) {
return true;
}
foreach (['Unformatted', 'Label'] as $suffix) {
if (str_ends_with($key, $suffix) && in_array(substr($key, 0, -strlen($suffix)), self::ALL_KEYS, true)) {
return true;
}
}
return false;
}
/**
* Get the raw value (number) of a dimension
*
* Returns null if the value has not been set (e.g. on a new page).
*
* @param string $key length, width, height, area or volume
* @return int|float|null int if no decimals are configured
*/
public function raw(string $key): int|float|null
{
switch ($key) {
case 'length':
case 'width':
return $this->toNumber(parent::get($key), $this->dimDecimals);
case 'height':
$height = parent::get('height');
if ($this->dimType === '2d' && $height !== null) {
$height = 0; // height does not exist on 2 dimensions
}
return $this->toNumber($height, $this->dimDecimals);
case 'area':
$length = $this->raw('length');
$width = $this->raw('width');
if ($length === null || $width === null) {
return null;
}
return $this->toNumber($length * $width, $this->getDecimals('area'));
case 'volume':
$area = $this->raw('area');
if ($area === null) {
return null;
}
if ($this->dimType === '2d') {
return $this->toNumber(0, $this->getDecimals('volume'));
}
$height = $this->raw('height');
if ($height === null) {
return null;
}
return $this->toNumber(
$this->raw('length') * $this->raw('width') * $height,
$this->getDecimals('volume')
);
}
return null;
}
/**
* Get the formatted value of a dimension including the unit (e.g. "2 cm", "6 cm²", "12 cm³")
*
* Returns plain text (not encoded for HTML).
*
* @param string $key length, width, height, area or volume
* @return string
*/
public function format(string $key): string
{
$number = $this->formatNumber($this->raw($key) ?? 0, $this->getDecimals($key));
$unit = $this->dimUnit;
if ($unit !== '') {
if ($key === 'area') {
$unit .= '²';
} elseif ($key === 'volume') {
$unit .= '³';
}
$number .= ' ' . $unit;
}
return $number;
}
/**
* Get the label and the formatted value of a dimension (e.g. "Length: 2 cm")
*
* Returns plain text (not encoded for HTML).
*
* @param string $key length, width, height, area or volume
* @return string
*/
public function label(string $key): string
{
$labels = InputfieldObjectDimensions::getLabels();
return ($labels[$key] ?? $key) . ': ' . $this->format($key);
}
/**
* Get all raw values and the unit as an array
*
* @return array
*/
public function getArray(): array
{
$out = [];
foreach (self::ALL_KEYS as $key) {
$out[$key] = $this->raw($key);
}
$out['unit'] = $this->dimUnit;
return $out;
}
/**
* Get the number of decimals for a dimension
*
* The area needs twice and the volume three times the decimals of the dimensions.
*
* @param string $key
* @return int
*/
protected function getDecimals(string $key): int
{
$factor = match ($key) {
'area' => 2,
'volume' => 3,
default => 1
};
return min($this->dimDecimals * $factor, self::MAX_OUTPUT_DECIMALS);
}
/**
* Convert a value to a rounded number
*
* @param mixed $value
* @param int $decimals
* @return int|float|null int if no decimals are allowed, null if the value is empty
*/
protected function toNumber(mixed $value, int $decimals): int|float|null
{
if ($value === null || $value === '') {
return null;
}
$value = round((float)$value, $decimals);
return $decimals === 0 ? (int)$value : $value;
}
/**
* Format a number for the output
*
* Removes trailing zeros (e.g. 2.50 -> 2.5) and uses the decimal separator of the current language.
*
* @param int|float $number
* @param int $decimals
* @return string
*/
protected function formatNumber(int|float $number, int $decimals): string
{
$out = number_format((float)$number, $decimals, '.', '');
if ($decimals > 0) {
$out = rtrim(rtrim($out, '0'), '.');
}
// translate "." to "," (e.g. in the German language file), if you want to use a comma as decimal separator
return str_replace('.', $this->_x('.', 'Decimal separator'), $out);
}
/**
* Render all dimensions as a string for the HTML output (e.g. "25 cm (L) * 10 cm (W) * 25 cm (H)")
*
* The values are encoded for HTML, because the unit is entered in the field configuration.
* Dimensions with a value of 0 are not shown.
*
* @param bool $label show the label in front of the dimensions (true) or not (false)
* @param string $multiplicationSign the sign for the multiplication (default is *)
* @return string empty string if all dimensions are 0
*/
public function renderDimensions(bool $label = false, string $multiplicationSign = '*'): string
{
$label = $label ? InputfieldObjectDimensions::getLabels()['dimensions'] . ': ' : '';
$abbreviations = [
'length' => $this->_('L'),
'width' => $this->_('W'),
'height' => $this->_('H')
];
// do not show zero values inside the string
$dimensions = [];
foreach ($abbreviations as $key => $abbreviation) {
if ((float)$this->raw($key) != 0) {
$dimensions[] = $this->entities($this->format($key) . ' (' . $abbreviation . ')');
}
}
if (!$dimensions) {
return '';
}
return $this->entities($label) . implode(' ' . $this->entities($multiplicationSign) . ' ', $dimensions);
}
/**
* Render dimensions, area and volume as an unordered list for the HTML output
*
* Area and volume are not shown if they are 0.
*
* @param string $multiplicationSign the sign for the multiplication (default is *)
* @return string empty string if there are no values
*/
public function renderAll(string $multiplicationSign = '*'): string
{
$allDimensions = [
'lwh' => $this->renderDimensions(true, $multiplicationSign)
];
// do not show area and volume if 0
foreach (self::CALCULATED_KEYS as $key) {
if ((float)$this->raw($key) != 0) {
$allDimensions[$key] = $this->entities($this->label($key));
}
}
// filter out empty values
$values = array_filter($allDimensions);
$out = '';
if ($values) {
$out .= '<ul class="dimensions">';
foreach ($values as $name => $value) {
$out .= '<li class="' . $name . '">' . $value . '</li>';
}
$out .= '</ul>';
}
return $out;
}
/**
* Encode a string for the HTML output
*
* @param string $value
* @return string
*/
protected function entities(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
/**
* Get the string value of the object (same as renderAll())
*
* @return string
*/
public function __toString(): string
{
return $this->renderAll();
}
}