CronUpdater::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace MyBuilder\Cronos\Updater;
4
5
use MyBuilder\Cronos\Formatter\Cron;
6
7
class CronUpdater
8
{
9
    public const KEY_BEGIN = '# KEY %key%';
10
    public const KEY_END = '# END';
11
12
    /** @var CronManipulator */
13
    private $cronManipulator;
14
15
    public function __construct(CronManipulator $cronManipulator)
16
    {
17
        $this->cronManipulator = $cronManipulator;
18
    }
19
20
    public static function createDefault(): self
21
    {
22
        return new self(new CommandCronManipulator(new SymfonyProcessRunner, new StandardFileSystem));
23
    }
24
25
    public function replaceWith(Cron $cron): void
26
    {
27
        $this->cronManipulator->replace($cron->format());
28
    }
29
30
    public function updateWith(Cron $cron, string $key): void
31
    {
32
        $this->cronManipulator->replace($this->updateContent($cron, $key));
33
    }
34
35
    private function updateContent(Cron $cron, string $key): string
36
    {
37
        $content = $this->cronManipulator->getContent();
38
39
        $count = 0;
40
        $pattern = '/\r?\n' . $this->beginKey($key) . '.*?' . self::KEY_END . '/s';
41
        $replacedContent = \preg_replace($pattern, $this->wrapInKey($cron, $key), $content, -1, $count);
42
43
        if ($count > 0) {
44
            return $replacedContent;
45
        }
46
47
        return $this->appendContent($cron, $key, $content);
48
    }
49
50
    private function wrapInKey(Cron $cron, string $key): string
51
    {
52
        return \PHP_EOL . $this->beginKey($key) . \PHP_EOL . \trim($cron->format()) . \PHP_EOL . self::KEY_END;
53
    }
54
55
    private function beginKey(string $key): string
56
    {
57
        return \str_replace('%key%', $key, self::KEY_BEGIN);
58
    }
59
60
    private function appendContent(Cron $cron, string $key, string $content): string
61
    {
62
        return $content . $this->wrapInKey($cron, $key) . \PHP_EOL;
63
    }
64
}
65