Completed
Push — master ( 95a54c...7178fa )
by Samuel
10:58
created

BashFileManipulator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 55
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getVariablePattern() 0 4 1
A getValue() 0 8 2
A replaceValue() 0 11 2
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