-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInstallationService.php
More file actions
646 lines (549 loc) · 23.3 KB
/
InstallationService.php
File metadata and controls
646 lines (549 loc) · 23.3 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
<?php
namespace CommonGateway\CoreBundle\Service;
use App\Entity\CollectionEntity;
use App\Entity\Entity;
use App\Entity\ObjectEntity;
use App\Entity\Value;
use App\Kernel;
use Doctrine\ORM\EntityManagerInterface;
use Monolog\Logger;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
class InstallationService
{
private ComposerService $composerService;
private EntityManagerInterface $em;
private SymfonyStyle $io;
private $container;
private Logger $logger;
private CacheService $cacheService;
public function __construct(
ComposerService $composerService,
EntityManagerInterface $em,
Kernel $kernel,
CacheService $cacheService
) {
$this->composerService = $composerService;
$this->em = $em;
$this->container = $kernel->getContainer();
$this->collection = null;
$this->logger = new Logger('installation');
$this->cacheService = $cacheService;
}
/**
* Set symfony style in order to output to the console.
*
* @param SymfonyStyle $io
*
* @return self
*/
public function setStyle(SymfonyStyle $io): self
{
$this->io = $io;
return $this;
}
/**
* Updates all commonground bundles on the common gateway installation.
*
* @param array $config
*
* @return int
*/
public function composerupdate(array $config = []): int
{
$plugins = $this->composerService->getAll();
if ($this->io) {
$this->io->writeln([
'',
'<info>Common Gateway Bundle Updater</info>',
'============',
'',
'Found: <comment> '.count($plugins).' </comment> to check for updates',
'',
]);
}
$this->logger->debug('Running plugin installer');
foreach ($plugins as $plugin) {
$this->install($plugin['name'], $config);
}
if ($this->io) {
$this->cacheService->setStyle($this->io);
$this->cacheService->warmup();
}
return Command::SUCCESS;
}
/**
* Validates the objects in the EAV setup.
*
* @return void
*/
public function validateObjects(): int
{
$objects = $this->em->getRepository('App:ObjectEntity')->findAll();
if ($this->io) {
$this->io->writeln([
'Validating: <comment> '.count($objects).' </comment> objects\'s',
]);
}
$this->logger->info('Validating:'.count($objects).'objects\'s');
// Lets go go go !
foreach ($objects as $object) {
if ($object->get) {
}
}
}
/**
* Validates the objects in the EAV setup.
*
* @return void
*/
public function validateValues(): int
{
$values = $this->em->getRepository('App:Value')->findAll();
if ($this->io) {
$this->io->writeln([
'Validating: <comment> '.count($values).' </comment> values\'s',
]);
}
$this->logger->info('Validating:'.count($values).'values\'s');
// Lets go go go !
foreach ($values as $value) {
if (!$value->getObjectEntity()) {
$message = 'Value '.$value->getStringValue().' ('.$value->getId().') that belongs to '.$value->getAttribute()->getName().' ('.$value->getAttribute()->getId().') is orpahned';
}
}
}
/**
* Validates the schemas in the EAV setup.
*
* @return void
*/
public function validateSchemas(): int
{
$schemas = $this->em->getRepository('App:Entity')->findAll();
if ($this->io) {
$this->io->writeln([
'Validating: <comment> '.count($schemas).' </comment> schema\'s',
]);
}
$this->logger->info('Validating:'.count($schemas).'schema\'s');
// Lets go go go !
foreach ($schemas as $schema) {
$statusOk = true;
// Gereric check
if (!$schema->getReference()) {
$this->logger->info('Schema '.$schema->getName().' ('.$schema->getId().') dosn\t have a reference');
}
// Gereric check
/*
if(!$schema->getApplication()){
$this->logger->info( 'Schema '.$schema->getName().' ('.$schema->getId().') dosn\t have a application');
}
// Gereric check
if(!$schema->getOrganization()){
$this->logger->info( 'Schema '.$schema->getName().' ('.$schema->getId().') dosn\t have a organization');
}
*/
// Check atributes
foreach ($schema->getAttributes() as $attribute) {
// Specific checks for objects
if ($attribute->getType() == 'object') {
// Check for object link
if (!$attribute->getObject()) {
$message = 'Schema '.$schema->getName().' ('.$schema->getId().') has attribute '.$attribute->getName().' ('.$attribute->getId().') that is of type Object but is not linked to an object';
$this->logger->error($message);
if ($this->io) {
$this->io->error($message);
}
$statusOk = false;
} else {
$message = 'Schema '.$schema->getName().' ('.$schema->getId().') has attribute '.$attribute->getName().' ('.$attribute->getId().') that is linked to object '.$attribute->getObject()->getName().' ('.$attribute->getObject()->getId();
$this->logger->debug($message);
if ($this->io) {
$this->io->note($message);
}
}
// Check for reference link
if (!$attribute->getReference()) {
//$message = 'Schema '.$schema->getName().' ('.$schema->getId().') has attribute '.$attribute->getName().' ('.$attribute->getId().') that is of type Object but is not linked to an reference';
//$this->logger->info($message);
//if ($this->io) { $this->io->info($message);}
}
}
// Specific wierdnes
// Check for reference link
if ($attribute->getReference() && !$attribute->getType() == 'object') {
$message = 'Schema '.$schema->getName().' ('.$schema->getId().') has attribute '.$attribute->getName().' ('.$attribute->getId().') that has a reference ('.$attribute->getReference().') but isn\'t of the type object';
$this->logger->error($message);
if ($this->io) {
$this->io->error($message);
}
$statusOk = false;
}
}
if ($statusOk) {
$message = 'Schema '.$schema->getName().' ('.$schema->getId().') has been checked and is fine';
$this->logger->info($message);
if ($this->io) {
$this->io->info($message);
}
} else {
$message = 'Schema '.$schema->getName().' ('.$schema->getId().') has been checked and has an error';
$this->logger->error($message);
if ($this->io) {
$this->io->error($message);
}
}
}
return 1;
}
/**
* Performs installation actions on a common Gataway bundle.
*
* @param SymfonyStyle $io
* @param string $bundle
* @param bool $noSchema
*
* @return int
*/
public function install(string $bundle, array $config = []): int
{
if ($this->io) {
$this->io->writeln([
'Trying to install: <comment> '.$bundle.' </comment>',
'',
]);
}
$this->logger->debug('Trying to install: '.$bundle);
$packages = $this->composerService->getAll();
$found = array_filter($packages, function ($v, $k) use ($bundle) {
return $v['name'] == $bundle;
}, ARRAY_FILTER_USE_BOTH); // With the latest PHP third parameter is optional.. Available Values:- ARRAY_FILTER_USE_BOTH OR ARRAY_FILTER_USE_KEY
$package = reset($found);
if ($package) {
$this->io->writeln([
'<info>Package '.$bundle.' found</info>',
'',
'Name: '.$package['name'],
'Version: '.$package['version'],
'Description: '.$package['description'],
'Homepage :'.$package['homepage'],
'Source: '.$package['source']['url'],
]);
} else {
$this->io->error($bundle.' not found');
return Command::FAILURE;
}
$vendorFolder = 'vendor';
$filesystem = new Filesystem();
// Handling the schema's
$this->io->section('Looking for schema\'s');
$schemaDir = $vendorFolder.'/'.$bundle.'/Schema';
if ($filesystem->exists($schemaDir)) {
$this->io->writeln('Schema folder found');
$schemas = new Finder();
$schemas = $schemas->in($schemaDir);
$this->io->writeln('Files found: '.count($schemas));
// We want each plugin to also be a collection (if it contains schema's that is)
if (count($schemas) > 0) {
if (!$this->collection = $this->em->getRepository('App:CollectionEntity')->findOneBy(['plugin' => $package['name']])) {
$this->logger->debug('Created a collection for plugin '.$bundle);
$this->io->writeln(['Created a collection for this plugin', '']);
$this->collection = new CollectionEntity();
$this->collection->setName($package['name']);
$this->collection->setPlugin($package['name']);
isset($package['description']) && $this->collection->setDescription($package['description']);
} else {
$this->io->writeln(['Found a collection for this plugin', '']);
$this->logger->debug('Found a collection for plugin '.$bundle);
}
}
// Persist collection
if (isset($this->collection)) {
$this->em->persist($this->collection);
$this->em->flush();
}
foreach ($schemas->files() as $schema) {
$this->handleSchema($schema);
}
//$progressBar->finish();
} else {
$this->io->writeln('No schema folder found');
$this->logger->debug('No schema folder found for plugin '.$bundle);
}
// Handling the data
$this->io->section('Looking for data');
if (array_key_exists('data', $config) && $config['data']) {
$dataDir = $vendorFolder.'/'.$bundle.'/Data';
if ($filesystem->exists($dataDir)) {
$this->io->writeln('Data folder found');
$datas = new Finder();
$datas = $datas->in($dataDir);
$this->io->writeln('Files found: '.count($datas));
foreach ($datas->files() as $data) {
$this->handleData($data);
}
// We need to clear the finder
} else {
$this->logger->debug('No data folder found for plugin '.$bundle);
$this->io->writeln('No data folder found');
}
} else {
$this->io->warning('No test data loaded for bundle, run command with -data to load (test) data');
}
// Handling the installations
$this->io->section('Looking for installers');
$installationDir = $vendorFolder.'/'.$bundle.'/Installation';
if ($filesystem->exists($installationDir)) {
$this->io->writeln('Installation folder found');
$installers = new Finder();
$installers = $installers->in($installationDir);
$this->io->writeln('Files found: '.count($installers));
foreach ($installers->files() as $installer) {
$this->handleInstaller($installer);
}
} else {
$this->logger->debug('No Installation folder found for plugin '.$bundle);
$this->io->writeln('No Installation folder found');
}
$this->io->success('All Done');
$this->logger->debug('All Done installing plugin '.$bundle);
return Command::SUCCESS;
}
public function update(string $bundle, string $data)
{
$this->io->writeln([
'Common Gateway Bundle Updater',
'============',
'',
]);
return Command::SUCCESS;
}
public function uninstall(string $bundle, string $data)
{
$this->io->writeln([
'Common Gateway Bundle Uninstaller',
'============',
'',
]);
return Command::SUCCESS;
}
public function handleSchema($file)
{
if (!$schema = json_decode($file->getContents(), true)) {
$this->io->writeln($file->getFilename().' is not a valid json object');
return false;
}
if (!$this->valdiateJsonSchema($schema)) {
$this->io->writeln($file->getFilename().' is not a valid json-schema object');
return false;
}
if (!$entity = $this->em->getRepository('App:Entity')->findOneBy(['reference' => $schema['$id']])) {
$this->io->writeln('Schema not present, creating schema '.$schema['title'].' under reference '.$schema['$id']);
$entity = new Entity();
} else {
$this->io->writeln('Schema already present, looking to update');
if (array_key_exists('version', $schema) && version_compare($schema['version'], $entity->getVersion()) < 0) {
$this->io->writeln('The new schema has a version number equal or lower then the already present version');
}
}
$entity->fromSchema($schema);
$this->em->persist($entity);
// Add the schema to collection
if (isset($this->collection)) {
$entity->addCollection($this->collection);
}
$this->em->flush();
$this->io->writeln('Done with schema '.$entity->getName());
}
/**
* Perform a very basic check to see if a schema file is a valid json-schema file.
*
* @param array $schema
*
* @return bool
*/
public function valdiateJsonSchema(array $schema): bool
{
if (
array_key_exists('$id', $schema) &&
array_key_exists('$schema', $schema) &&
$schema['$schema'] == 'https://json-schema.org/draft/2020-12/schema' &&
array_key_exists('type', $schema) &&
$schema['type'] == 'object' &&
array_key_exists('properties', $schema)
) {
return true;
}
return false;
}
public function handleData($file)
{
if (!$data = json_decode($file->getContents(), true)) {
$this->io->writeln($file->getFilename().' is not a valid json object');
return false;
}
foreach ($data as $reference => $objects) {
// Lets see if we actuelly have a shema to upload the objects to
if (!$entity = $this->em->getRepository('App:Entity')->findOneBy(['reference' => $reference])) {
$this->io->writeln('No Schema found for reference '.$reference);
continue;
}
$this->io->writeln([
'',
'<info> Found data for schema '.$reference.'</info> containing '.count($objects).' object(s)',
]);
// Then we can handle data
foreach ($objects as $object) {
// Lets see if we need to update
// Backwarsd competability
if (isset($object['_id'])) {
$object['id'] = $object['_id'];
unset($object['_id']);
}
if (isset($object['id']) && $objectEntity = $this->em->getRepository('App:ObjectEntity')->findOneBy(['id' => $object['id']])) {
$this->io->writeln(['', 'Object '.$object['id'].' already exists, so updating']);
} else {
$objectEntity = new ObjectEntity($entity);
}
$this->io->writeln('Writing data to the object');
$this->saveOnFixedId($objectEntity, $object);
$this->io->writeln(['Object saved as '.$objectEntity->getId(), '']);
}
}
}
public function handleInstaller($file)
{
if (!$data = json_decode($file->getContents(), true)) {
$this->io->writeln($file->getFilename().' is not a valid json object');
return false;
}
if (!isset($data['installationService']) || !$installationService = $data['installationService']) {
$this->io->writeln($file->getFilename().' Doesn\'t contain an installation service');
return false;
}
if (!$installationService = $this->container->get($installationService)) {
$this->io->writeln($file->getFilename().' Could not be loaded from container');
return false;
}
$installationService->setStyle($this->io);
return $installationService->install();
}
/**
* Handles forced id's on object entities.
*
* @param ObjectEntity $objectEntity
*
* @return ObjectEntity
*/
private function saveOnFixedId(ObjectEntity $objectEntity, array $hydrate = []): ObjectEntity
{
// This savetey dosn't make sense but we need it
if (!$objectEntity->getEntity()) {
$this->logger->error('Object can\'t be persisted due to missing schema');
$this->io->writeln(['', 'Object can\'t be persisted due to missing schema']);
return $objectEntity;
}
// Save the values
//$values = $objectEntity->getObjectValues()->toArray();
//$objectEntity->clearAllValues();
// We have an object entity with a fixed id that isn't in the database, so we need to act
if (isset($hydrate['id']) && !$this->em->contains($objectEntity)) {
$this->io->writeln(['Creating new object ('.$objectEntity->getEntity()->getName().') on a fixed id ('.$hydrate['id'].')']);
// save the id
$id = $hydrate['id'];
// Create the entity
$this->em->persist($objectEntity);
$this->em->flush();
$this->em->refresh($objectEntity);
// Reset the id
$objectEntity->setId($id);
$this->em->persist($objectEntity);
$this->em->flush();
$this->em->clear(get_class($objectEntity));
$objectEntity = $this->em->getRepository('App:ObjectEntity')->findOneBy(['id' => $id]);
$this->io->writeln(['Defintive object id ('.$objectEntity->getId().')']);
} else {
$this->io->writeln(['Creating new object ('.$objectEntity->getEntity()->getName().') on a generated id']);
}
// We already dit this so lets skip it
unset($hydrate['_id']);
foreach ($hydrate as $key => $value) {
// Try to get a value object
$valueObject = $objectEntity->getValueObject($key);
// If we find the Value object we set the value
if ($valueObject instanceof Value) {
// Value is an array so lets create an object
if ($valueObject->getAttribute()->getType() == 'object') {
// I hate arrays
if ($valueObject->getAttribute()->getMultiple()) {
$this->io->info('an array for objects
');
if (is_array($value)) {
foreach ($value as $subvalue) {
// Savety
if (!$valueObject->getAttribute()->getObject()) {
continue;
}
// is array
if (is_array($subvalue)) {
$newObject = new ObjectEntity($valueObject->getAttribute()->getObject());
$newObject = $this->saveOnFixedId($newObject, $subvalue);
$valueObject->addObject($newObject);
}
// Is not an array
else {
$idValue = $subvalue;
$subvalue = $this->em->getRepository('App:ObjectEntity')->findOneBy(['id' => $idValue]);
// Savety
if (!$subvalue) {
$this->io->error('Could not find an object for id '.$idValue);
} else {
$valueObject->addObject($subvalue);
}
}
}
} else {
$this->io->error($valueObject->getAttribute()->getName().' Is a multiple so should be filled with an array, but provided value was '.$value.'(type: '.gettype($value).')');
}
continue;
}
// End of array hate, we are friends again
// is array
if (is_array($value)) {
// Savety
if (!$valueObject->getAttribute()->getObject()) {
$this->io->error('Could not find an object for atribute '.$valueObject->getAttribute()->getname().' ('.$valueObject->getAttribute()->getId().')');
continue;
}
$newObject = new ObjectEntity($valueObject->getAttribute()->getObject());
$value = $this->saveOnFixedId($newObject, $value);
$valueObject->setValue($value);
}
// Is not an array
else {
$idValue = $value;
$value = $this->em->getRepository('App:ObjectEntity')->findOneBy(['id' => $idValue]);
// Savety
if (!$value) {
$this->io->error('Could not find an object for id '.$idValue);
} else {
$valueObject->setValue($value);
}
}
} else {
$valueObject->setValue($value);
}
// Do the normaul stuf
$objectEntity->addObjectValue($valueObject);
}
}
// Lets force the default values
$objectEntity->hydrate([]);
$this->em->persist($objectEntity);
$this->em->flush();
return $objectEntity;
}
}