-
Notifications
You must be signed in to change notification settings - Fork 8
/
TestingFramework.php
2152 lines (1916 loc) · 76.4 KB
/
TestingFramework.php
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace OliverKlee\Oelib\Testing;
use Doctrine\DBAL\Driver\ResultStatement;
use OliverKlee\Oelib\Authentication\FrontEndLoginManager;
use OliverKlee\Oelib\DataStructures\Collection;
use OliverKlee\Oelib\FrontEnd\UserWithoutCookies;
use OliverKlee\Oelib\Mapper\FrontEndUserMapper;
use OliverKlee\Oelib\Mapper\MapperRegistry;
use OliverKlee\Oelib\Model\FrontEndUserGroup;
use Psr\Log\NullLogger;
use TYPO3\CMS\Core\Configuration\SiteConfiguration;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Exception\Page\PageNotFoundException;
use TYPO3\CMS\Core\Http\Uri;
use TYPO3\CMS\Core\Information\Typo3Version;
use TYPO3\CMS\Core\Localization\Locales;
use TYPO3\CMS\Core\Routing\PageArguments;
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
use TYPO3\CMS\Core\TypoScript\TemplateService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\RootlineUtility;
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
/**
* This class provides various functions to handle dummy records in unit tests.
*/
final class TestingFramework
{
/**
* @var positive-int
*/
private const AUTO_INCREMENT_THRESHOLD_WITHOUT_ROOTLINE_CACHE = 100;
/**
* all system table names to which this instance of the testing framework
* has access
*
* @var array<int, non-empty-string>
*/
private const ALLOWED_SYSTEM_TABLES = [
'be_users',
'fe_groups',
'fe_users',
'pages',
'sys_template',
'tt_content',
'be_groups',
'sys_file',
'sys_file_collection',
'sys_file_reference',
'sys_category',
'sys_category_record_mm',
];
/**
* @var non-empty-string
*/
private const FAKE_FRONTEND_DOMAIN_NAME = 'typo3-test.dev';
/**
* @var non-empty-string
*/
private const SITE_IDENTIFIER = 'testing-framework';
/**
* cache for the results of hasTableColumn with the column names as keys and
* the SHOW COLUMNS field information (in an array) as values
*
* @var array<string, array<string, array<string, string>>>
*/
private static $tableColumnCache = [];
/**
* @var array<non-empty-string, array<string, string|int|null>> cache for the results of existsTable with the
* table names as keys and the table SHOW STATUS information (in an array) as values
*/
private static $tableNameCache = [];
/**
* @var bool
*/
private $databaseInitialized = false;
/**
* prefix of the extension for which this instance of the testing framework
* was instantiated (e.g. "tx_seminars")
*
* @var non-empty-string
*/
private $tablePrefix;
/**
* prefixes of additional extensions to which this instance of the testing
* framework has access (e.g. "tx_seminars")
*
* @var string[]
*/
private $additionalTablePrefixes = [];
/**
* all own DB table names to which this instance of the testing framework has access
*
* @var array<int, non-empty-string>
*/
private $ownAllowedTables = [];
/**
* all additional DB table names to which this instance of the testing framework has access
*
* @var string[]
*/
private $additionalAllowedTables = [];
/**
* all "dirty" non-system tables (i.e., all tables that were used for testing
* and need to be cleaned up)
*
* @var array<string, non-empty-string>
*/
private $dirtyTables = [];
/**
* all "dirty" system tables (i.e. all tables that were used for testing and
* need to be cleaned up)
*
* @var array<string, non-empty-string>
*/
private $dirtySystemTables = [];
/**
* sorting values of all relation tables
*
* @var array<string, array<int, int>>
*/
private $relationSorting = [];
/**
* The number of unusable UIDs after the maximum UID in a table before the auto increment value will be reset by
* resetAutoIncrementLazily.
*
* This value needs to be high enough so that no two page UIDs will be the same within on request as the local
* root-line cache of TYPO3 CMS otherwise might create false cache hits, causing failures for unit tests relying on
* the root line.
*
* @see https://bugs.oliverklee.com/show_bug.cgi?id=5011
*
* @var int
*/
private $resetAutoIncrementThreshold = 0;
/**
* the names of the created dummy files relative to the upload folder of the extension to test
*
* @var array<string, non-empty-string>
*/
private $dummyFiles = [];
/**
* the names of the created dummy folders relative to the upload folder of the extension to test
*
* @var array<string, non-empty-string>
*/
private $dummyFolders = [];
/**
* the absolute path to the upload folder of the extension to test (with the trailing slash)
*
* @var non-empty-string
*/
private $uploadFolderPath;
/**
* whether a fake front end has been created
*
* @var bool
*/
private $hasFakeFrontEnd = false;
/**
* hook objects for this class
*
* @var array<int, object>
*/
private static $hooks = [];
/**
* whether the hooks in self::hooks have been retrieved
*
* @var bool
*/
private static $hooksHaveBeenRetrieved = false;
/**
* @var CacheNullifyer
*/
private $cacheNullifyer;
/**
* @var array<string, string|bool|null>|null
*/
private $serverVariablesBackup = null;
/**
* This testing framework can be instantiated for one extension at a time.
* Example: In your testcase, you'll have something similar to this line of code:
*
* `$this->subject = new TestingFramework('tx_seminars');`
*
* The parameter you provide is the prefix of the table names of that particular
* extension. Like this, we ensure that the testing framework creates and
* deletes records only on table with this prefix.
*
* If you need dummy records on tables of multiple extensions, you will have to
* instantiate the testing framework multiple times (once per extension).
*
* Instantiating this class sets all core caches in order to avoid errors about not registered caches.
*
* @param non-empty-string $tablePrefix table name prefix of the extension
* for this instance of the testing framework
* @param array<int, string> $additionalTablePrefixes additional table name prefixes of the extensions for which
* this instance of the testing framework should be used, may be empty
*/
public function __construct(string $tablePrefix, array $additionalTablePrefixes = [])
{
$this->tablePrefix = $tablePrefix;
$this->additionalTablePrefixes = $additionalTablePrefixes;
$this->uploadFolderPath = Environment::getPublicPath() . '/typo3temp/' . $this->tablePrefix . '/';
$this->cacheNullifyer = new CacheNullifyer();
$this->cacheNullifyer->setAllCoreCaches();
}
private function initializeDatabase(): void
{
if ($this->databaseInitialized) {
return;
}
$this->createListOfOwnAllowedTables();
$this->createListOfAdditionalAllowedTables();
$this->determineAndSetAutoIncrementThreshold();
$this->databaseInitialized = true;
}
/**
* Determines a good value for the auto increment threshold and sets it.
*/
private function determineAndSetAutoIncrementThreshold(): void
{
$this->setResetAutoIncrementThreshold(self::AUTO_INCREMENT_THRESHOLD_WITHOUT_ROOTLINE_CACHE);
}
/**
* Creates a new dummy record for unit tests.
*
* If no record data for the new array is given, an empty record will be
* created. It will only contain a valid UID and the "is_dummy_record" flag
* will be set to 1.
*
* Should there be any problem creating the record (wrong table name or a
* problem with the database), 0 instead of a valid UID will be returned.
*
* @param non-empty-string $table the name of the table on which the record should be created
* @param array<string, string|int|bool> $recordData data to save in the new record, may be empty,
* but must not contain the key "uid"
*
* @return int the UID of the new record, will be > 0
*
* @throws \InvalidArgumentException
*/
public function createRecord(string $table, array $recordData = []): int
{
$this->initializeDatabase();
if (!$this->isNoneSystemTableNameAllowed($table)) {
throw new \InvalidArgumentException('The table name "' . $table . '" is not allowed.', 1331489666);
}
if (isset($recordData['uid'])) {
throw new \InvalidArgumentException('The column "uid" must not be set in $recordData.', 1331489678);
}
return $this->createRecordWithoutTableNameChecks($table, $recordData);
}
/**
* Creates a new dummy record for unit tests without checks for the table name.
*
* If no record data for the new array is given, an empty record will be created.
* It will only contain a valid UID and the "is_dummy_record" flag will be set to 1.
*
* Should there be any problem creating the record (wrong table name or a
* problem with the database), 0 instead of a valid UID will be returned.
*
* @param non-empty-string $table the name of the table on which the record should be created
* @param array<string, string|int|bool> $rawData data to save, may be empty, but must not contain the key "uid"
*
* @return int the UID of the new record, will be > 0
*/
private function createRecordWithoutTableNameChecks(string $table, array $rawData): int
{
$this->initializeDatabase();
$dataToInsert = $this->normalizeDatabaseRow($rawData);
$dummyColumnName = $this->getDummyColumnName($table);
$dataToInsert[$dummyColumnName] = 1;
$connection = $this->getConnectionForTable($table);
$connection->insert($table, $dataToInsert);
$this->markTableAsDirty($table);
return (int)$connection->lastInsertId($table);
}
/**
* Normalizes the types in the given data so that the data con be inserted into a DB.
*
* @param array<string, string|int|bool|float> $rawData
*
* @return array<string, string|int|float>
*/
private function normalizeDatabaseRow(array $rawData): array
{
$dataToInsert = [];
foreach ($rawData as $key => $value) {
$dataToInsert[$key] = \is_bool($value) ? (int)$value : $value;
}
return $dataToInsert;
}
/**
* @param non-empty-string $tableName
*
* @return Connection
*/
private function getConnectionForTable(string $tableName): Connection
{
return $this->getConnectionPool()->getConnectionForTable($tableName);
}
/**
* @param non-empty-string $tableName
*
* @return QueryBuilder
*/
private function getQueryBuilderForTable(string $tableName): QueryBuilder
{
return $this->getConnectionPool()->getQueryBuilderForTable($tableName);
}
/**
* @return ConnectionPool
*/
private function getConnectionPool(): ConnectionPool
{
return GeneralUtility::makeInstance(ConnectionPool::class);
}
/**
* Creates a front-end page on the given page, and provides it with the page UID as slug.
*
* @return int the UID of the new page, will be > 0
*/
public function createFrontEndPage(int $parentPageUid = 0): int
{
$uid = $this->createGeneralPageRecord(1, $parentPageUid, []);
$this->changeRecord('pages', $uid, ['slug' => '/' . $uid]);
return $uid;
}
/**
* Creates a system folder on the page with the UID given by the first
* parameter $parentId.
*
* @param int $parentId
* UID of the page on which the system folder should be created
*
* @return int the UID of the new system folder, will be > 0
*/
public function createSystemFolder(int $parentId = 0): int
{
return $this->createGeneralPageRecord(254, $parentId, []);
}
/**
* Creates a page record with the document type given by the first parameter
* $documentType.
*
* The record will be created on the page with the UID given by the second
* parameter $parentId.
*
* @param int $documentType document type of the record to create, must be > 0
* @param int $parentId UID of the page on which the record should be created
* @param array<string, string|int|bool> $recordData data to save in the record, may be empty,
* but must not contain the keys "uid", "pid" or "doktype"
*
* @return int the UID of the new record, will be > 0
*
* @throws \InvalidArgumentException
*/
private function createGeneralPageRecord(int $documentType, int $parentId, array $recordData): int
{
if (isset($recordData['uid'])) {
throw new \InvalidArgumentException('The column "uid" must not be set in $recordData.', 1331489697);
}
if (isset($recordData['pid'])) {
throw new \InvalidArgumentException('The column "pid" must not be set in $recordData.', 1331489703);
}
if (isset($recordData['doktype'])) {
throw new \InvalidArgumentException('The column "doktype" must not be set in $recordData.', 1331489708);
}
$completeRecordData = $recordData;
$completeRecordData['pid'] = $parentId;
$completeRecordData['doktype'] = $documentType;
return $this->createRecordWithoutTableNameChecks('pages', $completeRecordData);
}
/**
* Creates a template on the page with the UID given by the first parameter $pageId.
*
* @param int $pageId
* UID of the page on which the template should be created, must be > 0
* @param array<string, string|int|bool> $recordData data to save, may be empty,
* but must not contain the keys "uid" or "pid"
*
* @return int the UID of the new template, will be > 0
*
* @throws \InvalidArgumentException
*/
public function createTemplate(int $pageId, array $recordData = []): int
{
if ($pageId <= 0) {
throw new \InvalidArgumentException('$pageId must be > 0.', 1331489774);
}
if (isset($recordData['uid'])) {
throw new \InvalidArgumentException('The column "uid" must not be set in $recordData.', 1331489769);
}
if (isset($recordData['pid'])) {
throw new \InvalidArgumentException('The column "pid" must not be set in $recordData.', 1331489764);
}
$completeRecordData = $recordData;
$completeRecordData['pid'] = $pageId;
return $this->createRecordWithoutTableNameChecks('sys_template', $completeRecordData);
}
/**
* Creates a FE user group.
*
* @param array<string, string|int|bool> $recordData data to save, may be empty, but must not contain the key "uid"
*
* @return int the UID of the new user group, will be > 0
*
* @throws \InvalidArgumentException
*/
public function createFrontEndUserGroup(array $recordData = []): int
{
if (isset($recordData['uid'])) {
throw new \InvalidArgumentException('The column "uid" must not be set in $recordData.', 1331489807);
}
return $this->createRecordWithoutTableNameChecks('fe_groups', $recordData);
}
/**
* Creates a FE user record.
*
* @param string|int $frontEndUserGroups
* comma-separated list of UIDs of the user groups to which the new user belongs, each must be > 0,
* may contain spaces, if empty a new FE user group will be created
* @param array<string, string|int|bool> $recordData data to save, may be empty,
* but must not contain the keys "uid" or "usergroup"
*
* @return int the UID of the new FE user, will be > 0
*
* @throws \InvalidArgumentException
*/
public function createFrontEndUser($frontEndUserGroups = '', array $recordData = []): int
{
$frontEndUserGroupsWithoutSpaces = str_replace(' ', '', (string)$frontEndUserGroups);
if ($frontEndUserGroupsWithoutSpaces === '') {
$frontEndUserGroupsWithoutSpaces = (string)$this->createFrontEndUserGroup();
}
$groupsCheckResult = \preg_match('/^(?:[1-9]+\\d*,?)+$/', $frontEndUserGroupsWithoutSpaces);
if (!\is_int($groupsCheckResult) || $groupsCheckResult === 0) {
throw new \InvalidArgumentException(
'$frontEndUserGroups must contain a comma-separated list of UIDs. Each UID must be > 0.',
1331489824
);
}
if (isset($recordData['uid'])) {
throw new \InvalidArgumentException('The column "uid" must not be set in $recordData.', 1331489842);
}
if (isset($recordData['usergroup'])) {
throw new \InvalidArgumentException('The column "usergroup" must not be set in $recordData.', 1331489846);
}
$completeRecordData = $recordData;
$completeRecordData['usergroup'] = $frontEndUserGroupsWithoutSpaces;
return $this->createRecordWithoutTableNameChecks('fe_users', $completeRecordData);
}
/**
* Creates and logs in an FE user.
*
* @param string|int $frontEndUserGroups comma-separated list of UIDs of the user groups to which the user belongs,
* each must be > 0, may contain spaces; if empty a new front-end user group is created
* @param array<string, string|int|bool> $recordData data to save, may be empty,
* but must not contain the keys "uid" or "usergroup"
*
* @return int the UID of the new FE user, will be > 0
*/
public function createAndLoginFrontEndUser($frontEndUserGroups = '', array $recordData = []): int
{
$frontEndUserUid = $this->createFrontEndUser($frontEndUserGroups, $recordData);
$this->loginFrontEndUser($frontEndUserUid);
return $frontEndUserUid;
}
/**
* Creates a BE user record.
*
* @param array<string, string|int|bool> $recordData data to save, may be empty, but must not contain the key "uid"
*
* @return int the UID of the new BE user, will be > 0
*/
public function createBackEndUser(array $recordData = []): int
{
if (isset($recordData['uid'])) {
throw new \InvalidArgumentException('The column "uid" must not be set in $recordData.', 1331489905);
}
return $this->createRecordWithoutTableNameChecks('be_users', $recordData);
}
/**
* Changes an existing dummy record and stores the new data for this
* record. Only fields that get new values in $recordData will be changed,
* everything else will stay untouched.
*
* The array with the new recordData must contain at least one entry, but
* must not contain a new UID for the record. If you need to change the UID,
* you have to create a new record!
*
* @param non-empty-string $table the name of the table
* @param int $uid the UID of the record to change
* @param array<string, string|int|bool|float> $rawData the values to be changed as key-value pairs
*
* @throws \InvalidArgumentException
* @throws \BadMethodCallException
*/
public function changeRecord(string $table, int $uid, array $rawData): void
{
$this->initializeDatabase();
$dummyColumnName = $this->getDummyColumnName($table);
if (!$this->isTableNameAllowed($table)) {
throw new \InvalidArgumentException(
'The table "' . $table . '" is not on the lists with allowed tables.',
1331489997
);
}
if ($uid === 0) {
throw new \InvalidArgumentException('The parameter $uid must not be zero.', 1331490003);
}
if (empty($rawData)) {
throw new \InvalidArgumentException('The array with the new record data must not be empty.', 1331490008);
}
if (isset($rawData['uid'])) {
throw new \InvalidArgumentException(
'The parameter $recordData must not contain changes to the UID of a record.',
1331490017
);
}
if (isset($rawData[$dummyColumnName])) {
throw new \InvalidArgumentException(
'The parameter $recordData must not contain changes to the field "' . $dummyColumnName .
'". It is impossible to convert a dummy record into a regular record.',
1331490024
);
}
if (!$this->existsRecordWithUid($table, $uid)) {
throw new \BadMethodCallException(
'There is no record with UID ' . $uid . ' on table "' . $table . '".',
1331490033
);
}
$dataToSave = $this->normalizeDatabaseRow($rawData);
$this->getConnectionForTable($table)->update($table, $dataToSave, ['uid' => $uid, $dummyColumnName => 1]);
}
/**
* Creates a relation between two records on different tables (so called
* m:n relation).
*
* @param non-empty-string $table name of the m:n table to which the record should be added
* @param int $uidLocal UID of the local table, must be > 0
* @param int $uidForeign UID of the foreign table, must be > 0
*
* @throws \InvalidArgumentException
*/
public function createRelation(string $table, int $uidLocal, int $uidForeign): void
{
$this->initializeDatabase();
if (!$this->isNoneSystemTableNameAllowed($table)) {
throw new \InvalidArgumentException('The table name "' . $table . '" is not allowed.', 1331490358);
}
if ($uidLocal <= 0) {
throw new \InvalidArgumentException('$uidLocal must be > 0, but is: ' . $uidLocal, 1331490370);
}
if ($uidForeign <= 0) {
throw new \InvalidArgumentException('$uidForeign must be > 0, but is: ' . $uidForeign, 1331490378);
}
$this->markTableAsDirty($table);
$recordData = [
'uid_local' => $uidLocal,
'uid_foreign' => $uidForeign,
'sorting' => $this->getRelationSorting($table, $uidLocal),
$this->getDummyColumnName($table) => 1,
];
$this->getConnectionForTable($table)->insert($table, $recordData);
}
/**
* Creates a relation between two records based on the rules defined in TCA
* regarding the relation.
*
* @param non-empty-string $tableName name of the table from which a relation should be created
* @param int $uidLocal UID of the record in the local table, must be > 0
* @param int $uidForeign UID of the record in the foreign table, must be > 0
* @param non-empty-string $columnName name of the column in which the relation counter should be updated
*
* @throws \InvalidArgumentException
* @throws \BadMethodCallException
*/
public function createRelationAndUpdateCounter(
string $tableName,
int $uidLocal,
int $uidForeign,
string $columnName
): void {
$this->initializeDatabase();
if (!$this->isTableNameAllowed($tableName)) {
throw new \InvalidArgumentException('The table name "' . $tableName . '" is not allowed.', 1331490419);
}
if ($uidLocal <= 0) {
throw new \InvalidArgumentException(
'$uidLocal must be > 0, but actually is "' . $uidLocal . '"',
1331490425
);
}
if ($uidForeign <= 0) {
throw new \InvalidArgumentException(
'$uidForeign must be > 0, but actually is "' . $uidForeign . '"',
1331490429
);
}
$tca = $this->getTcaForTable($tableName);
$relationConfiguration = $tca['columns'][$columnName];
if (!isset($relationConfiguration['config']['MM']) || ($relationConfiguration['config']['MM'] === '')) {
throw new \BadMethodCallException(
'The column ' . $columnName . ' in the table ' . $tableName .
' is not configured to contain m:n relations using a m:n table.',
1331490434
);
}
if (isset($relationConfiguration['config']['MM_opposite_field'])) {
// Switches the order of $uidForeign and $uidLocal as the relation
// is the reverse part of a bidirectional relation.
$this->createRelationAndUpdateCounter(
$relationConfiguration['config']['foreign_table'],
$uidForeign,
$uidLocal,
$relationConfiguration['config']['MM_opposite_field']
);
} else {
$this->createRelation(
$relationConfiguration['config']['MM'],
$uidLocal,
$uidForeign
);
}
$this->increaseRelationCounter($tableName, $uidLocal, $columnName);
}
/**
* Returns the TCA for a certain table.
*
* @param non-empty-string $tableName the table name to look up
*
* @return array<array<string, mixed>> associative array with the TCA description for this table
*/
private function getTcaForTable(string $tableName): array
{
if (!isset($GLOBALS['TCA'][$tableName])) {
throw new \BadMethodCallException('The table "' . $tableName . '" has no TCA.', 1569701919);
}
return $GLOBALS['TCA'][$tableName];
}
/**
* Deletes all dummy records that have been added through this framework.
* For this, all records with the "is_dummy_record" flag set to 1 will be
* deleted from all tables that have been used within this instance of the
* testing framework.
*
* If you set $performDeepCleanUp to TRUE, it will go through ALL tables to
* which the current instance of the testing framework has access. Please
* consider well, whether you want to do this as it's a huge performance
* issue.
*
* @param bool $performDeepCleanUp whether a deep clean up should be performed, may be empty
*/
public function cleanUp(bool $performDeepCleanUp = false): void
{
$this->cleanUpDatabase($performDeepCleanUp);
$this->cleanUpWithoutDatabase();
}
private function cleanUpDatabase(bool $performDeepCleanUp = false): void
{
$this->initializeDatabase();
$this->cleanUpTableSet(false, $performDeepCleanUp);
$this->cleanUpTableSet(true, $performDeepCleanUp);
}
/**
* Cleanup without deleting dummy records. Use this method instead of cleanUp() for better performance when
* another testing framework (e.g., nimut/testing-framework) already takes care of cleaning up old database records.
*/
public function cleanUpWithoutDatabase(): void
{
$this->deleteAllDummyFoldersAndFiles();
$this->discardFakeFrontEnd();
WritableEnvironment::restoreCurrentScript();
GeneralUtility::flushInternalRuntimeCaches();
if (\is_array($this->serverVariablesBackup)) {
$GLOBALS['_SERVER'] = $this->serverVariablesBackup;
$this->serverVariablesBackup = null;
}
foreach ($this->getHooks() as $hook) {
if (method_exists($hook, 'cleanUp')) {
$hook->cleanUp($this);
}
}
RootlineUtility::purgeCaches();
}
/**
* Deletes a set of records that have been added through this framework for
* a set of tables (either the test tables or the allowed system tables).
* For this, all records with the "is_dummy_record" flag set to 1 will be
* deleted from all tables that have been used within this instance of the
* testing framework.
*
* If you set $performDeepCleanUp to TRUE, it will go through ALL tables to
* which the current instance of the testing framework has access. Please
* consider well, whether you want to do this as it's a huge performance
* issue.
*
* @param bool $useSystemTables whether to clean up the system tables (TRUE) or the non-system test tables (FALSE)
* @param bool $performDeepCleanUp whether a deep clean up should be performed, may be empty
*/
private function cleanUpTableSet(bool $useSystemTables, bool $performDeepCleanUp): void
{
if ($useSystemTables) {
$tablesToCleanUp = $performDeepCleanUp ? self::ALLOWED_SYSTEM_TABLES : $this->dirtySystemTables;
} else {
$tablesToCleanUp = $performDeepCleanUp ? $this->ownAllowedTables : $this->dirtyTables;
}
foreach ($tablesToCleanUp as $currentTable) {
$dummyColumnName = $this->getDummyColumnName($currentTable);
if (!$this->tableHasColumn($currentTable, $dummyColumnName)) {
continue;
}
// Runs a delete query for each allowed table. A "one-query-deletes-them-all" approach was tested,
// but we didn't find a working solution for that.
$this->getConnectionForTable($currentTable)->delete($currentTable, [$dummyColumnName => 1]);
$this->resetAutoIncrementLazily($currentTable);
}
$this->dirtyTables = [];
}
/**
* Checks whether a table has a column "uid".
*
* @param non-empty-string $table the name of the table to check
*
* @return bool
*/
private function tableHasColumnUid(string $table): bool
{
return $this->tableHasColumn($table, 'uid');
}
/**
* Checks whether a table has a column with a particular name.
*
* @param non-empty-string $table the name of the table to check
* @param string $column the column name to check
*
* @return bool
*/
private function tableHasColumn(string $table, string $column): bool
{
if ($column === '') {
return false;
}
$this->retrieveColumnsForTable($table);
return isset(self::$tableColumnCache[$table][$column]);
}
/**
* Retrieves and caches the column data for the table $table.
*
* If the column data for that table already is cached, this function does
* nothing.
*
* @param non-empty-string $table the name of the table for which the column names should be retrieved
*/
private function retrieveColumnsForTable(string $table): void
{
if (isset(self::$tableColumnCache[$table])) {
return;
}
$connection = $this->getConnectionForTable($table);
$query = 'SHOW FULL COLUMNS FROM `' . $table . '`';
if (\method_exists($connection, 'executeQuery')) {
$queryResult = $connection->executeQuery($query);
} else {
$queryResult = $connection->query($query);
}
$columns = [];
if (\method_exists($queryResult, 'fetchAllAssociative')) {
/** @var array<string, string> $fieldRow */
foreach ($queryResult->fetchAllAssociative() as $fieldRow) {
$field = $fieldRow['Field'];
$columns[$field] = $fieldRow;
}
} else {
/** @var array<string, string> $fieldRow */
foreach ($queryResult->fetchAll() as $fieldRow) {
$field = $fieldRow['Field'];
$columns[$field] = $fieldRow;
}
}
self::$tableColumnCache[$table] = $columns;
}
/**
* Deletes all dummy files and folders.
*/
private function deleteAllDummyFoldersAndFiles(): void
{
// If the upload folder was created by the testing framework, it can be
// removed at once.
if (isset($this->dummyFolders['uploadFolder'])) {
GeneralUtility::rmdir($this->getUploadFolderPath(), true);
$this->dummyFolders = [];
$this->dummyFiles = [];
} else {
foreach ($this->dummyFiles as $dummyFile) {
$this->deleteDummyFile($dummyFile);
}
foreach ($this->dummyFolders as $dummyFolder) {
$this->deleteDummyFolder($dummyFolder);
}
}
}
// File creation and deletion
/**
* Creates an empty dummy file with a unique file name in the calling
* extension's upload directory.
*
* @param non-empty-string $fileName path of the dummy file to create,
* relative to the calling extension's upload directory
* @param string $content content for the file to create, may be empty
*
* @return non-empty-string the absolute path of the created dummy file
*
* @throws \RuntimeException
*
* @deprecated will be removed in oelib 5.0
*/
public function createDummyFile(string $fileName = 'test.txt', string $content = ''): string
{
$this->createDummyUploadFolder();
$uniqueFileName = $this->getUniqueFileOrFolderPath($fileName);
if (!GeneralUtility::writeFile($uniqueFileName, $content)) {
throw new \RuntimeException('The file ' . $uniqueFileName . ' could not be created.', 1331490486);
}
$this->addToDummyFileList($uniqueFileName);
return $uniqueFileName;
}
/**
* Adds a file name to $this->dummyFiles.
*
* @param non-empty-string $uniqueFileName file name to add, must be the unique name of a dummy file
*/
private function addToDummyFileList(string $uniqueFileName): void
{
$relativeFileName = $this->getPathRelativeToUploadDirectory($uniqueFileName);
$this->dummyFiles[$relativeFileName] = $relativeFileName;
}
/**
* Deletes the dummy file specified by the first parameter $fileName.
*
* @param non-empty-string $fileName the path to the file to delete relative to $this->uploadFolderPath
*
* @throws \RuntimeException
* @throws \InvalidArgumentException
*/
public function deleteDummyFile(string $fileName): void
{
$absolutePathToFile = $this->getUploadFolderPath() . $fileName;
$fileExists = is_file($absolutePathToFile);
if (!isset($this->dummyFiles[$fileName])) {
throw new \InvalidArgumentException(
'The file "' . $absolutePathToFile . '" which you are trying to delete ' .
(!$fileExists ? 'does not exist and has never been ' : 'was not ') .
'created by this instance of the testing framework.',
1331490556
);
}
if ($fileExists && !@unlink($absolutePathToFile)) {
throw new \RuntimeException('The file "' . $absolutePathToFile . '" could not be deleted.', 1331490596);
}
unset($this->dummyFiles[$fileName]);
}
/**
* Creates a dummy folder with a unique folder name in the calling
* extension's upload directory.
*
* @param non-empty-string $folderName name of the dummy folder to create relative to `$this->uploadFolderPath`
*
* @return non-empty-string the absolute path of the created dummy folder
*
* @throws \RuntimeException
*/
public function createDummyFolder(string $folderName): string
{
$this->createDummyUploadFolder();
$uniqueFolderName = $this->getUniqueFileOrFolderPath($folderName);
if (!GeneralUtility::mkdir($uniqueFolderName)) {
throw new \RuntimeException('The folder ' . $uniqueFolderName . ' could not be created.', 1331490619);
}
$relativeUniqueFolderName = $this->getPathRelativeToUploadDirectory($uniqueFolderName);