Completed
Push — master ( 16bce0...f6a8c2 )
by David
15s
created

Service::addVirtualHost()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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