Repository navigation
Expand file tree
/
Copy pathFieldtypeOpeningHours.test.php
More file actions
879 lines (756 loc) · 37.6 KB
/
Copy pathFieldtypeOpeningHours.test.php
File metadata and controls
879 lines (756 loc) · 37.6 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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
<?php namespace ProcessWire;
/**
* WireTests for the FieldtypeOpeningHours module (live environment)
*
* These tests run inside a real ProcessWire installation with the real database, a real
* Field/Fieldgroup/Template/Page and the real Inputfield form processing. They complement
* the unit tests in the "tests" folder (which run against a stub environment without
* ProcessWire - see tests/bootstrap.php).
*
* Run from the ProcessWire root directory:
*
* php index.php test FieldtypeOpeningHours
*
* Requirements: ProcessWire with the WireTests module installed (core module since 3.0.267).
*
* A temporary field (self::TEST_FIELD_NAME) is created on the shared WireTests test page's
* template for the duration of the test and removed again in finish() - also if a test
* fails. Nothing on an already-existing field of this type is touched.
*/
class WireTest_FieldtypeOpeningHours extends WireTest {
const TEST_FIELD_NAME = 'wtest_openinghours';
/** @var FieldtypeOpeningHours */
protected $module;
/** @var InputfieldOpeningHours */
protected $inputfieldModule;
/** @var Field|null */
protected $field;
/** @var Page|null the shared WireTests test page */
protected $page;
/** whether this test created the field (and must remove it again) */
protected $fieldCreatedByTest = false;
/** whether this test added the field to the test page's fieldgroup */
protected $fieldAddedToFieldgroup = false;
/** notices that existed before the test (to remove the ones we create) */
protected $noticeCount = 0;
/** the "page" API variable as it was before this test changed it (restored in finish()) */
protected $originalPage;
/** @var Page|null a second, independent real page created for testLazyCronCleanupAcrossPages() */
protected $extraPage;
/** @var Fieldgroup|null a temporary fieldgroup created for testFieldContextOverride() */
protected $contextFieldgroup;
/** @var Template|null a temporary template created for testFieldContextOverride() */
protected $contextTemplate;
/** @var Page|null a temporary page created for testFieldContextOverride() */
protected $contextPage;
/** @var Language|null the language given a temporary per-language timeformat by testMultiLanguageFormatting() */
protected $languageForFormatTest;
/** whether testMultiLanguageFormatting() changed the active user language (restored in finish()) */
protected $languageChanged = false;
public function allow() {
return $this->wire()->modules->isInstalled('FieldtypeOpeningHours')
&& $this->wire()->modules->isInstalled('InputfieldOpeningHours');
}
public function init() {
$modules = $this->wire()->modules;
$this->module = $modules->get('FieldtypeOpeningHours');
$this->inputfieldModule = $modules->get('InputfieldOpeningHours');
$this->noticeCount = count($this->wire()->notices);
$this->page = $this->getTestPage(true);
$this->setupField();
// output formatting must be off while we set/read values directly via the API below -
// otherwise Page::get() would hand back a formatted CLONE (see
// FieldtypeOpeningHours::formatValue(), which clones the value), and mutating that
// clone would silently be lost instead of ending up in the saved value
$this->page->of(false);
// OpeningHours::render()/renderDay()/renderTable()/renderDefinitionList()/renderDiv()
// all refuse to output anything while the "page" API variable points somewhere under
// the admin URL (they are meant to be frontend-only). Point it at our own, definitely
// non-admin test page for the duration of this test so those checks below are
// deterministic regardless of what "page" happens to be set to when tests are run
// from the command line.
$this->originalPage = $this->wire()->page;
$this->wire()->wire('page', $this->page);
}
public function execute() {
$this->testInstallation();
$this->testDatabaseSchema();
$this->testSchemaSelfHeal();
$this->testBlankAndSanitizeValue();
$this->testSaveAndLoadRoundtrip();
$this->testRenderMethods();
$this->testJsonLD();
$this->testExceptionsAndStatus();
$this->testOverlapWarning();
$this->testFormProcessing();
$this->testConfigInputfields();
$this->testTranslations();
$this->testLazyCronCleanupAcrossPages();
$this->testXssAndSecurityHardening();
$this->testFieldContextOverride();
$this->testMultiLanguageFormatting();
}
public function finish() {
// restore the "page" API variable
if($this->originalPage) {
$this->wire()->wire('page', $this->originalPage);
}
// remove the second test page created by testLazyCronCleanupAcrossPages(), if any
if($this->extraPage && $this->extraPage->id) {
$this->wire()->pages->delete($this->extraPage, true);
}
// restore the active user language changed by testMultiLanguageFormatting(), if any
if($this->languageChanged && $this->wire()->languages) {
$this->wire()->languages->unsetLanguage();
$this->languageChanged = false;
}
// remove the temporary per-language timeformat set by testMultiLanguageFormatting()
if($this->languageForFormatTest && $this->field) {
$this->field->remove('timeformat' . $this->languageForFormatTest->id);
$this->field->save();
}
// remove the temporary page/template/fieldgroup created by testFieldContextOverride(),
// in that order (a page must go before its template, a template before its fieldgroup)
if($this->contextPage && $this->contextPage->id) {
$this->wire()->pages->delete($this->contextPage, true);
}
if($this->contextTemplate && $this->contextTemplate->id) {
$this->wire()->templates->delete($this->contextTemplate);
}
if($this->contextFieldgroup && $this->contextFieldgroup->id) {
$this->wire()->fieldgroups->delete($this->contextFieldgroup);
}
// reset the page value so no leftover test data stays on the shared test page
if($this->page && $this->field) {
$this->page->set($this->field->name, $this->module->getBlankValue($this->page, $this->field));
$this->page->save($this->field->name);
}
// remove the field from the test template again, and delete it if this test created it
if($this->field && $this->fieldAddedToFieldgroup && $this->page) {
$fieldgroup = $this->page->template->fieldgroup;
$fieldgroup->remove($this->field);
$fieldgroup->save();
}
if($this->field && $this->fieldCreatedByTest) {
$this->wire()->fields->delete($this->field);
}
// remove the notices/warnings created by the tests above (fe the overlap warning)
$notices = $this->wire()->notices;
$remove = [];
foreach($notices as $index => $notice) {
if($index >= $this->noticeCount) $remove[] = $notice;
}
foreach($remove as $notice) $notices->remove($notice);
}
// ---------------------------------------------------------------------------------------------
// Setup
// ---------------------------------------------------------------------------------------------
/**
* Create (or reuse) a field of this type on the shared WireTests test page's template
*/
protected function setupField() {
$fields = $this->wire()->fields;
$field = $fields->get(self::TEST_FIELD_NAME);
if(!$field) {
$field = new Field();
$field->type = $this->module;
$field->name = self::TEST_FIELD_NAME;
$field->label = 'WireTest OpeningHours';
$this->fieldCreatedByTest = true;
}
// A field created via the API (rather than through its own config screen in the
// admin) does NOT automatically get the Inputfield's config defaults - those are
// only ever applied to what's shown in the form (fe
// "$f->attr('value', $this->numberOftimes ? $this->numberOftimes : 2)"), not
// persisted to the Field itself until that screen is actually saved once. Enforce
// them explicitly here - every run, not just on creation - so this field always
// behaves like a normally-configured one, even if a previous run left it behind
// (fe after a crashed test) without these properties set.
$defaults = [
'numberOftimes' => 2,
'timeformat' => '%R',
'tableheader' => '',
'hideholiday' => 0,
];
$needsSave = !$field->id; // brand new field always needs the initial save
foreach($defaults as $name => $value) {
if($field->get($name) !== $value) {
$field->set($name, $value);
$needsSave = true;
}
}
if($needsSave) $field->save();
$this->field = $field;
if($this->page) {
$fieldgroup = $this->page->template->fieldgroup;
if(!$fieldgroup->hasField($field)) {
$fieldgroup->add($field);
$fieldgroup->save();
$this->fieldAddedToFieldgroup = true;
}
}
}
// ---------------------------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------------------------
/**
* Module is installed correctly, is autoload, and declares the Inputfield it depends on
*/
protected function testInstallation() {
$modules = $this->wire()->modules;
$this->check('Module instance', true, $this->module instanceof FieldtypeOpeningHours);
$this->check('Module is autoload', true, (bool) $modules->isAutoload($this->module));
$this->check('Inputfield module is installed', true, $modules->isInstalled('InputfieldOpeningHours'));
$this->check('Test field uses FieldtypeOpeningHours', true, $this->field->type instanceof FieldtypeOpeningHours);
$this->check('Test field returns the OpeningHours Inputfield', true,
$this->module->getInputfield($this->page, $this->field) instanceof InputfieldOpeningHours);
$info = FieldtypeOpeningHours::getModuleInfo();
$this->check('Module declares InputfieldOpeningHours as a dependency to install', 'InputfieldOpeningHours', $info['installs'] ?? '');
}
/**
* The real database table for a field of this type has the expected columns
*/
protected function testDatabaseSchema() {
$database = $this->wire()->database;
$table = $this->field->getTable();
$columns = $database->query("SHOW COLUMNS FROM `$table`")->fetchAll(\PDO::FETCH_COLUMN);
$this->check('Table has a "times" column', true, in_array('times', $columns, true));
$this->check('Table has an "exceptions" column', true, in_array('exceptions', $columns, true));
$schema = $this->module->getDatabaseSchema($this->field);
$this->check('getDatabaseSchema() declares "times"', true, isset($schema['times']));
$this->check('getDatabaseSchema() declares "exceptions"', true, isset($schema['exceptions']));
}
/**
* The self-healing schema check (init()) re-adds a column that was dropped from an
* existing field's table, without the user having to resave the field manually
*/
protected function testSchemaSelfHeal() {
$database = $this->wire()->database;
$modules = $this->wire()->modules;
$table = $this->field->getTable();
// back up and reset the "already applied" schema version flag so ensureSchemaUpToDate()
// actually runs its checks again instead of returning early
$configData = $modules->getModuleConfigData($this->module);
$originalSchemaVersion = $configData['schemaVersion'] ?? null;
$configData['schemaVersion'] = 0;
$modules->saveModuleConfigData($this->module, $configData);
$database->exec("ALTER TABLE `$table` DROP COLUMN `exceptions`");
$columns = $database->query("SHOW COLUMNS FROM `$table`")->fetchAll(\PDO::FETCH_COLUMN);
$this->check('Setup: "exceptions" column was dropped', false, in_array('exceptions', $columns, true));
$this->callMethod('ensureSchemaUpToDate');
$columns = $database->query("SHOW COLUMNS FROM `$table`")->fetchAll(\PDO::FETCH_COLUMN);
$this->check('Self-heal: "exceptions" column was re-added', true, in_array('exceptions', $columns, true));
// restore the original schema version flag
$configData = $modules->getModuleConfigData($this->module);
if($originalSchemaVersion === null) {
unset($configData['schemaVersion']);
} else {
$configData['schemaVersion'] = $originalSchemaVersion;
}
$modules->saveModuleConfigData($this->module, $configData);
}
/**
* getBlankValue()/sanitizeValue(): a fresh value is an empty OpeningHours instance, and
* a non-OpeningHours value passed to sanitizeValue() is replaced with a blank one
*/
protected function testBlankAndSanitizeValue() {
$blank = $this->module->getBlankValue($this->page, $this->field);
$this->check('getBlankValue() returns an OpeningHours instance', true, $blank instanceof OpeningHours);
$sanitized = $this->module->sanitizeValue($this->page, $this->field, 'not an OpeningHours object');
$this->check('sanitizeValue() replaces a foreign value with a blank OpeningHours instance', true, $sanitized instanceof OpeningHours);
$same = $this->module->sanitizeValue($this->page, $this->field, $blank);
$this->check('sanitizeValue() keeps an existing OpeningHours instance as-is', true, $same === $blank);
}
/**
* A value set via the API round-trips correctly through ___sleepValue()/___wakeupValue()
* and a real page save/load cycle (including the JSON-encoded exceptions column)
*/
protected function testSaveAndLoadRoundtrip() {
$name = $this->field->name;
$value = $this->page->get($name);
$value->times = [
'mo' => [['start' => '08:00', 'finish' => '12:00']],
'tu' => [['start' => '08:00', 'finish' => '12:00']],
'we' => [],
'th' => [['start' => '08:00', 'finish' => '12:00']],
'fr' => [['start' => '08:00', 'finish' => '12:00']],
'sa' => [],
'su' => [],
'ho' => [],
];
$value->exceptions = [
[
'label' => 'Christmas',
'startDate' => '2026-12-24',
'endDate' => '2026-12-26',
'recurring' => true,
'closed' => true,
'times' => [],
],
];
$this->page->save($name);
// force a real reload from the database, bypassing any in-memory page cache
$this->wire()->pages->uncacheAll();
$reloaded = $this->wire()->pages->getById($this->page->id, ['cache' => false, 'getOne' => true])->getUnformatted($name);
$this->check('Roundtrip: value reloads as an OpeningHours instance', true, $reloaded instanceof OpeningHours);
$this->check('Roundtrip: Monday times are kept', [['start' => '08:00', 'finish' => '12:00']], $reloaded->times['mo'] ?? null);
$this->check('Roundtrip: Wednesday stays closed (empty)', [], $reloaded->times['we'] ?? null);
$this->check('Roundtrip: exception count', 1, count($reloaded->exceptions ?: []));
$this->check('Roundtrip: exception label', 'Christmas', $reloaded->exceptions[0]['label'] ?? null);
$this->check('Roundtrip: exception is marked closed', true, (bool) ($reloaded->exceptions[0]['closed'] ?? false));
// configuration fields (numberOftimes/timeformat/hideholiday) are made available on
// the value object by ___wakeupValue()
$this->check('Roundtrip: field config is exposed on the value (numberOftimes)', (string) $this->field->numberOftimes, $reloaded->numberOftimes);
}
/**
* The public render*() methods produce the expected markup for a real, saved value
*/
protected function testRenderMethods() {
$name = $this->field->name;
$value = $this->page->getUnformatted($name);
$list = $value->render();
$this->check('render(): contains an unordered list', true, stripos($list, '<ul') !== false);
$this->check('render(): Monday is shown', true, stripos($list, 'day-mo') !== false);
$combined = $value->renderCombinedDays();
$this->check('renderCombinedDays(): produces markup', true, stripos($combined, '<li') !== false);
$day = $value->renderDay('mo');
$this->check('renderDay(): returns the Monday time as a plain string', '08:00 - 12:00', $day, '*=');
$table = $value->renderTable();
$this->check('renderTable(): contains a <table>', true, stripos($table, '<table') !== false);
$dl = $value->renderDefinitionList();
$this->check('renderDefinitionList(): contains a <dl>', true, stripos($dl, '<dl') !== false);
$div = $value->renderDiv();
$this->check('renderDiv(): contains a <div>', true, stripos($div, '<div') !== false);
}
/**
* Schema.org JsonLD output is valid JSON and reflects the saved value
*/
protected function testJsonLD() {
$value = $this->page->getUnformatted($this->field->name);
$json = $value->renderjsonLDTimes();
$this->check('renderjsonLDTimes(): produces output', true, strlen($json) > 0);
$special = $value->getJsonLDSpecialOpeningHours(new \DateTime('2026-12-24'));
$this->check('getJsonLDSpecialOpeningHours(): returns an array for a date inside the exception', true, is_array($special) && count($special) > 0);
$specialHtml = $value->renderJsonLDSpecialOpeningHours(new \DateTime('2026-12-24'));
$decoded = null;
if(preg_match('/\{.*"@type"\s*:\s*"OpeningHoursSpecification".*\}/s', $specialHtml, $m)) {
$decoded = json_decode($m[0], true);
}
$this->check('renderJsonLDSpecialOpeningHours(): output is valid JSON', true, is_array($decoded));
}
/**
* Exceptions (holidays/company vacation) are matched correctly by date, and
* getStatusForDate() reflects them
*/
protected function testExceptionsAndStatus() {
$value = $this->page->getUnformatted($this->field->name);
$christmasDay = new \DateTime('2026-12-25');
$exception = $value->getExceptionForDate($christmasDay);
$this->check('getExceptionForDate(): the recurring Christmas exception matches 25.12.', true, is_array($exception));
$this->check('getExceptionForDate(): label matches', 'Christmas', $exception['label'] ?? null);
$status = $value->getStatusForDate($christmasDay);
$this->check('getStatusForDate(): closed on Christmas', true, (bool) ($status['closed'] ?? false));
$this->check('getStatusForDate(): flagged as an exception', true, (bool) ($status['exception'] ?? false));
$otherDay = new \DateTime('2026-06-15');
$this->check('getExceptionForDate(): no exception matches an unrelated date', null, $value->getExceptionForDate($otherDay));
$yearList = $value->getExceptionsForYear(2026);
$this->check('getExceptionsForYear(): the recurring exception is included', 1, count($yearList));
$rendered = $value->renderExceptionsForYear(2026);
$this->check('renderExceptionsForYear(): label is shown', true, stripos($rendered, 'Christmas') !== false);
}
/**
* The Inputfield's own overlap check (added for two exceptions with overlapping date
* ranges) produces a warning notice through the real notices system
*/
protected function testOverlapWarning() {
$inputfield = $this->inputfieldModule;
$before = count($this->wire()->notices);
$exceptions = [
['startDate' => '2026-12-24', 'endDate' => '2026-12-26', 'recurring' => true, 'closed' => true, 'label' => 'Christmas'],
['startDate' => '2026-12-25', 'endDate' => '2027-01-02', 'recurring' => false, 'closed' => true, 'label' => 'Company vacation'],
];
$sanitized = $this->callMethodOn($inputfield, 'sanitizeExceptionsInput', json_encode($exceptions));
$this->check('Overlap check: both exceptions are still kept (only warned about, not dropped)', 2, count($sanitized));
$this->check('Overlap check: a warning notice was added', true, count($this->wire()->notices) > $before);
}
/**
* ___processInput() correctly separates the per-day time inputs from the exceptions
* JSON, exactly as a real form submission from openinghours.js would
*/
protected function testFormProcessing() {
$inputfield = $this->wire()->modules->get('InputfieldOpeningHours');
$name = $this->field->name;
$inputfield->attr('name', $name);
$inputfield->attr('value', $this->module->getBlankValue($this->page, $this->field));
$data = [
$name . '-mo-0-start' => '09:00',
$name . '-mo-0-finish' => '13:00',
$name . '-exceptions' => json_encode([
['startDate' => '2026-05-01', 'endDate' => '2026-05-01', 'recurring' => true, 'closed' => true, 'label' => 'Labor Day'],
]),
];
$input = $this->wire(new WireInputData($data));
$inputfield->___processInput($input);
$times = $inputfield->value->times;
$exceptions = $inputfield->value->exceptions;
$this->check('processInput(): Monday start time was parsed', '09:00', $times[$name . '-mo-0-start'] ?? null);
$this->check('processInput(): exceptions were parsed separately from the day times', 1, count($exceptions ?? []));
$this->check('processInput(): exception label was sanitized through', 'Labor Day', $exceptions[0]['label'] ?? null);
}
/**
* The per-field configuration screen (Setup > Fields > this field > Input) contains the
* expected inputs, including the "How to" quick-start guide
*/
protected function testConfigInputfields() {
$inputfield = $this->wire()->modules->get('InputfieldOpeningHours');
$inputfield->attr('name', $this->field->name);
$inputfield->hasField = $this->field;
$form = $inputfield->getConfigInputfields();
$this->check('Config screen is available', true, $form instanceof InputfieldWrapper);
if(!$form instanceof InputfieldWrapper) return;
foreach(['numberOftimes', 'timeformat', 'tableheader', 'hideholiday'] as $configName) {
$this->check("Config screen: field $configName exists", true, $form->getChildByName($configName) instanceof Inputfield);
}
$markup = $form->render();
$this->check('Config screen: "How to" quick-start guide is present', true, stripos($markup, 'How to') !== false);
$this->check('Config screen: quick-start guide documents exceptions', true, stripos($markup, 'Exceptions') !== false);
}
/**
* Every translatable text across all three source files has a translation, for every
* language that ships one (mirrors the pattern used by SnowFallAnimation.test.php)
*/
protected function testTranslations() {
$modules = $this->wire()->modules;
$languages = $this->wire()->languages;
if(!$modules->isInstalled('LanguageSupport') || !$languages) {
$this->li('Translations: skipped - LanguageSupport is not installed');
return;
}
$path = $this->wire()->config->paths('FieldtypeOpeningHours');
$files = ['FieldtypeOpeningHours.module', 'InputfieldOpeningHours.module', 'OpeningHours.php'];
$tested = 0;
foreach($languages as $language) {
if($language->isDefault()) continue;
$name = $language->name;
$translator = $language->translator();
$hadFile = false;
$missing = [];
$totalTexts = 0;
foreach($files as $file) {
$fullPath = $path . $file;
if(!is_file($fullPath)) continue;
$texts = $this->getTranslatableTexts($fullPath);
$textdomain = $translator->filenameToTextdomain($fullPath);
if(!$translator->textdomainFileExists($textdomain)) continue;
$hadFile = true;
$totalTexts += count($texts);
foreach($texts as $text) {
$translation = $translator->getTranslationOrFalse($textdomain, $text);
if($translation === false || $translation === '') $missing[] = "$file: $text";
}
}
if(!$hadFile) {
$this->li("Translations: language '$name' has no translation file for this module - skipped");
continue;
}
$tested++;
$this->check("Translations ($name): all $totalTexts texts across the 3 files are translated", [], $missing);
}
if(!$tested) $this->li('Translations: no language with a translation file for this module');
}
/**
* LazyCron::everyDay -> cleanupExpiredExceptions(): expired, non-recurring exceptions are
* removed from every real page using this field type (not just the one field instance),
* while still-valid and recurring exceptions are left untouched. This exercises the real
* $pages->find() traversal and page save, which the stub-based unit tests cannot cover.
*/
protected function testLazyCronCleanupAcrossPages() {
$name = $this->field->name;
// primary test page: one expired, one still-valid (both non-recurring), and one
// recurring exception whose stored date is far in the past (recurring exceptions must
// never be removed, regardless of their stored startDate/endDate)
$value = $this->page->get($name);
$value->exceptions = [
['label' => 'Expired one-off', 'startDate' => $this->dateStr(-10), 'endDate' => $this->dateStr(-5), 'recurring' => false, 'closed' => true, 'times' => []],
['label' => 'Still valid', 'startDate' => $this->dateStr(5), 'endDate' => $this->dateStr(10), 'recurring' => false, 'closed' => true, 'times' => []],
['label' => 'Recurring', 'startDate' => '2020-01-01', 'endDate' => '2020-01-02', 'recurring' => true, 'closed' => true, 'times' => []],
];
$this->page->save($name);
// a second, independent real page on the same template, with only an expired exception
$this->extraPage = $this->createExtraTestPage();
if($this->extraPage) {
$extraValue = $this->module->getBlankValue($this->extraPage, $this->field);
$extraValue->exceptions = [
['label' => 'Expired on second page', 'startDate' => $this->dateStr(-20), 'endDate' => $this->dateStr(-15), 'recurring' => false, 'closed' => true, 'times' => []],
];
$this->extraPage->of(false);
$this->extraPage->set($name, $extraValue);
$this->extraPage->save($name);
}
// fire the same method LazyCron::everyDay hooks into, once - it scans every page using
// this field type in a single pass
$this->callMethod('cleanupExpiredExceptions', $this->wire(new HookEvent()));
$this->wire()->pages->uncacheAll();
$reloaded = $this->wire()->pages->getById($this->page->id, ['cache' => false, 'getOne' => true])->getUnformatted($name);
$labels = array_column($reloaded->exceptions ?: [], 'label');
$this->check('LazyCron cleanup: expired one-off exception was removed', false, in_array('Expired one-off', $labels, true));
$this->check('LazyCron cleanup: still-valid exception was kept', true, in_array('Still valid', $labels, true));
$this->check('LazyCron cleanup: recurring exception was kept regardless of its stored date', true, in_array('Recurring', $labels, true));
if($this->extraPage) {
$reloadedExtra = $this->wire()->pages->getById($this->extraPage->id, ['cache' => false, 'getOne' => true])->getUnformatted($name);
$this->check('LazyCron cleanup: expired exception on a second, independent page was also removed', 0, count($reloadedExtra->exceptions ?: []));
} else {
$this->li('LazyCron cleanup: second-page check skipped (could not create an additional test page)');
}
}
/**
* Security regression checks: a malicious time value stored on a page is escaped rather
* than injected verbatim into the admin markup, and a submitted exception label cannot
* smuggle in a prototype-pollution-style key (fe "__proto__", "constructor") or raw HTML.
*/
protected function testXssAndSecurityHardening() {
$name = $this->field->name;
// 1) a malicious value already stored in a day's time (fe from data entered before
// this fix, or edited directly in the database) must come out HTML-escaped when the
// admin edit screen renders the <input>, never as raw, executable markup
$payload = '"><script>alert(1)</script>';
$value = $this->module->getBlankValue($this->page, $this->field);
$times = $value->times;
$times['mo'][0]['start'] = $payload;
$value->times = $times;
$inputfield = $this->wire()->modules->get('InputfieldOpeningHours');
$inputfield->attr('name', $name);
$inputfield->set('numberOftimes', (string) $this->field->numberOftimes);
$inputfield->set('hideholiday', (int) $this->field->hideholiday);
$inputfield->attr('value', $value);
$html = $inputfield->render();
$this->check('Security: malicious time value is not rendered verbatim', false, strpos($html, '<script>alert(1)</script>') !== false);
$this->check('Security: malicious time value is HTML-escaped instead', true, strpos($html, htmlspecialchars($payload, ENT_QUOTES)) !== false);
// 2) a submitted exception label with disallowed keys and an HTML payload is
// sanitized: unrecognized keys (fe "__proto__"/"constructor") are dropped entirely,
// and the remaining text has any markup stripped
$maliciousJson = json_encode([[
'startDate' => $this->dateStr(30),
'endDate' => $this->dateStr(30),
'recurring' => true,
'closed' => true,
'label' => [
'default' => '<script>alert(1)</script>',
'__proto__' => 'evil',
'constructor' => 'evil2',
],
]]);
$sanitized = $this->callMethodOn($this->inputfieldModule, 'sanitizeExceptionsInput', $maliciousJson);
$this->check('Security: exactly one exception survives sanitization', 1, count($sanitized));
$label = $sanitized[0]['label'] ?? null;
$this->check('Security: label is an array (multi-language capable)', true, is_array($label));
$this->check('Security: "__proto__" key is dropped from the label', false, is_array($label) && array_key_exists('__proto__', $label));
$this->check('Security: "constructor" key is dropped from the label', false, is_array($label) && array_key_exists('constructor', $label));
$this->check('Security: markup is stripped from the label text', false, is_array($label) && stripos($label['default'] ?? '', '<script') !== false);
// end-to-end: the same sanitized exception, once rendered as part of a real page's
// exception list, must not leak raw markup into the page either
$pageValue = $this->page->get($name);
$pageValue->exceptions = $sanitized;
$this->page->save($name);
$rendered = $this->page->getUnformatted($name)->renderExceptionsForYear((int) $this->dateStr(30, 'Y'));
$this->check('Security: rendered exception list does not contain raw <script> markup', false, stripos($rendered, '<script>alert(1)</script>') !== false);
}
/**
* Field context overrides: numberOftimes (and timeformat/tableheader/hideholiday, see
* getConfigAllowContext()) can be overridden per-template under Setup > Fields > this
* field > "used in template X" > Input. A real page on a template with such an override
* must pick up the overridden value, while a page on a different template keeps the
* field's own (non-overridden) default - this is ProcessWire's fieldgroup-context
* mechanism, which the stub-based unit tests have no way of exercising.
*/
protected function testFieldContextOverride() {
$fields = $this->wire()->fields;
$setup = $this->createContextTemplateAndPage();
if(!$setup) {
$this->li('Field context override: skipped (could not create a temporary fieldgroup/template/page)');
return;
}
[$fieldgroup, $template, $page] = $setup;
$this->contextFieldgroup = $fieldgroup;
$this->contextTemplate = $template;
$this->contextPage = $page;
$name = $this->field->name;
$originalNumberOfTimes = $this->field->numberOftimes;
$overrideValue = ((int) $originalNumberOfTimes) + 1;
// Fieldgroup::getField($name, true) - which getFieldContext() calls - always returns a
// CLONE with Field::flagFieldgroupContext already set (see ProcessWire core). Mutating
// that clone and saving it is exactly how the field's own "used in template X" config
// screen applies a per-template override; the base $this->field is never touched.
$contextField = $fieldgroup->getFieldContext($name);
$contextField->set('numberOftimes', $overrideValue);
$fields->saveFieldgroupContext($contextField, $fieldgroup);
$resolved = $fieldgroup->getFieldContext($name);
$this->check('Field context: getFieldContext() reflects the override', (string) $overrideValue, (string) $resolved->numberOftimes);
$this->check('Field context: the base field itself is unaffected', (string) $originalNumberOfTimes, (string) $this->field->numberOftimes);
// Page::getField()/PageValues::getField() (ProcessWire core) only resolves the
// fieldgroup context when output formatting is ON for that page - with of(false)
// it deliberately falls back to the plain, non-context field. So unlike the rest of
// this test suite (which reads/writes with of(false) to get a live, mutable value),
// checking the *context* resolution itself requires of(true) here.
$pageOf = $page->of();
$page->of(true);
$contextField = $page->getField($name);
$page->of($pageOf);
$this->check('Field context: a real page on the overriding template picks up the override', (string) $overrideValue, (string) $contextField->numberOftimes);
$originalPageOf = $this->page->of();
$this->page->of(true);
$originalPageField = $this->page->getField($name);
$this->page->of($originalPageOf);
$this->check('Field context: the original page (different template) keeps the field default', (string) $originalNumberOfTimes, (string) $originalPageField->numberOftimes);
}
/**
* Real multi-language formatting: switching the active user's language changes which
* per-language timeformat FieldtypeOpeningHours::formatValue() applies, exactly as a
* multi-language frontend would show it to visitors of that language.
*/
protected function testMultiLanguageFormatting() {
$modules = $this->wire()->modules;
$languages = $this->wire()->languages;
if(!$modules->isInstalled('LanguageSupport') || !$languages || count($languages) <= 1) {
$this->li('Multi-language formatting: skipped - LanguageSupport with more than one language is not installed');
return;
}
$language = null;
foreach($languages as $candidate) {
if(!$candidate->isDefault()) {
$language = $candidate;
break;
}
}
if(!$language) {
$this->li('Multi-language formatting: skipped - no non-default language found');
return;
}
// remembered here (before any check() call, which throws on failure) so finish() can
// always remove this again, even if a check below fails
$this->languageForFormatTest = $language;
$name = $this->field->name;
// give this language its own timeformat ("%r" = 12-hour with AM/PM, fe "08:00:00 AM"),
// different from the field's own default ("%R" = 24-hour, fe "08:00")
$this->field->set('timeformat' . $language->id, '%r');
$this->field->save();
$value = $this->page->get($name);
$times = $value->times;
$times['mo'][0] = ['start' => '08:00', 'finish' => '12:00'];
$value->times = $times;
$this->page->save($name);
$this->languageChanged = $languages->setLanguage($language);
try {
$formatted = $this->page->getFormatted($name);
$mondayStart = $formatted->times['mo'][0]['start'] ?? null;
$this->check(
"Multi-language formatting ({$language->name}): uses that language's own timeformat (12-hour, fe \"08:00:00 AM\")",
true,
(bool) preg_match('/^\d{1,2}:\d{2}:\d{2}\s?[AP]M$/i', (string) $mondayStart)
);
} finally {
if($this->languageChanged) {
$languages->unsetLanguage();
$this->languageChanged = false;
}
}
// back on the default language, the field's own (non-per-language) timeformat applies
$formattedDefault = $this->page->getFormatted($name);
$mondayStartDefault = $formattedDefault->times['mo'][0]['start'] ?? null;
$this->check(
'Multi-language formatting (default language): uses the field\'s own timeformat (24-hour, fe "08:00")',
true,
(bool) preg_match('/^\d{2}:\d{2}$/', (string) $mondayStartDefault)
);
}
// ---------------------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------------------------
/**
* Create a temporary fieldgroup (containing the shared test field), template and one
* unpublished page for testFieldContextOverride(). Returns [$fieldgroup, $template, $page]
* or null (logging why) if any step fails - fe because the shared parent page's template
* restricts which child templates are allowed under it.
*/
protected function createContextTemplateAndPage() {
try {
$unique = 'wtoh' . time() . mt_rand(1000, 9999);
$fieldgroup = $this->wire(new Fieldgroup());
$fieldgroup->name = $unique . '_fg';
$fieldgroup->add($this->field);
$fieldgroup->save();
$template = $this->wire(new Template());
$template->name = $unique . '_tpl';
$template->fieldgroup = $fieldgroup;
$template->noParents = 0;
$template->parentTemplates = [];
$template->childTemplates = [];
$template->save();
$page = $this->wire(new Page());
$page->template = $template;
$page->parent = $this->page->parent;
$page->name = $unique . '-page';
$page->title = 'WireTest OpeningHours context';
$page->addStatus(Page::statusUnpublished);
$page->save();
return [$fieldgroup, $template, $page];
} catch(\Throwable $e) {
$this->li('Could not set up a temporary context template/page (' . $e->getMessage() . ')');
return null;
}
}
/**
* A "Y-m-d" date string a given number of days from today (negative for the past), or in
* a custom format when $format is given (fe "Y" to get just the year).
*/
protected function dateStr($offsetDays, $format = 'Y-m-d') {
$sign = $offsetDays >= 0 ? '+' : '';
return (new \DateTime('today'))->modify($sign . $offsetDays . ' days')->format($format);
}
/**
* Create a second, independent real page on the same template as the shared WireTests
* test page (as a sibling under the same parent), for tests that need to prove behavior
* across more than one page. Returns null (and logs why) if this isn't possible - fe
* because the template's family settings don't allow another child under that parent -
* so the calling test can fall back to checking a single page only.
*/
protected function createExtraTestPage() {
try {
$child = $this->wire(new Page());
$child->template = $this->page->template;
$child->parent = $this->page->parent;
$child->name = 'wtest-openinghours-cleanup-' . time() . '-' . mt_rand(1000, 9999);
$child->title = 'WireTest OpeningHours cleanup';
$child->addStatus(Page::statusUnpublished);
$child->save();
return $child;
} catch(\Throwable $e) {
$this->li('Could not create a second test page (' . $e->getMessage() . ') - some checks will run against a single page only');
return null;
}
}
/**
* Get all texts of a file that are translatable with $this->_('...')
*/
protected function getTranslatableTexts($file) {
$texts = [];
if(preg_match_all('/\$this->_\(\s*\'((?:[^\'\\\\]|\\\\.)*)\'\s*\)/', (string) file_get_contents($file), $matches)) {
foreach($matches[1] as $text) $texts[] = stripcslashes($text);
}
return array_values(array_unique($texts));
}
/**
* Call a protected/private method on $this->module via reflection
*/
protected function callMethod($name, ...$args) {
return $this->callMethodOn($this->module, $name, ...$args);
}
/**
* Call a protected/private method on the given object via reflection
*/
protected function callMethodOn($object, $name, ...$args) {
$method = new \ReflectionMethod($object, $name);
if(PHP_VERSION_ID < 80100) $method->setAccessible(true);
return $method->invoke($object, ...$args);
}
}