Passed
Push — master ( 9e0b2c...e0b23c )
by Pol
03:34
created

ProcessConfigFile::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 2
dl 0
loc 6
ccs 0
cts 6
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace PhpTaskman\Core\Robo\Task\ProcessConfigFile;
6
7
use PhpTaskman\Core\Contract\ConfigurationTokensAwareInterface;
8
use PhpTaskman\Core\Traits\ConfigurationTokensTrait;
9
use Robo\Common\BuilderAwareTrait;
10
use Robo\Contract\BuilderAwareInterface;
11
use Robo\Exception\TaskException;
12
use Robo\Result;
13
use Robo\Task\BaseTask;
14
use Robo\Task\File\Replace;
15
use Robo\Task\Filesystem\FilesystemStack;
16
17
/**
18
 * Class ProcessConfigFile.
19
 */
20
final class ProcessConfigFile extends BaseTask implements BuilderAwareInterface, ConfigurationTokensAwareInterface
21
{
22
    use BuilderAwareTrait;
23
    use ConfigurationTokensTrait;
24
25
    /**
26
     * Destination file.
27
     *
28
     * @var string
29
     */
30
    protected $destination;
31
32
    /**
33
     * @var FilesystemStack
34
     */
35
    protected $filesystem;
36
37
    /**
38
     * @var Replace
39
     */
40
    protected $replace;
41
42
    /**
43
     * Source file.
44
     *
45
     * @var string
46
     */
47
    protected $source;
48
49
    /**
50
     * ProcessConfigFile constructor.
51
     *
52
     * @param string $source
53
     * @param string $destination
54
     */
55
    public function __construct($source, $destination)
56
    {
57
        $this->source = $source;
58
        $this->destination = $destination;
59
        $this->filesystem = new FilesystemStack();
60
        $this->replace = new Replace($destination);
61
    }
62
63
    /**
64
     * @throws TaskException
65
     *
66
     * @return Result
67
     */
68
    public function run()
69
    {
70
        if (false === $fileContent = \file_get_contents($this->source)) {
71
            throw new TaskException($this, "Source file '{$this->source}' does not exists.");
72
        }
73
74
        $tokens = $this->extractProcessedTokens($fileContent);
75
76
        $tasks = [];
77
        if ($this->source !== $this->destination) {
78
            $tasks[] = $this->filesystem->copy($this->source, $this->destination, true);
79
        }
80
        $tasks[] = $this->replace->from(\array_keys($tokens))->to(\array_values($tokens));
81
82
        return $this->collectionBuilder()->addTaskList($tasks)->run();
83
    }
84
}
85