Link   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 1

Importance

Changes 0
Metric Value
wmc 17
lcom 3
cbo 1
dl 0
loc 91
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A name() 0 4 1
A ports() 0 12 3
A env() 0 10 3
A mainPort() 0 5 1
A tcpPorts() 0 4 1
A udpPorts() 0 4 1
A build() 0 8 1
A buildEnv() 0 10 3
A buildPorts() 0 9 2
1
<?php
2
3
namespace TH\Docker;
4
5
class Link
6
{
7
    private $name;
8
    private $ports;
9
    private $env;
10
11
    /**
12
     * @param  string $name
13
     */
14
    public function __construct($name, array $ports, array $env)
15
    {
16
        $this->name  = $name;
17
        $this->ports = $ports;
18
        $this->env   = $env;
19
    }
20
21
    public function name()
22
    {
23
        return $this->name;
24
    }
25
26
    public function ports($protocol = null)
27
    {
28
        if ($protocol === null) {
29
            return $this->ports;
30
        }
31
        return array_reduce($this->ports, function($ports, Port $port) use ($protocol) {
32
            if ($port->protocol() === $protocol) {
33
                $ports[$port->number()] = $port;
34
            }
35
            return $ports;
36
        }, []);
37
    }
38
39
    public function env($name = null, $default = null)
40
    {
41
        if ($name === null) {
42
            return $this->env;
43
        }
44
        if (array_key_exists($name, $this->env)) {
45
            return $this->env[$name];
46
        }
47
        return $default;
48
    }
49
50
    public function mainPort()
51
    {
52
        $ports = $this->ports();
53
        return reset($ports);
54
    }
55
56
    public function tcpPorts()
57
    {
58
        return $this->ports(Port::TCP);
59
    }
60
61
    public function udpPorts()
62
    {
63
        return $this->ports(Port::UDP);
64
    }
65
66
    public static function build(array $env)
67
    {
68
        return new Link(
69
            $env['NAME'],
70
            self::buildPorts($env),
71
            self::buildEnv($env)
72
        );
73
    }
74
75
    private static function buildEnv(array $env)
76
    {
77
        $linkEnv = [];
78
        foreach ($env as $name => $value) {
79
            if (preg_match("/^ENV_(?<name>.*)$/", $name, $matches) === 1) {
80
                $linkEnv[$matches['name']] = $value;
81
            }
82
        }
83
        return $linkEnv;
84
    }
85
86
    private static function buildPorts(array $env)
87
    {
88
        return array_reduce(array_keys($env), function($linkPorts, $name) use ($env) {
89
            if (preg_match("/^PORT_(?<port>[0-9]+)_(?<protocol>((TCP)|(UDP)))$/", $name, $matches) === 1) {
90
                $linkPorts[] = Port::build($env, $matches['port'], $matches['protocol']);
91
            }
92
            return $linkPorts;
93
        }, []);
94
    }
95
}
96