Service   F
last analyzed

Complexity

Total Complexity 81

Size/Duplication

Total Lines 563
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 202
dl 0
loc 563
rs 2
c 0
b 0
f 0
wmc 81

57 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A addPort() 0 8 1
A getPorts() 0 3 1
A getImage() 0 3 1
A getAllSharedEnvVariable() 0 3 1
A getDockerfileCommands() 0 3 1
A getCommand() 0 3 1
A jsonSerialize() 0 58 5
A removeAllNamedVolumes() 0 3 1
A getEnvironment() 0 3 1
A getServiceName() 0 3 1
A getLabels() 0 3 1
A addTmpfsVolume() 0 3 1
A getAllImageEnvVariable() 0 3 1
A addVirtualHost() 0 3 1
A addEnvVar() 0 17 5
A setInternalPorts() 0 3 1
A setNeedBuild() 0 3 1
A addVolume() 0 14 4
A getRequestCpu() 0 3 1
B parsePayload() 0 48 7
A getAllSharedSecret() 0 3 1
A addDependsOn() 0 3 1
A getLimitMemory() 0 3 1
A addCommand() 0 3 1
A setImage() 0 3 1
A addBindVolume() 0 3 1
A setRequestMemory() 0 3 1
A removeAllTmpfsVolumes() 0 3 1
A getVirtualHosts() 0 3 1
A setLimitCpu() 0 3 1
A setLimitMemory() 0 3 1
A removeAllBindVolumes() 0 3 1
A addNamedVolume() 0 3 1
A getInternalPorts() 0 3 1
A removeVolumesByType() 0 6 1
A getVolumes() 0 3 1
A getAllContainerEnvVariable() 0 3 1
A setCommand() 0 3 1
A removeVolumesBySource() 0 6 1
A addLabel() 0 3 1
A getRequestMemory() 0 3 1
A checkValidity() 0 13 3
A getLimitCpu() 0 3 1
A addSharedSecret() 0 3 1
A getDependsOn() 0 3 1
A getNeedBuild() 0 3 1
A addSharedEnvVariable() 0 3 1
A setRequestCpu() 0 3 1
A getAllEnvVariablesByType() 0 13 3
A setServiceName() 0 3 1
A setDependsOn() 0 3 1
A addInternalPort() 0 3 1
A addContainerEnvVariable() 0 3 1
A imageJsonSerialize() 0 19 4
A addDockerfileCommand() 0 3 1
A addImageEnvVariable() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Service often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Service, and based on these observations, apply Extract Interface, too.

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