Completed
Push — master ( 5755a3...7725bc )
by Samuel
07:29 queued 03:35
created

BashFileManipulator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Dock\System\Bash;
4
5
use Dock\IO\FileManipulator;
6
7
class BashFileManipulator
8
{
9
    /**
10
     * @var FileManipulator
11
     */
12
    private $fileManipulator;
13
14
    /**
15
     * @param FileManipulator $fileManipulator
16
     */
17
    public function __construct(FileManipulator $fileManipulator)
18
    {
19
        $this->fileManipulator = $fileManipulator;
20
    }
21
22
    /**
23
     * @param string $variableName
24
     *
25
     * @return string|null
26
     */
27
    public function getValue($variableName)
28
    {
29
        if (preg_match($this->getVariablePattern($variableName), $this->fileManipulator->read(), $matches)) {
30
            return trim($matches[1]);
31
        }
32
33
        return;
34
    }
35
36
    /**
37
     * @param string $variableName
38
     * @param string $value
39
     */
40
    public function replaceValue($variableName, $value)
41
    {
42
        $variableDeclaration = $variableName.'=\''.$value.'\'';
43
        if (null === $this->getValue($variableName)) {
44
            $contents = $this->fileManipulator->read().PHP_EOL.$variableDeclaration;
45
        } else {
46
            $contents = preg_replace($this->getVariablePattern($variableName), $variableDeclaration, $this->fileManipulator->read());
47
        }
48
49
        $this->fileManipulator->write($contents);
50
    }
51
52
    /**
53
     * @param string $variableName
54
     *
55
     * @return string
56
     */
57
    private function getVariablePattern($variableName)
58
    {
59
        return '/'.$variableName.'=\'?([^\']*)\'?/mi';
60
    }
61
}
62