Passed
Push — test ( 7d3b45...f494b8 )
by Tom
03:36
created

EnvVar::__toString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines\Value\Env;
6
7
/**
8
 * -e, --env <value>
9
 */
10
class EnvVar
11
{
12
    const PATTERN = '~^([^\\x0-\\x20$={}\\x7f-\\xff-]+)(?:=([^\\0]*))?$~';
13
14
    /**
15
     * @var array
16
     */
17
    private $expression;
18
19
    /**
20
     * @param string $env
21
     */
22 14
    public function __construct($env)
23
    {
24 14
        $this->parseDefinition((string)$env);
25
    }
26
27 3
    public function __toString()
28
    {
29 3
        list($name, $value) = $this->expression;
30
31 3
        return $name . (isset($value) ? '=' . $value : '');
32
    }
33
34
    /**
35
     * @return string
36
     */
37 1
    public function getName()
38
    {
39 1
        return $this->expression[0];
40
    }
41
42
    /**
43
     * @return null|string
44
     */
45 1
    public function tryValue()
46
    {
47 1
        return $this->expression[1];
48
    }
49
50 2
    public function getValue()
51
    {
52 2
        $value = $this->expression[1];
53 2
        if (null === $value) {
54 1
            throw new \BadFunctionCallException(
55 1
                sprintf('Environment variable %s has no value', $this->expression[0])
56
            );
57
        }
58
59 1
        return $value;
60
    }
61
62
    /**
63
     * @return array{string, string|null}
0 ignored issues
show
Documentation Bug introduced by
The doc comment array{string, string|null} at position 2 could not be parsed: Expected ':' at position 2, but found 'string'.
Loading history...
64
     */
65 3
    public function getPair()
66
    {
67 3
        return $this->expression;
68
    }
69
70
    /**
71
     * @param string $definition
72
     *
73
     * @return void
74
     */
75 14
    private function parseDefinition($definition)
76
    {
77 14
        $result = preg_match(self::PATTERN, $definition, $matches);
78 14
        if (0 === $result) {
79 4
            throw new \InvalidArgumentException(sprintf(
80
                'Environment variable error: %s',
81 4
                addcslashes($definition, "\0..\40\\\177..\377")
82
            ));
83
        }
84
85
        /** @var array{0: string, 1: string, 2: null|string} $matches */
86
87 10
        list(, $name, $value) = $matches + array(2 => null);
88
89 10
        $this->expression = array($name, $value);
90
    }
91
}
92