-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInstallationService.php
More file actions
1850 lines (1512 loc) · 73.6 KB
/
InstallationService.php
File metadata and controls
1850 lines (1512 loc) · 73.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
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
namespace CommonGateway\CoreBundle\Service;
use App\Entity\Action;
use App\Entity\Application;
use App\Entity\CollectionEntity;
use App\Entity\Cronjob;
use App\Entity\DashboardCard;
use App\Entity\Endpoint;
use App\Entity\Entity;
use App\Entity\Gateway as Source;
use App\Entity\Mapping;
use App\Entity\ObjectEntity;
use App\Entity\Organization;
use App\Entity\SecurityGroup;
use App\Entity\Template;
use App\Entity\User;
use App\Kernel;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Psr\Log\LoggerInterface;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
/**
* The installation service is used to install plugins (or actually symfony bundles) on the gateway.
*
* This class breaks complexity, methods and coupling rules. This could be solved by deviding the class into smaller classes but that would deminisch the readability of the code as a whole. All the code in this class is only used in an installation context, and it makes more sense to keep it together. Therefore, a design decision was made to keep al this code in one class.
*
* @Author Ruben van der Linde <ruben@conduction.nl>, Wilco Louwerse <wilco@conduction.nl>, Barry Brands <barry@conduction.nl>, Robert Zondervan <robert@conduction.nl>, Sarai Misidjan <sarai@conduction.nl>
*
* @license EUPL <https://github.com/ConductionNL/contactcatalogus/blob/master/LICENSE.md>
*
* @category Service
*/
class InstallationService
{
/**
* @var ComposerService
*/
private ComposerService $composerService;
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
/**
* @var GatewayResourceService
*/
private GatewayResourceService $resourceService;
/**
* @var ContainerInterface
*/
private ContainerInterface $container;
/**
* @var LoggerInterface
*/
private LoggerInterface $logger;
/**
* @var Filesystem
*/
private Filesystem $filesystem;
/**
* @var SchemaService
*/
private SchemaService $schemaService;
/**
* @var CacheService
*/
private CacheService $cacheService;
/**
* @var SymfonyStyle
*/
private SymfonyStyle $style;
/**
* @var string The location of the vendor folder.
*/
private string $vendorFolder = 'vendor';
/**
* @var array The Objects acquired during an installation
*/
private array $objects = [];
/**
* Some values used for creating test data.
* Note that owner => reference is replaces with an uuid of that User object.
*
* @var array|string[]
*/
private array $testDataDefault = ['owner' => 'https://docs.commongateway.nl/user/default.user.json'];
private const ALLOWED_CORE_SCHEMAS = [
'https://docs.commongateway.nl/schemas/Action.schema.json',
'https://docs.commongateway.nl/schemas/Application.schema.json',
'https://docs.commongateway.nl/schemas/CollectionEntity.schema.json',
'https://docs.commongateway.nl/schemas/Cronjob.schema.json',
'https://docs.commongateway.nl/schemas/DashboardCard.schema.json',
'https://docs.commongateway.nl/schemas/Endpoint.schema.json',
'https://docs.commongateway.nl/schemas/Entity.schema.json',
'https://docs.commongateway.nl/schemas/Gateway.schema.json',
'https://docs.commongateway.nl/schemas/Mapping.schema.json',
'https://docs.commongateway.nl/schemas/Organization.schema.json',
'https://docs.commongateway.nl/schemas/SecurityGroup.schema.json',
'https://docs.commongateway.nl/schemas/User.schema.json',
];
/**
* The constructor sets al needed variables.
*
* @codeCoverageIgnore We do not need to test constructors
*
* @param ComposerService $composerService The Composer service
* @param EntityManagerInterface $entityManager The entity manager
* @param GatewayResourceService $resourceService The resource service
* @param Kernel $kernel The kernel
* @param LoggerInterface $installationLogger The logger for the installation channel.
* @param SchemaService $schemaService The schema service
* @param CacheService $cacheService The cache service
*/
public function __construct(
ComposerService $composerService,
EntityManagerInterface $entityManager,
GatewayResourceService $resourceService,
Kernel $kernel,
LoggerInterface $installationLogger,
SchemaService $schemaService,
CacheService $cacheService
) {
$this->composerService = $composerService;
$this->entityManager = $entityManager;
$this->resourceService = $resourceService;
$this->container = $kernel->getContainer();
$this->logger = $installationLogger;
$this->schemaService = $schemaService;
$this->cacheService = $cacheService;
$this->filesystem = new Filesystem();
}//end __construct()
/**
* Set symfony style in order to output to the console.
*
* @param SymfonyStyle $style The SymfonyStyle.
*
* @return self
*/
public function setStyle(SymfonyStyle $style): self
{
$this->style = $style;
return $this;
}//end setStyle()
/**
* Updates all commonground bundles on the common gateway installation.
*
* This functions serves as the jump of point for the `commengateway:plugins:update` command
*
* @param array $config The (optional) configuration
* @param SymfonyStyle|null $style In case we run update from the :initialize command and want cache:warmup to show IO messages.
*
* @throws Exception
*
* @return int
*/
public function update(array $config = [], SymfonyStyle $style = null): int
{
$this->setStyle($style);
$this->cacheService->setStyle($style);
// Let's see if we are trying to update a single plugin.
if (isset($config['plugin']) === true) {
$this->logger->debug('Running plugin installer for a single plugin: '.$config['plugin']);
$this->install($config['plugin'], $config);
isset($this->style) === true && $this->style->section('Doing a cache warmup after installer is done...');
$this->logger->debug('Doing a cache warmup after installer is done...');
$this->cacheService->warmup();
return Command::SUCCESS;
}//end if
// If we don't want to update a single plugin then we want to install al the plugins.
$plugins = $this->composerService->getAll();
$this->logger->debug('Running plugin installer for all plugins');
foreach ($plugins as $plugin) {
$this->install($plugin['name'], $config);
}
isset($this->style) === true && $this->style->section('Doing a cache warmup after installer is done...');
$this->logger->debug('Doing a cache warmup after installer is done...');
$this->cacheService->warmup();
return Command::SUCCESS;
}//end update()
/**
* Installs the files from a bundle.
*
* Based on the default action handler so schould supoprt a config parrameter even if we do not use it.
*
* @param string $bundle The bundle.
* @param array $config Optional config.
*
* @throws Exception
*
* @return bool The result of the installation.
*/
public function install(string $bundle, array $config = []): bool
{
isset($this->style) === true && $this->style->section('Installing plugin '.$bundle);
$this->logger->debug('Installing plugin '.$bundle, ['plugin' => $bundle]);
// First we want to read all the files so that we have all the content we should install.
// Let's check the basic folders for legacy purposes. todo: remove these at some point.
$this->readDirectory($this->vendorFolder.'/'.$bundle.'/Action');
// Entity.
$this->readDirectory($this->vendorFolder.'/'.$bundle.'/Schema');
// Gateway.
$this->readDirectory($this->vendorFolder.'/'.$bundle.'/Source');
$this->readDirectory($this->vendorFolder.'/'.$bundle.'/Mapping');
$this->readDirectory($this->vendorFolder.'/'.$bundle.'/Data');
// A function that translates old core schema references to the new ones. Only here for backwards compatibility.
$this->translateCoreReferences();
// Then the folder where everything should be.
$this->readDirectory($this->vendorFolder.'/'.$bundle.'/Installation');
// Handling all the found files.
$this->handlePluginFiles($bundle, $config);
isset($this->style) === true && $this->style->info('All Done installing plugin '.$bundle);
$this->logger->debug('All Done installing plugin '.$bundle, ['bundle' => $bundle]);
return true;
}//end install()
/**
* Will handle all files found in the plugin, creating new objects using the $this->objects array.
*
* @param string $bundle The bundle.
* @param array $config Optional config.
*
* @throws Exception
*
* @return void
*/
private function handlePluginFiles(string $bundle, array $config)
{
if (isset($this->style) === true) {
$this->style->writeln('Found '.count($this->objects).' different schema types for '.$bundle);
$this->style->newline();
}
$this->logger->debug('Found '.count($this->objects).' different schema types for '.$bundle, ['bundle' => $bundle]);
// There is a certain order to this, meaning that we want to handle certain schema types before other schema types.
if (isset($this->objects['https://docs.commongateway.nl/schemas/Entity.schema.json']) === true && is_array($this->objects['https://docs.commongateway.nl/schemas/Entity.schema.json']) === true) {
$schemas = $this->objects['https://docs.commongateway.nl/schemas/Entity.schema.json'];
isset($this->style) === true && $this->style->writeln('Found '.count($schemas).' objects for schema https://docs.commongateway.nl/schemas/Entity.schema.json');
$this->logger->debug('Found '.count($schemas).' objects for schema https://docs.commongateway.nl/schemas/Entity.schema.json', ['bundle' => $bundle, 'reference' => 'https://docs.commongateway.nl/schemas/Entity.schema.json']);
$this->handleObjectType('https://docs.commongateway.nl/schemas/Entity.schema.json', $schemas);
unset($this->objects['https://docs.commongateway.nl/schemas/Entity.schema.json']);
}
// Save the entities to the database.
$this->entityManager->flush();
// Make sure we set default data for creating testdata before we start creating ObjectEntities.
if (Uuid::isValid($this->testDataDefault['owner']) === false) {
$testDataUser = $this->entityManager->getRepository('App:User')->findOneBy(['reference' => $this->testDataDefault['owner']]);
$this->testDataDefault['owner'] = $testDataUser ? $testDataUser->getId()->toString() : $testDataUser;
}
// Handle all the other objects.
foreach ($this->objects as $ref => $schemas) {
// Only do handleObjectType if we want to load in ALL testdata, when user has used the argument data.
// Or if it is a core schema, of course.
if ((isset($config['data']) === true && $config['data'] !== false) || in_array($ref, $this::ALLOWED_CORE_SCHEMAS)) {
if (isset($this->style) === true) {
$this->style->newline();
$this->style->writeln('Found '.count($schemas).' objects for schema '.$ref);
}
$this->logger->debug('Found '.count($schemas).' objects for schema '.$ref, ['bundle' => $bundle, 'reference' => $ref]);
$this->handleObjectType($ref, $schemas);
}
unset($this->objects[$ref]);
}//end foreach
// Find and handle the data.json file, if it exists.
if (isset($this->style) === true) {
$this->style->newLine();
$this->style->block('Handling fixtures for '.$bundle.' ...');
}
$this->handleDataJson($bundle, $config);
// Save the all other objects to the database.
$this->entityManager->flush();
// Find and handle the installation.json file, if it exists.
$this->handleInstallationJson($bundle);
}//end handlePluginFiles()
/**
* Handles default / required test data from the data.json file if we are not loading in ALL testdata.
*
* @param string $bundle The bundle.
* @param array $config Optional config.
*
* @return void
*/
private function handleDataJson(string $bundle, array $config)
{
// Handle default / required testdata in data.json file if we are not loading in ALL testdata.
if (isset($config['data']) === false || $config['data'] === false) {
$finder = new Finder();
$files = $finder->in($this->vendorFolder.'/'.$bundle.'/Installation')->files()->name('data.json');
if (isset($this->style) === true) {
$this->style->writeln('Found '.count($files).' data.json file(s)');
$this->style->newline();
}
$this->logger->debug('Found '.count($files).' data.json file(s)', ['bundle' => $bundle]);
foreach ($files as $file) {
$this->readfile($file);
}
foreach ($this->objects as $ref => $schemas) {
$this->handleObjectType($ref, $schemas);
unset($this->objects[$ref]);
}
}
}//end handleDataJson()
/**
* @param string $bundle The bundle.
*
* @throws Exception
*
* @return void
*/
private function handleInstallationJson(string $bundle)
{
if ($this->filesystem->exists($this->vendorFolder.'/'.$bundle.'/Installation/installation.json') !== false) {
$finder = new Finder();
// todo: maybe only allow installation.json file in root of Installation folder?
// $finder->depth('== 0');
$files = $finder->in($this->vendorFolder.'/'.$bundle.'/Installation')->files()->name('installation.json');
if (count($files) === 1) {
$this->logger->debug('Found an installation.json file', ['bundle' => $bundle]);
foreach ($files as $file) {
$this->handleInstaller($file);
}
} else {
$this->logger->error('Found '.count($files).' installation.json files', ['location' => $this->vendorFolder.'/'.$bundle.'/Installation']);
}
// Save the objects created during handling installation.json to the database.
$this->entityManager->flush();
}
}//end handleInstallationJson()
/**
* For backwards compatibility, support old core schema reference and translate them to the new ones.
* Todo: remove this function when we no longer need it.
*
* @return void
*/
private function translateCoreReferences()
{
foreach (array_keys($this->objects) as $translateFrom) {
switch ($translateFrom) {
case 'https://json-schema.org/draft/2020-12/action':
$translateTo = 'https://docs.commongateway.nl/schemas/Action.schema.json';
break;
case 'https://json-schema.org/draft/2020-12/schema':
$translateTo = 'https://docs.commongateway.nl/schemas/Entity.schema.json';
break;
case 'https://json-schema.org/draft/2020-12/source':
$translateTo = 'https://docs.commongateway.nl/schemas/Gateway.schema.json';
break;
case 'https://json-schema.org/draft/2020-12/mapping':
$translateTo = 'https://docs.commongateway.nl/schemas/Mapping.schema.json';
break;
default:
continue 2;
}
if (isset($this->objects[$translateTo]) === false) {
$this->objects[$translateTo] = [];
}
$this->objects[$translateTo] = array_merge($this->objects[$translateTo], $this->objects[$translateFrom]);
unset($this->objects[$translateFrom]);
}//end foreach
}//end translateCoreReferences()
/**
* This function reads a folder to find other folders or json objects.
*
* @TODO: Split this function into 2, one function for reading files and one function for checking if a folder doesn't contain to many files.
*
* @param string $location The location of the folder
*
* @return bool Whether the function was successfully executed
*/
private function readDirectory(string $location): bool
{
// Let's see if the folder exists to start with.
if ($this->filesystem->exists($location) === false) {
$this->logger->debug('Installation folder not found', ['location' => $location]);
return false;
}
// Get the folder content.
$hits = new Finder();
$hits = $hits->in($location);
// Make sure we only check directories and files on this ($location) level deep, use recursion for lower levels.
$hits->depth('== 0');
// Handle directories and files.
$this->logger->debug('Found '.count($hits->directories()).' directories and '.count($hits->files()).' files.', ['location' => $location, 'files' => count($hits->directories()), 'files' => count($hits->files())]);
// Check if we have any directories/folders at this $location.
if (count($hits->directories()) > 0) {
foreach ($hits->directories() as $directory) {
// Let's check out 1 level deeper.
$this->readDirectory($directory->getPathname());
}
}
// Make sure to warn users if they have to many files in a folder. (36 is maximum).
if (count($hits->files()) > 25) {
$this->logger->warning("Found ".strval(count($hits->files()))." files in directory, try limiting your files to 32 per directory. Or you won\'t be able to load in these schema\'s locally on a windows machine.", ['location' => $location, 'files' => count($hits->files())]);
}
// Read all files in this folder.
foreach ($hits->files() as $file) {
if ($file->getFilename() === 'installation.json') {
continue;
}
$this->readfile($file);
}
return true;
}//end readDirectory()
/**
* This function read a folder to find other folders or json objects.
*
* @param SplFileInfo $file The file location
*
* @return bool|array The file contents, or false if content could not be established
*/
private function readfile(SplFileInfo $file)
{
// Check if it is a valid json object.
$mappingSchema = json_decode($file->getContents(), true);
if (empty($mappingSchema) === true) {
$this->logger->error($file->getFilename().' is not a valid json object');
return false;
}
// @Todo: validateJsonMapping does not exist.
// Check if it is a valid schema.
// $mappingSchema = $this->validateJsonMapping($mappingSchema);
// if ($this->validateJsonMapping($mappingSchema) === true) {
// $this->logger->error($file->getFilename().' is not a valid json-mapping object');
// return false;
// }
// Add the file to the object.
return $this->addToObjects($mappingSchema);
}//end readfile()
/**
* Adds an object to the objects stack if it is valid.
*
* @param array $schema The schema
*
* @return bool|array The file contents, or false if content could not be established
*/
private function addToObjects(array $schema)
{
// It is a schema so let's save it like that.
if (array_key_exists('$schema', $schema) === true) {
$this->objects[$schema['$schema']][] = $schema;
return $schema;
}
// If it is not a schema of itself it might be an array of objects.
foreach ($schema as $key => $value) {
if (is_array($value) === true) {
foreach ($value as $object) {
$this->objects[$key][] = $object;
}
continue;
}
// The use of gettype is discouraged, but we don't use it as a bl here and only for logging text purposes. So a design decision was made te allow it.
$this->logger->error('Expected to find array for schema type '.$key.' but found '.gettype($value).' instead', ['value' => $value, 'schema' => $key]);
}//end foreach
return true;
}//end addToObjects()
/**
* Handles schemas of a certain type.
*
* @param string $type The type of the object
* @param array $schemas The schemas to handle
*
* @return array The objects.
*/
private function handleObjectType(string $type, array $schemas): array
{
$objects = [];
foreach ($schemas as $schema) {
$object = $this->handleObject($type, $schema);
if ($object === null) {
continue;
}
// Save it to the database.
$this->entityManager->persist($object);
$objects[] = $object;
}//end foreach
return $objects;
}//end handleObjectType()
/**
* Create an object bases on a type and a schema (the object as an array).
*
* This function breaks complexity rules, but since a switch is the most effective way of doing it a design decision was made to allow it
*
* @param string $type The type of the object
* @param array $schema The object as an array
*
* @return object|null
*/
private function handleObject(string $type, array $schema): ?object
{
// Only base we need it the assumption that on object isn't valid until we made is so.
$object = null;
// Handle core schema's.
if (in_array($type, $this::ALLOWED_CORE_SCHEMAS) === true) {
$object = $this->loadCoreSchema($schema, $type);
}//end if
// Handle Other schema's.
if (in_array($type, $this::ALLOWED_CORE_SCHEMAS) === false) {
$object = $this->loadSchema($schema, $type);
}//end if
// Make sure not to continue on errors.
if ($object === null) {
return null;
}
// Let's see if it is a new object.
if ($this->entityManager->contains($object) === false) {
$this->logger->info(
'A new object has been created trough the installation service',
[
'class' => get_class($object),
// If you get a "::$id must not be accessed before initialization" error here, remove type UuidInterface from the class^ $id declaration. Something to do with read_secure I think.
'id' => $object->getId(),
// TODO: using toSchema on an object that is not persisted yet breaks stuff... "must not be accessed before initialization" errors
// 'object' => method_exists(get_class($object), 'toSchema') === true ? $object->toSchema() : 'toSchema function does not exists.',
]
);
}//end if
return $object;
}//end handleObject()
/**
* This function loads a core schema.
*
* @param array $schema The schema
* @param string $type The type of the schema
*
* @return mixed The loaded object
*/
private function loadCoreSchema(array $schema, string $type): ?object
{
// Cleanup the type / core schema reference.
$matchesCount = preg_match('/^https:\/\/docs\.commongateway\.nl\/schemas\/([#A-Za-z]+)\.schema\.json(|\?((|,)[^,=]+=[^,=]+)+)$/', $type, $matches);
if ($matchesCount === 0) {
$this->logger->error('Can\'t find schema type in this core schema reference: '.$type);
return null;
}
$type = $matches[1];
// @todo remove $query? its not being used.
// $query = explode(',', ltrim($matches[2], '?'));
// Load it if we have it.
if (array_key_exists('$id', $schema) === true) {
$object = $this->entityManager->getRepository('App:'.$type)->findOneBy(['reference' => $schema['$id']]);
}
// Create it if we don't.
if (isset($object) === false || $object === null) {
$object = $this->createNewObjectType($type);
if ($object === null) {
$this->logger->error('Unsupported type for creating a new core object from a schema', ['type' => $type]);
return null;
}
}//end if
// Make sure we have a fromSchema function for this type of object.
if (method_exists(get_class($object), 'fromSchema') === false) {
$this->logger->critical('fromSchema function does not exists for this core schema type: '.get_class($object));
return null;
}
if (isset($this->style) === true) {
$this->style->writeln('Creating or updating core schema:');
$this->style->writeln('['.$schema['$id'].']');
}
$this->logger->debug('Creating or updating core schema', ['schema' => $schema['$id']]);
// Load the data. Compare version to check if we need to update or not.
if (array_key_exists('version', $schema) === true && version_compare($schema['version'], $object->getVersion()) <= 0) {
isset($this->style) === true && $this->style->writeln('The schema has a version number ('.$schema['version'].') equal or lower than the current version ('.$object->getVersion().'), the object is NOT updated');
$this->logger->debug('The schema has a version number equal or lower than the current version, the object is NOT updated', ['schema' => $schema['$id'], 'schemaVersion' => $schema['version'], 'objectVersion' => $object->getVersion()]);
return $object;
}
if (array_key_exists('version', $schema) === true && version_compare($schema['version'], $object->getVersion()) > 0) {
isset($this->style) === true && $this->style->writeln('The schema has a version number ('.$schema['version'].') higher than the current version ('.$object->getVersion().'), the object data is updated');
$this->logger->debug('The schema has a version number higher than the current version, the object data is updated', ['schema' => $schema['$id'], 'schemaVersion' => $schema['version'], 'objectVersion' => $object->getVersion()]);
$object->fromSchema($schema);
return $object;
}
if (array_key_exists('version', $schema) === false || $object->getVersion() === null) {
isset($this->style) === true && $this->style->writeln('The schema doesn\'t have a version number ('.($schema['version'] ?? null).') or the existing object doesn\'t have a version number ('.$object->getVersion().'), the object data is created');
$this->logger->debug('The schema doesn\'t have a version number or the existing object doesn\'t have a version number, the object data is created', ['schema' => $schema['$id'], 'schemaVersion' => ($schema['version'] ?? null), 'objectVersion' => $object->getVersion()]);
$object->fromSchema($schema);
return $object;
}
return $object;
}//end loadCoreSchema()
/**
* Creates a new object of the given type.
*
* @param string $type The type to create an object of.
*
* @return object|null The new Object or null if the type is not supported.
*/
private function createNewObjectType(string $type): ?object
{
switch ($type) {
case 'Action':
return new Action();
case 'Application':
return new Application();
case 'CollectionEntity':
return new CollectionEntity();
case 'Cronjob':
return new Cronjob();
case 'DashboardCard':
return new DashboardCard();
case 'Endpoint':
return new Endpoint();
case 'Entity':
return new Entity();
case 'Gateway':
return new Source();
case 'Mapping':
return new Mapping();
case 'Organization':
return new Organization();
case 'SecurityGroup':
return new SecurityGroup();
case 'User':
return new User();
default:
return null;
}//end switch
}//end createNewObjectType()
/**
* This function loads an non-core schema.
*
* @param array $schema The schema
* @param string $type The type of the schema
*
* @return ObjectEntity|null The loaded object or null on error.
*/
private function loadSchema(array $schema, string $type): ?ObjectEntity
{
$entity = $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $type]);
if ($entity === null) {
$this->logger->error('trying to create data for non-existing entity', ['reference' => $type]);
return null;
}
// If we have an id let try to grab an object.
if (array_key_exists('id', $schema) === true) {
$object = $this->entityManager->getRepository('App:ObjectEntity')->findOneBy(['id' => $schema['id']]);
}
// Create it if we don't.
if (isset($object) === false || $object === null) {
$object = new ObjectEntity($entity);
$object->setOwner($this->testDataDefault['owner']);
}
// TODO: testdata objects seem to have twice as much subobjects as they should have. Duplicates... (example: kiss->klanten->telefoonnummers).
// Now it gets a bit specif but for EAV data we allow nested fixed id's so let dive deep.
if ($this->entityManager->contains($object) === false && (array_key_exists('id', $schema) === true || array_key_exists('_id', $schema) === true)) {
$object = $this->schemaService->hydrate($object, $schema);
}
// EAV objects arn't cast from schema but hydrated from array's.
$object->hydrate($schema);
return $object;
}//end loadSchema()
/**
* Specifically handles the installation file.
*
* @todo: clean up this function, split it into multiple smaller pieces.
*
* @param SplFileInfo $file The installation file.
*
* @throws Exception
*
* @return bool
*/
private function handleInstaller(SplFileInfo $file): bool
{
$data = json_decode($file->getContents(), true);
if (empty($data) === true) {
$this->logger->error($file->getFilename().' is not a valid json object');
return false;
}
// Collection prefixes for schema's.
$this->updateSchemasCollection(($data['collections'] ?? []));
// Endpoints for schema's and/or sources.
$this->createEndpoints(($data['endpoints'] ?? []));
// Actions for action handlers.
$this->createActions(($data['actions']['handlers'] ?? []));
// Fix references in configuration of these actions.
$this->fixConfigRef(($data['actions']['fixConfigRef'] ?? []));
// Cronjobs for actions for action handlers.
$this->createCronjobs(($data['cronjobs']['actions'] ?? []));
// Create users with given Organization, Applications & SecurityGroups.
$this->createApplications(($data['applications'] ?? []));
// Create users with given Organization, Applications & SecurityGroups.
$this->createUsers(($data['users'] ?? []));
// Let's see if we have things that we want to create cards for stuff (Since this might create cards for the stuff above this should always be last).
$this->createCards(($data['cards'] ?? []));
// Set the default source for a schema.
$this->editSchemaProperties(($data['schemas'] ?? []));
// Create template
$this->createTemplates(($data['templates'] ?? []));
if (isset($data['installationService']) === false || empty($data['installationService']) === true) {
$this->logger->error($file->getFilename().' Doesn\'t contain an installation service');
return false;
}
$installationService = $data['installationService'];
try {
$installationService = $this->container->get($installationService);
} catch (Exception $exception) {
$error = "{$file->getFilename()} Could not be loaded from container: {$exception->getMessage()}";
}
if (empty($installationService) === true || isset($error) === true) {
$this->logger->error(($error ?? "{$file->getFilename()} Could not be loaded from container"));
return false;
}
try {
if (isset($this->style) === true && method_exists(get_class($installationService), 'setStyle') === true) {
$installationService->setStyle($this->style);
}
$install = $installationService->install();
return is_bool($install) === true ? $install : empty($install) === false;
} catch (\Throwable $throwable) {
$this->logger->critical("Failed to install installationService {$data['installationService']}: {$throwable->getMessage()}", ['file' => $throwable->getFile(), 'line' => $throwable->getLine()]);
return false;
}
}//end handleInstaller()
/**
* This function adds a given default source to the schema.
*
* @param array $schemasData The array with data of the schemas
*
* @throws Exception
*
* @return void
*/
private function editSchemaProperties(array $schemasData = []): void
{
foreach ($schemasData as $schemaData) {
// Get the schema and source from the schemadata.
$schema = $this->resourceService->getSchema($schemaData['reference'], 'commongateway/corebundle');
if (key_exists('defaultSource', $schemaData) === true) {
$source = $this->resourceService->getSource($schemaData['defaultSource'], 'commongateway/corebundle');
// Set the source as defaultSource to the schema.
$schema->setDefaultSource($source);
}
if (key_exists('createAuditTrails', $schemaData) === true) {
$schema->setCreateAuditTrails($schemaData['createAuditTrails']);
}
$this->entityManager->persist($schema);
}//end foreach
}//end editSchemaProperties()
/**
* This functions connects schema's with a reference containing the collection schemaPrefix to the given collection.
* This way endpoints will be created with the correct prefix.
*
* @param array $collectionsData An array of references of collections + a schemaPrefix.
*
* @return void
*/
private function updateSchemasCollection(array $collectionsData = [])
{
$collections = 0;
foreach ($collectionsData as $collectionData) {
$collection = $this->entityManager->getRepository('App:CollectionEntity')->findOneBy(['reference' => $collectionData['reference']]);
if ($collection === null) {
$this->logger->error('No collection found with this reference: '.$collectionData['reference']);
continue;
}
if (isset($collectionData['schemaPrefix']) === false || empty($collectionData['schemaPrefix']) === true) {
$this->logger->error('No valid schemaPrefix given while trying to add collection to schema\'s', ['reference' => $collectionData['reference']]);
continue;
}
$this->addSchemasToCollection($collection, $collectionData['schemaPrefix']);
$collections++;
$this->logger->debug("Updated schemas with a reference starting with {$collectionData['schemaPrefix']} for Collection {$collectionData['reference']}");
}
$this->logger->info("Updated schemas for $collections Collections");
}//end updateSchemasCollection()
/**
* Adds a collection to all schemas that have a reference starting with $schemaPrefix.
*
* @param CollectionEntity $collection The collection to add.
* @param string $schemaPrefix The prefix to find schemas for.
*
* @return void
*/
private function addSchemasToCollection(CollectionEntity $collection, string $schemaPrefix)
{
$entities = $this->entityManager->getRepository('App:Entity')->findByReferencePrefix($schemaPrefix);
foreach ($entities as $entity) {
$entity->addCollection($collection);
}
}//end addSchemasToCollection()
/**
* This function creates templates for an array of schema references.
*
* @param array $templatesData An array of data used for creating templates.
*
* @return array An array of templates
*/
private function createTemplates(array $templatesData = []): array
{
$templates = [];
// Let's loop through the templatesData.
foreach ($templatesData as $templateData) {
// Create the base Endpoint.
$template = $this->createTemplate($templateData);
if ($template === null) {
continue;
}
$templates[] = $template;
}//end foreach
$this->logger->info(count($templates).' Templates Created');
return $templates;
}//end createTemplates()
/**
* Creates a single endpoint for an Entity or a Source using the data from installation.json.
*
* @param array $templateData The data used to create an Template.
*
* @return Template|null The created Template or null.
*/
private function createTemplate(array $templateData): ?Template
{
$repository = $this->entityManager->getRepository('App:Entity');
if (isset($templateData['supportedSchemas']) === false) {
return null;
}
$supportedSchemas = [];
foreach ($templateData['supportedSchemas'] as $schema) {
$schemaObject = $this->checkIfObjectExists($repository, $schema, 'Template');
if ($schemaObject !== null) {
$supportedSchemas[] = $schemaObject->getId()->toString();
}
}
unset($templateData['supportedSchemas']);
$templateData['supportedSchemas'] = $supportedSchemas;
if (key_exists('organization', $templateData) === true) {