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