Passed
Push — test ( d8d4a5...bb43f9 )
by Tom
03:01
created

Services::getByNames()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines\File\Definitions;
6
7
use Countable;
8
use Ktomk\Pipelines\File\ParseException;
9
10
/**
11
 * Class Services
12
 *
13
 * @package Ktomk\Pipelines\File\Definitions
14
 */
15
class Services implements Countable
16
{
17
    /**
18
     * @var array
19
     */
20
    private $array;
21
22
    /**
23
     * @var array|Service[]
24
     */
25
    private $services = array();
26
27
    /**
28
     * Services constructor.
29
     *
30
     * @param array $array
31
     */
32 5
    public function __construct(array $array)
33
    {
34 5
        $this->parseServices($array);
35
36 3
        $this->array = $array;
37 3
    }
38
39
    /**
40
     * @param string $serviceName
41
     *
42
     * @return null|Service
43
     */
44 1
    public function getByName($serviceName)
45
    {
46 1
        return isset($this->services[$serviceName]) ? $this->services[$serviceName] : null;
47
    }
48
49
    /**
50
     * get array of services by names
51
     *
52
     * if a service is not found it will not be returned
53
     *
54
     * @param string[] $serviceNames names of services to obtain
55
     *
56
     * @return Service[]
57
     */
58 1
    public function getByNames(array $serviceNames)
59
    {
60 1
        return array_intersect_key($this->services, array_flip($serviceNames));
61
    }
62
63
    /**
64
     * @return int
65
     */
66 2
    public function count()
67
    {
68 2
        return count($this->services);
69
    }
70
71
    /**
72
     * @param array $array
73
     *
74
     * @return void
75
     */
76 5
    private function parseServices(array $array)
77
    {
78 5
        foreach ($array as $name => $service) {
79 4
            if (!is_string($name)) {
80 1
                throw new ParseException(sprintf('Invalid service definition name: %s', var_export($name, true)));
81
            }
82 3
            if (!is_array($service)) {
83 1
                throw new ParseException(sprintf('Invalid service definition "%s"', $name));
84
            }
85
            // docker service is internal, for pipelines no need here to handle it
86 2
            if ('docker' === $name) {
87 1
                continue;
88
            }
89 1
            $this->services[$name] = $this->parseNamedService($name, $service);
90
        }
91 3
    }
92
93
    /**
94
     * @param string $name
95
     * @param array $service
96
     *
97
     * @return Service
98
     */
99 1
    private function parseNamedService($name, array $service)
100
    {
101 1
        return new Service($name, $service);
102
    }
103
}
104