Passed
Push — test ( 3623cf...52bb81 )
by Tom
02:51
created

Env::getInheritValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines\Runner;
6
7
use Ktomk\Pipelines\Cli\Args\Args;
8
use Ktomk\Pipelines\Cli\Args\Collector;
9
use Ktomk\Pipelines\Lib;
10
11
/**
12
 * Pipeline environment collaborator
13
 */
14
class Env
15
{
16
    /**
17
     * @var array pipelines (bitbucket) environment variables
18
     */
19
    private $vars = array();
20
21
    /**
22
     * collected arguments
23
     *
24
     * @var array
25
     */
26
    private $collected = array();
27
28
    /**
29
     * environment variables to inherit from
30
     *
31
     * @var array
32
     */
33
    private $inherit = array();
34
35
    /**
36
     * @var null|EnvResolver
37
     */
38
    private $resolver;
39
40
    /**
41
     * @param null|array $inherit
42
     *
43
     * @return Env
44
     */
45 17
    public static function create(array $inherit = array())
46
    {
47 17
        $env = new self();
48 17
        $env->initDefaultVars($inherit);
49
50 17
        return $env;
51
    }
52
53
    /**
54
     * Initialize default environment used in a Bitbucket Pipeline
55
     *
56
     * As the runner mimics some values, defaults are available
57
     *
58
     * @param array $inherit Environment variables to inherit from
59
     */
60 20
    public function initDefaultVars(array $inherit)
61
    {
62 20
        $this->inherit = array_filter($inherit, 'is_string');
63
64
        $inheritable = array(
65 20
            'BITBUCKET_BOOKMARK' => null,
66
            'BITBUCKET_BRANCH' => null,
67 20
            'BITBUCKET_BUILD_NUMBER' => '0',
68 20
            'BITBUCKET_COMMIT' => '0000000000000000000000000000000000000000',
69 20
            'BITBUCKET_REPO_OWNER' => '' . Lib::r($inherit['USER'], 'nobody'),
70 20
            'BITBUCKET_REPO_SLUG' => 'local-has-no-slug',
71
            'BITBUCKET_TAG' => null,
72 20
            'CI' => 'true',
73
            'PIPELINES_CONTAINER_NAME' => null,
74
            'PIPELINES_IDS' => null,
75
            'PIPELINES_PARENT_CONTAINER_NAME' => null,
76
            'PIPELINES_PROJECT_PATH' => null,
77
        );
78
79
        $invariant = array(
80 20
            'PIPELINES_ID' => null,
81
        );
82
83 20
        foreach ($inheritable as $name => $value) {
84 20
            isset($inherit[$name]) ? $inheritable[$name] = $inherit[$name] : null;
85
        }
86
87 20
        $var = $invariant + $inheritable;
88 20
        ksort($var);
89
90 20
        $this->vars = $var;
91 20
    }
92
93
    /**
94
     * Map reference to environment variable setting
95
     *
96
     * Only add the BITBUCKET_BOOKMARK/_BRANCH/_TAG variable
97
     * if not yet set.
98
     *
99
     * @param Reference $ref
100
     */
101 4
    public function addReference(Reference $ref)
102
    {
103 4
        if (null === $type = $ref->getType()) {
104 2
            return;
105
        }
106
107
        $map = array(
108 4
            'bookmark' => 'BITBUCKET_BOOKMARK',
109
            'branch' => 'BITBUCKET_BRANCH',
110
            'tag' => 'BITBUCKET_TAG',
111
            'pr' => 'BITBUCKET_BRANCH',
112
        );
113
114 4
        if (!isset($map[$type])) {
115 1
            throw new \UnexpectedValueException(sprintf('Unknown reference type: "%s"', $type));
116
        }
117 3
        $var = $map[$type];
118
119 3
        if (!isset($this->vars[$var])) {
120 2
            $this->vars[$var] = $ref->getName();
121
        }
122 3
    }
123
124
    /**
125
     * @param string $name of container
126
     */
127 2
    public function setContainerName($name)
128
    {
129 2
        if (isset($this->vars['PIPELINES_CONTAINER_NAME'])) {
130 2
            $this->vars['PIPELINES_PARENT_CONTAINER_NAME']
131 2
                = $this->vars['PIPELINES_CONTAINER_NAME'];
132
        }
133
134 2
        $this->vars['PIPELINES_CONTAINER_NAME'] = $name;
135 2
    }
136
137
    /**
138
     * set the pipelines environment's running pipeline id
139
     *
140
     * @param string $id of pipeline, e.g. "default" or "branch/feature/*"
141
     *
142
     * @return bool whether was used before (endless pipelines in pipelines loop)
143
     */
144 2
    public function setPipelinesId($id)
145
    {
146 2
        $list = (string)$this->getValue('PIPELINES_IDS');
147 2
        $hashes = preg_split('~\s+~', $list, -1, PREG_SPLIT_NO_EMPTY);
148 2
        $hashes = array_map('strtolower', /** @scrutinizer ignore-type */ $hashes);
149
150 2
        $idHash = md5($id);
151 2
        $hasId = in_array($idHash, $hashes, true);
152 2
        $hashes[] = $idHash;
153
154 2
        $this->vars['PIPELINES_ID'] = $id;
155 2
        $this->vars['PIPELINES_IDS'] = implode(' ', $hashes);
156
157 2
        return $hasId;
158
    }
159
160
    /**
161
     * set PIPELINES_PROJECT_PATH
162
     *
163
     * can never be overwritten, must be set by pipelines itself for the
164
     * initial pipeline. will be taken over into each sub-pipeline.
165
     *
166
     * @param string $path absolute path to the project directory (deploy source path)
167
     */
168 1
    public function setPipelinesProjectPath($path)
169
    {
170
        // TODO $path must be absolute
171
172 1
        if (isset($this->vars['PIPELINES_PROJECT_PATH'])
173 1
            || !isset($this->vars['PIPELINES_ID'], $this->vars['PIPELINES_IDS'])
174 1
            || $this->vars['PIPELINES_IDS'] !== md5($this->vars['PIPELINES_ID'])
175
        ) {
176 1
            return;
177
        }
178
179 1
        $this->vars['PIPELINES_PROJECT_PATH'] = $path;
180 1
    }
181
182
    /**
183
     * @param null|string $default [optional]
184
     *
185
     * @return null|string
186
     */
187 1
    public function getPipelinesProjectPath($default = null)
188
    {
189 1
        if (isset($this->vars['PIPELINES_PROJECT_PATH'])) {
190 1
            return $this->vars['PIPELINES_PROJECT_PATH'];
191
        }
192
193 1
        return $default;
194
    }
195
196
    /**
197
     * @param string $option "-e" typically for Docker binary
198
     *
199
     * @return array of options (from $option) and values, ['-e', 'val1', '-e', 'val2', ...]
200
     */
201 12
    public function getArgs($option)
202
    {
203 12
        $args = $this->collected;
204
205 12
        foreach ($this->getVarDefinitions() as $definition) {
206 11
            $args[] = $option;
207 11
            $args[] = $definition;
208
        }
209
210 12
        return $args;
211
    }
212
213
    /**
214
     * get a variables' value from the inherited
215
     * environment or null if not set
216
     *
217
     * @param $name
218
     *
219
     * @return null|string
220
     */
221 1
    public function getInheritValue($name)
222
    {
223 1
        return isset($this->inherit[$name])
224 1
            ? $this->inherit[$name]
225 1
            : null;
226
    }
227
228
    /**
229
     * get a variables value or null if not set
230
     *
231
     * @param string $name
232
     *
233
     * @return null|string
234
     */
235 6
    public function getValue($name)
236
    {
237 6
        return isset($this->vars[$name])
238 4
            ? $this->vars[$name]
239 6
            : null;
240
    }
241
242
    /**
243
     * collect option arguments
244
     *
245
     * those options to be passed to docker client, normally -e,
246
     * --env and --env-file.
247
     *
248
     * @param Args $args
249
     * @param string|string[] $option
250
     *
251
     * @throws \InvalidArgumentException
252
     * @throws \Ktomk\Pipelines\Cli\ArgsException
253
     */
254 1
    public function collect(Args $args, $option)
255
    {
256 1
        $collector = new Collector($args);
257 1
        $collector->collect($option);
258 1
        $this->collected = array_merge($this->collected, $collector->getArgs());
259
260 1
        $this->getResolver()->addArguments($collector);
261 1
    }
262
263
    /**
264
     * @param array $paths
265
     *
266
     * @throws \InvalidArgumentException
267
     */
268 2
    public function collectFiles(array $paths)
269
    {
270 2
        $resolver = $this->getResolver();
271 2
        foreach ($paths as $path) {
272 2
            if ($resolver->addFileIfExists($path)) {
273 2
                $this->collected[] = '--env-file';
274 2
                $this->collected[] = $path;
275
            }
276
        }
277 2
    }
278
279
    /**
280
     * @return EnvResolver
281
     */
282 4
    public function getResolver()
283
    {
284 4
        if (null === $this->resolver) {
285 4
            $this->resolver = new EnvResolver($this->inherit);
286
        }
287
288 4
        return $this->resolver;
289
    }
290
291
    /**
292
     * @return array w/ a string variable definition (name=value) per value
293
     */
294 12
    private function getVarDefinitions()
295
    {
296 12
        $array = array();
297
298 12
        foreach ($this->vars as $name => $value) {
299 11
            if (isset($value)) {
300 11
                $array[] = sprintf('%s=%s', $name, $value);
301
            }
302
        }
303
304 12
        return $array;
305
    }
306
}
307