Completed
Push — master ( 0416ce...a7eaa4 )
by Jindun
10s
created

Service::jsonSerialize()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 61
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 40
nc 8
nop 0
dl 0
loc 61
rs 8.9688
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace TheAentMachine\Service;
4
5
use Opis\JsonSchema\ValidationError;
6
use Opis\JsonSchema\Validator;
7
use TheAentMachine\Aenthill\CommonMetadata;
8
use TheAentMachine\Aenthill\Manifest;
9
use TheAentMachine\Service\Enum\EnvVariableTypeEnum;
10
use TheAentMachine\Service\Enum\VolumeTypeEnum;
11
use TheAentMachine\Service\Environment\EnvVariable;
12
use TheAentMachine\Service\Environment\SharedEnvVariable;
13
use TheAentMachine\Service\Exception\ServiceException;
14
use TheAentMachine\Service\Volume\BindVolume;
15
use TheAentMachine\Service\Volume\NamedVolume;
16
use TheAentMachine\Service\Volume\TmpfsVolume;
17
use TheAentMachine\Service\Volume\Volume;
18
use TheAentMachine\Yaml\CommentedItem;
19
20
class Service implements \JsonSerializable
21
{
22
    /** @var string */
23
    private $serviceName = '';
24
    /** @var string|null */
25
    private $image;
26
    /** @var string[] */
27
    private $command = [];
28
    /** @var int[] */
29
    private $internalPorts = [];
30
    /** @var string[] */
31
    private $dependsOn = [];
32
    /** @var array<int, array<string, string|int>> */
33
    private $ports = [];
34
    /** @var array<string, CommentedItem> */
35
    private $labels = [];
36
    /** @var array<string, EnvVariable> */
37
    private $environment = [];
38
    /** @var mixed[] */
39
    private $volumes = [];
40
    /** @var array<int, array<string, string|int>> */
41
    private $virtualHosts = [];
42
    /** @var null|bool */
43
    private $needBuild;
44
    /** @var \stdClass */
45
    private $validatorSchema;
46
    /** @var string[] */
47
    private $dockerfileCommands = [];
48
    /** @var null|string */
49
    private $requestMemory;
50
    /** @var null|string */
51
    private $requestCpu;
52
    /** @var null|string */
53
    private $requestStorage;
54
    /** @var null|string */
55
    private $limitMemory;
56
    /** @var null|string */
57
    private $limitCpu;
58
    /** @var string[] */
59
    private $destEnvTypes = []; // empty === all env types
60
61
    /**
62
     * Service constructor.
63
     */
64
    public function __construct()
65
    {
66
        $this->validatorSchema = \GuzzleHttp\json_decode((string)file_get_contents(__DIR__ . '/ServiceJsonSchema.json'), false);
67
    }
68
69
    /**
70
     * @param mixed[] $payload
71
     * @return Service
72
     * @throws ServiceException
73
     */
74
    public static function parsePayload(array $payload): Service
75
    {
76
        $service = new self();
77
        $service->checkValidity($payload);
78
        $service->serviceName = $payload['serviceName'] ?? '';
79
        if (!empty($s = $payload['service'] ?? [])) {
80
            $service->image = $s['image'] ?? null;
81
            $service->command = $s['command'] ?? [];
82
            $service->internalPorts = $s['internalPorts'] ?? [];
83
            $service->dependsOn = $s['dependsOn'] ?? [];
84
            $service->ports = $s['ports'] ?? [];
85
            $labels = $s['labels'] ?? [];
86
            foreach ($labels as $key => $label) {
87
                $service->addLabel($key, $label['value'], $label['comment'] ?? null);
88
            }
89
            $environment = $s['environment'] ?? [];
90
            foreach ($environment as $key => $env) {
91
                $service->addEnvVar($key, $env['value'], $env['type'], $env['comment'] ?? null, $env['containerId'] ?? null);
92
            }
93
            $volumes = $s['volumes'] ?? [];
94
            foreach ($volumes as $vol) {
95
                $service->addVolume($vol['type'], $vol['source'], $vol['comment'] ?? null, $vol['target'] ?? '', $vol['readOnly'] ?? false);
96
            }
97
            $service->virtualHosts = $s['virtualHosts'] ?? [];
98
            $service->needBuild = $s['needBuild'] ?? null;
99
        }
100
        $service->dockerfileCommands = $payload['dockerfileCommands'] ?? [];
101
        $service->destEnvTypes = $payload['destEnvTypes'] ?? [];
102
103
        $resources = $payload['resources'] ?? [];
104
        if (isset($resources['requests'])) {
105
            $r = $resources['requests'];
106
            $service->requestMemory = $r['memory'] ?? null;
107
            $service->requestCpu = $r['cpu'] ?? null;
108
            $service->requestStorage= $r['storage'] ?? null;
109
        }
110
        if (isset($resources['limits'])) {
111
            $l = $resources['limits'];
112
            $service->limitMemory = $l['memory'] ?? null;
113
            $service->limitCpu = $l['cpu'] ?? null;
114
        }
115
116
        return $service;
117
    }
118
119
    /**
120
     * Specify data which should be serialized to JSON
121
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
122
     * @return array data which can be serialized by <b>json_encode</b>,
123
     * which is a value of any type other than a resource.
124
     * @since 5.4.0
125
     * @throws ServiceException
126
     */
127
    public function jsonSerialize(): array
128
    {
129
        $labelMap = function (CommentedItem $commentedItem): array {
130
            return null === $commentedItem->getComment() ?
131
                ['value' => $commentedItem->getItem()] :
132
                ['value' => $commentedItem->getItem(), 'comment' => $commentedItem->getComment()];
133
        };
134
135
        $jsonSerializeMap = function (\JsonSerializable $obj): array {
136
            return $obj->jsonSerialize();
137
        };
138
139
        $json = array(
140
            'serviceName' => $this->serviceName,
141
        );
142
143
        $service = array_filter([
144
            'image' => $this->image,
145
            'command' => $this->command,
146
            'internalPorts' => $this->internalPorts,
147
            'dependsOn' => $this->dependsOn,
148
            'ports' => $this->ports,
149
            'labels' => array_map($labelMap, $this->labels),
150
            'environment' => array_map($jsonSerializeMap, $this->environment),
151
            'volumes' => array_map($jsonSerializeMap, $this->volumes),
152
            'virtualHosts' => $this->virtualHosts,
153
            'needBuild' => $this->needBuild,
154
        ]);
155
156
        if (!empty($service)) {
157
            $json['service'] = $service;
158
        }
159
160
        if (!empty($this->dockerfileCommands)) {
161
            $json['dockerfileCommands'] = $this->dockerfileCommands;
162
        }
163
164
        $json['destEnvTypes'] = $this->destEnvTypes;
165
166
        $resources = array_filter([
167
            'requests' => array_filter([
168
                'memory' => $this->requestMemory,
169
                'cpu' => $this->requestCpu,
170
                'storage' => $this->requestStorage,
171
            ], function ($v) {
172
                return null !== $v;
173
            }),
174
            'limits' => array_filter([
175
                'memory' => $this->limitMemory,
176
                'cpu' => $this->limitCpu,
177
            ], function ($v) {
178
                return null !== $v;
179
            }),
180
        ]);
181
182
        if (!empty($resources)) {
183
            $json['resources'] = $resources;
184
        }
185
186
        $this->checkValidity($json);
187
        return $json;
188
    }
189
190
    /** @return mixed[] */
191
    public function imageJsonSerialize(): array
192
    {
193
        $dockerfileCommands = [];
194
        $dockerfileCommands[] = 'FROM ' . $this->image;
195
        foreach ($this->environment as $key => $env) {
196
            if ($env->getType() === EnvVariableTypeEnum::IMAGE_ENV_VARIABLE) {
197
                $dockerfileCommands[] = "ENV $key" . '=' . $env->getValue();
198
            }
199
        }
200
        foreach ($this->volumes as $volume) {
201
            if ($volume->getType() === VolumeTypeEnum::BIND_VOLUME) {
202
                $dockerfileCommands[] = 'COPY ' . $volume->getSource() . ' ' . $volume->getTarget();
203
            }
204
        }
205
206
        if (!empty($this->command)) {
207
            $dockerfileCommands[] = 'CMD ' . implode(' ', $this->command);
208
        }
209
210
        $dockerfileCommands = array_merge($dockerfileCommands, $this->dockerfileCommands);
211
212
        return [
213
            'serviceName' => $this->serviceName,
214
            'dockerfileCommands' => $dockerfileCommands,
215
            'destEnvTypes' => $this->destEnvTypes,
216
        ];
217
    }
218
219
    /**
220
     * @param \stdClass|array|string $data
221
     * @return bool
222
     * @throws ServiceException
223
     */
224
    private function checkValidity($data): bool
225
    {
226
        if (\is_array($data)) {
227
            $data = \GuzzleHttp\json_decode(\GuzzleHttp\json_encode($data), false);
228
        }
229
        $validator = new Validator();
230
        $result = $validator->dataValidation($data, $this->validatorSchema);
231
        if (!$result->isValid()) {
232
            /** @var ValidationError $vError */
233
            $vError = $result->getFirstError();
234
            throw ServiceException::invalidServiceData($vError);
235
        }
236
        return $result->isValid();
237
    }
238
239
240
    /************************ getters **********************/
241
242
    public function getServiceName(): string
243
    {
244
        return $this->serviceName;
245
    }
246
247
    public function getImage(): ?string
248
    {
249
        return $this->image;
250
    }
251
252
    /** @return string[] */
253
    public function getCommand(): array
254
    {
255
        return $this->command;
256
    }
257
258
    /** @return int[] */
259
    public function getInternalPorts(): array
260
    {
261
        return $this->internalPorts;
262
    }
263
264
    /** @return string[] */
265
    public function getDependsOn(): array
266
    {
267
        return $this->dependsOn;
268
    }
269
270
    /** @return array<int, array<string, string|int>> */
271
    public function getPorts(): array
272
    {
273
        return $this->ports;
274
    }
275
276
    /** @return array<string, CommentedItem> */
277
    public function getLabels(): array
278
    {
279
        return $this->labels;
280
    }
281
282
    /** @return array<string, EnvVariable> */
283
    public function getEnvironment(): array
284
    {
285
        return $this->environment;
286
    }
287
288
    /** @return mixed[] */
289
    public function getVolumes(): array
290
    {
291
        return $this->volumes;
292
    }
293
294
    /** @return array<int, array<string, string|int>> */
295
    public function getVirtualHosts(): array
296
    {
297
        return $this->virtualHosts;
298
    }
299
300
    public function getNeedBuild(): ?bool
301
    {
302
        return $this->needBuild;
303
    }
304
305
    /** @return string[] */
306
    public function getDockerfileCommands(): array
307
    {
308
        return $this->dockerfileCommands;
309
    }
310
311
    public function getRequestMemory(): ?string
312
    {
313
        return $this->requestMemory;
314
    }
315
316
    public function getRequestCpu(): ?string
317
    {
318
        return $this->requestCpu;
319
    }
320
321
    public function getRequestStorage(): ?string
322
    {
323
        return $this->requestStorage;
324
    }
325
326
    public function getLimitMemory(): ?string
327
    {
328
        return $this->limitMemory;
329
    }
330
331
    public function getLimitCpu(): ?string
332
    {
333
        return $this->limitCpu;
334
    }
335
336
    /**  @return string[] */
337
    public function getDestEnvTypes(): array
338
    {
339
        return $this->destEnvTypes;
340
    }
341
342
343
    /************************ setters **********************/
344
345
    public function setServiceName(string $serviceName): void
346
    {
347
        $this->serviceName = $serviceName;
348
    }
349
350
    public function setImage(?string $image): void
351
    {
352
        $this->image = $image;
353
    }
354
355
    /** @param string[] $command */
356
    public function setCommand(array $command): void
357
    {
358
        $this->command = $command;
359
    }
360
361
    /** @param int[] $internalPorts */
362
    public function setInternalPorts(array $internalPorts): void
363
    {
364
        $this->internalPorts = $internalPorts;
365
    }
366
367
    /** @param string[] $dependsOn */
368
    public function setDependsOn(array $dependsOn): void
369
    {
370
        $this->dependsOn = $dependsOn;
371
    }
372
373
    public function setRequestMemory(string $requestMemory): void
374
    {
375
        $this->requestMemory = $requestMemory;
376
    }
377
378
    public function setRequestCpu(string $requestCpu): void
379
    {
380
        $this->requestCpu = $requestCpu;
381
    }
382
383
    public function setRequestStorage(string $requestStorage): void
384
    {
385
        $this->requestStorage = $requestStorage;
386
    }
387
388
    public function setLimitMemory(string $limitMemory): void
389
    {
390
        $this->limitMemory = $limitMemory;
391
    }
392
393
    public function setLimitCpu(string $limitCpu): void
394
    {
395
        $this->limitCpu = $limitCpu;
396
    }
397
398
    public function setNeedBuild(?bool $needBuild): void
399
    {
400
        $this->needBuild = $needBuild;
401
    }
402
403
404
    /************************ adders **********************/
405
406
    public function addCommand(string $command): void
407
    {
408
        $this->command[] = $command;
409
    }
410
411
    public function addInternalPort(int $internalPort): void
412
    {
413
        $this->internalPorts[] = $internalPort;
414
    }
415
416
    public function addDependsOn(string $dependsOn): void
417
    {
418
        $this->dependsOn[] = $dependsOn;
419
    }
420
421
    public function addPort(int $source, int $target, ?string $comment = null): void
422
    {
423
        $this->ports[] = array_filter([
424
            'source' => $source,
425
            'target' => $target,
426
            'comment' => $comment,
427
        ], function ($v) {
428
            return null !== $v;
429
        });
430
    }
431
432
    public function addLabel(string $key, string $value, ?string $comment = null): void
433
    {
434
        $this->labels[$key] = new CommentedItem($value, $comment);
435
    }
436
437
    public function addVirtualHost(?string $host, int $port, ?string $comment = null): void
438
    {
439
        $array = [];
440
        if (null !== $host && '' !== $host) {
441
            $array['host'] = $host;
442
        }
443
        $array['port'] = $port;
444
        if (null !== $comment && '' !== $comment) {
445
            $array['comment'] = $comment;
446
        }
447
        $this->virtualHosts[] = $array;
448
    }
449
450
    public function addVirtualHostPrefix(?string $hostPrefix, int $port, ?string $comment = null): void
451
    {
452
        $array = [];
453
        if (null !== $hostPrefix && '' !== $hostPrefix) {
454
            $array['hostPrefix'] = $hostPrefix;
455
        }
456
        $array['port'] = $port;
457
        if (null !== $comment && '' !== $comment) {
458
            $array['comment'] = $comment;
459
        }
460
        $this->virtualHosts[] = $array;
461
    }
462
463
    /************************ environment adders & getters by type **********************/
464
465
    /** @throws ServiceException */
466
    private function addEnvVar(string $key, string $value, string $type, ?string $comment = null, ?string $containerId = null): void
467
    {
468
        switch ($type) {
469
            case EnvVariableTypeEnum::SHARED_ENV_VARIABLE:
470
                $this->addSharedEnvVariable($key, $value, $comment, $containerId);
471
                break;
472
            case EnvVariableTypeEnum::SHARED_SECRET:
473
                $this->addSharedSecret($key, $value, $comment, $containerId);
474
                break;
475
            case EnvVariableTypeEnum::IMAGE_ENV_VARIABLE:
476
                $this->addImageEnvVariable($key, $value, $comment);
477
                break;
478
            case EnvVariableTypeEnum::CONTAINER_ENV_VARIABLE:
479
                $this->addContainerEnvVariable($key, $value, $comment);
480
                break;
481
            default:
482
                throw ServiceException::unknownEnvVariableType($type);
483
        }
484
    }
485
486
    /**
487
     * @param string $key
488
     * @param string $value
489
     * @param null|string $comment
490
     * @param null|string $containerId A string representing the ID of the container of environment variables. Typically the name of the env_file in docker_compose or the name of the ConfigMap in Kubernetes
491
     */
492
    public function addSharedEnvVariable(string $key, string $value, ?string $comment = null, ?string $containerId = null): void
493
    {
494
        $this->environment[$key] = new SharedEnvVariable($value, EnvVariableTypeEnum::SHARED_ENV_VARIABLE, $comment, $containerId);
495
    }
496
497
    /**
498
     * @param string $key
499
     * @param string $value
500
     * @param null|string $comment
501
     * @param null|string $containerId A string representing the ID of the container of environment variables. Typically the name of the env_file in docker_compose or the name of the Secret in Kubernetes
502
     */
503
    public function addSharedSecret(string $key, string $value, ?string $comment = null, ?string $containerId = null): void
504
    {
505
        $this->environment[$key] = new SharedEnvVariable($value, EnvVariableTypeEnum::SHARED_SECRET, $comment, $containerId);
506
    }
507
508
    public function addImageEnvVariable(string $key, string $value, ?string $comment = null): void
509
    {
510
        $this->environment[$key] = new EnvVariable($value, EnvVariableTypeEnum::IMAGE_ENV_VARIABLE, $comment);
511
    }
512
513
    public function addContainerEnvVariable(string $key, string $value, ?string $comment = null): void
514
    {
515
        $this->environment[$key] = new EnvVariable($value, EnvVariableTypeEnum::CONTAINER_ENV_VARIABLE, $comment);
516
    }
517
518
    /** @return array<string, EnvVariable> */
519
    private function getAllEnvVariablesByType(string $type): array
520
    {
521
        $res = [];
522
        /**
523
         * @var string $key
524
         * @var EnvVariable $envVar
525
         */
526
        foreach ($this->environment as $key => $envVar) {
527
            if ($envVar->getType() === $type) {
528
                $res[$key] = $envVar;
529
            }
530
        }
531
        return $res;
532
    }
533
534
    /** @return array<string,SharedEnvVariable> */
535
    public function getAllSharedEnvVariable(): array
536
    {
537
        return $this->getAllEnvVariablesByType(EnvVariableTypeEnum::SHARED_ENV_VARIABLE);
538
    }
539
540
    /** @return array<string,SharedEnvVariable> */
541
    public function getAllSharedSecret(): array
542
    {
543
        return $this->getAllEnvVariablesByType(EnvVariableTypeEnum::SHARED_SECRET);
544
    }
545
546
    /** @return array<string, EnvVariable> */
547
    public function getAllImageEnvVariable(): array
548
    {
549
        return $this->getAllEnvVariablesByType(EnvVariableTypeEnum::IMAGE_ENV_VARIABLE);
550
    }
551
552
    /** @return array<string, EnvVariable> */
553
    public function getAllContainerEnvVariable(): array
554
    {
555
        return $this->getAllEnvVariablesByType(EnvVariableTypeEnum::CONTAINER_ENV_VARIABLE);
556
    }
557
558
559
    /************************ volumes adders & removers **********************/
560
561
    /** @throws ServiceException */
562
    private function addVolume(string $type, string $source, ?string $comment = null, string $target = '', bool $readOnly = false): void
563
    {
564
        switch ($type) {
565
            case VolumeTypeEnum::NAMED_VOLUME:
566
                $this->addNamedVolume($source, $target, $readOnly, $comment);
567
                break;
568
            case VolumeTypeEnum::BIND_VOLUME:
569
                $this->addBindVolume($source, $target, $readOnly, $comment);
570
                break;
571
            case VolumeTypeEnum::TMPFS_VOLUME:
572
                $this->addTmpfsVolume($source, $comment);
573
                break;
574
            default:
575
                throw ServiceException::unknownVolumeType($type);
576
        }
577
    }
578
579
    public function addNamedVolume(string $source, string $target, bool $readOnly = false, ?string $comment = null): void
580
    {
581
        $this->volumes[] = new NamedVolume($source, $target, $readOnly, $comment);
582
    }
583
584
    public function addBindVolume(string $source, string $target, bool $readOnly = false, ?string $comment = null): void
585
    {
586
        $this->volumes[] = new BindVolume($source, $target, $readOnly, $comment);
587
    }
588
589
    public function addTmpfsVolume(string $source, ?string $comment = null): void
590
    {
591
        $this->volumes[] = new TmpfsVolume($source, $comment);
592
    }
593
594
    public function addDockerfileCommand(string $dockerfileCommand): void
595
    {
596
        $this->dockerfileCommands[] = $dockerfileCommand;
597
    }
598
599
    private function removeVolumesByType(string $type): void
600
    {
601
        $filterFunction = function (Volume $vol) use ($type) {
602
            return $vol->getType() !== $type;
603
        };
604
        $this->volumes = array_values(array_filter($this->volumes, $filterFunction));
605
    }
606
607
    public function removeAllBindVolumes(): void
608
    {
609
        $this->removeVolumesByType(VolumeTypeEnum::BIND_VOLUME);
610
    }
611
612
    public function removeAllNamedVolumes(): void
613
    {
614
        $this->removeVolumesByType(VolumeTypeEnum::NAMED_VOLUME);
615
    }
616
617
    public function removeAllTmpfsVolumes(): void
618
    {
619
        $this->removeVolumesByType(VolumeTypeEnum::TMPFS_VOLUME);
620
    }
621
622
    public function removeVolumesBySource(string $source): void
623
    {
624
        $filterFunction = function (Volume $vol) use ($source) {
625
            return $vol->getSource() !== $source;
626
        };
627
        $this->volumes = array_values(array_filter($this->volumes, $filterFunction));
628
    }
629
630
    /************************ destEnvTypes stuffs **********************/
631
632
    public function addDestEnvType(string $envType, bool $keepTheOtherEnvTypes = true): void
633
    {
634
        if (!$keepTheOtherEnvTypes) {
635
            $this->destEnvTypes = [];
636
        }
637
        $this->destEnvTypes[] = $envType;
638
    }
639
640
    public function isForDevEnvType(): bool
641
    {
642
        return empty($this->destEnvTypes) || \in_array(CommonMetadata::ENV_TYPE_DEV, $this->destEnvTypes);
643
    }
644
645
    public function isForTestEnvType(): bool
646
    {
647
        return empty($this->destEnvTypes) || \in_array(CommonMetadata::ENV_TYPE_TEST, $this->destEnvTypes);
648
    }
649
650
    public function isForProdEnvType(): bool
651
    {
652
        return empty($this->destEnvTypes) || \in_array(CommonMetadata::ENV_TYPE_PROD, $this->destEnvTypes);
653
    }
654
655
    public function isForMyEnvType(): bool
656
    {
657
        $myEnvType = Manifest::getMetadata(CommonMetadata::ENV_TYPE_KEY);
658
        return empty($this->destEnvTypes) || \in_array($myEnvType, $this->destEnvTypes, true);
659
    }
660
}
661