Completed
Push — master ( 9b2b5f...28e902 )
by Sebastian
03:28
created

Template::format()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
crap 1
1
<?php
2
namespace phpbu\App\Log\ResultFormatter;
3
4
use phpbu\App\Exception;
5
use phpbu\App\Log\ResultFormatter;
6
use phpbu\App\Result;
7
8
/**
9
 * Template ResultFormatter
10
 *
11
 * @package    phpbu
12
 * @subpackage Log
13
 * @author     Sebastian Feldmann <[email protected]>
14
 * @copyright  Sebastian Feldmann <[email protected]>
15
 * @license    https://opensource.org/licenses/MIT The MIT License (MIT)
16
 * @link       https://phpbu.de/
17
 * @since      Class available since Release 5.0.0
18
 */
19
class Template extends Abstraction implements ResultFormatter
20
{
21
    /**
22
     * Template markup code
23
     *
24
     * @var string
25
     */
26
    private $template;
27
28
    /**
29
     * Template constructor.
30
     *
31
     * @param string $file
32
     */
33 3
    public function __construct(string $file)
34
    {
35 3
        $this->template = $this->loadBodyFromTemplate($file);
36 2
    }
37
38
    /**
39
     * Loads the body template if it exists.
40
     *
41
     * @param  string $template
42
     * @return string
43
     * @throws \phpbu\App\Exception
44
     */
45 3
    private function loadBodyFromTemplate(string $template) : string
46
    {
47 3
        if (!file_exists($template)) {
48 1
            throw new Exception('template not found: ' . $template);
49
        }
50 2
        return file_get_contents($template);
51
    }
52
53
    /**
54
     * Create request body from phpbu result data.
55
     *
56
     * @param  \phpbu\App\Result $result
57
     * @return string
58
     */
59 2
    public function format(Result $result): string
60
    {
61 2
        $data           = $this->getSummaryData($result);
62 2
        $this->template = $this->renderTemplate($this->template, $data);
63
64
        // replace error loop
65
        // manipulates $this->template
66 2
        $this->handleErrors($result);
67
68
        // replace backup loop
69
        // manipulates $this->template
70 2
        $this->handleBackups($result);
71
72 2
        return $this->template;
73
    }
74
75
    /**
76
     * Handles error sub template rendering if necessary.
77
     *   - Manipulates $this->template
78
     *
79
     * @param \phpbu\App\Result $result
80
     */
81 2 View Code Duplication
    private function handleErrors(Result $result)
82
    {
83 2
        $errorTpl = $this->extractSubTemplate($this->template, 'error');
84
85 2
        if (!empty($errorTpl)) {
86 2
            $errorLoopMarkup = $this->renderErrors($errorTpl, $result->getErrors());
87 2
            $this->renderLoop('error', $errorLoopMarkup);
88
        }
89 2
    }
90
91
    /**
92
     * Handles backup sub template rendreing if necessary.
93
     *   - Manipulates $this->template
94
     *
95
     * @param \phpbu\App\Result $result
96
     */
97 2 View Code Duplication
    private function handleBackups(Result $result)
98
    {
99 2
        $backupTpl = $this->extractSubTemplate($this->template, 'backup');
100
101 2
        if (!empty($backupTpl)) {
102 2
            $backupLoopMarkup = $this->renderBackups($backupTpl, $result->getBackups());
103 2
            $this->renderLoop('backup', $backupLoopMarkup);
104
        }
105 2
    }
106
107
    /**
108
     * Extract loop template.
109
     *
110
     * @param  string $template
111
     * @param  string $loop
112
     * @return string
113
     */
114 2
    private function extractSubTemplate(string $template, string $loop) : string
115
    {
116 2
        $subTemplate = '';
117 2
        $match       = [];
118 2
        if (preg_match('#%%' . $loop . '%%([\w\W\s]*)%%' . $loop . '%%#im', $template, $match)) {
119 2
            $subTemplate = $match[1];
120
        }
121 2
        return $subTemplate;
122
    }
123
124
    /**
125
     * Renders errors with extracted error sub template.
126
     *
127
     * @param  string $errorTpl
128
     * @param  array  $errors
129
     * @return string
130
     */
131 2
    private function renderErrors(string $errorTpl, array $errors) : string
132
    {
133 2
        $markup = '';
134
        /* @var $e \Exception */
135 2
        foreach ($errors as $e) {
136
            $data   = [
137 2
                'class'   => get_class($e),
138 2
                'message' => $e->getMessage(),
139 2
                'file'    => $e->getFile(),
140 2
                'line'    => $e->getLine()
141
            ];
142 2
            $markup = $this->renderTemplate($errorTpl, $data);
143
        }
144 2
        return $markup;
145
    }
146
147
    /**
148
     * Renders backups with the extracted sub template.
149
     *
150
     * @param  string $backupTpl
151
     * @param  array  $backups
152
     * @return string
153
     */
154 2
    private function renderBackups(string $backupTpl, array $backups) : string
155
    {
156 2
        $markup = '';
157
        /* @var $b \phpbu\App\Result\Backup */
158 2
        foreach ($backups as $b) {
159
            $data   = [
160 2
                'name'           => $b->getName(),
161 2
                'status'         => $b->allOk() ? 0 : 1,
162 2
                'checkCount'     => $b->checkCount(),
163 2
                'checkFailed'    => $b->checkCountFailed(),
164 2
                'cryptCount'     => $b->cryptCount(),
165 2
                'cryptFailed'    => $b->cryptCountFailed(),
166 2
                'cryptSkipped'   => $b->cryptCountSkipped(),
167 2
                'syncCount'      => $b->syncCount(),
168 2
                'syncFailed'     => $b->syncCountFailed(),
169 2
                'syncSkipped'    => $b->syncCountSkipped(),
170 2
                'cleanupCount'   => $b->cleanupCount(),
171 2
                'cleanupFailed'  => $b->cleanupCountFailed(),
172 2
                'cleanupSkipped' => $b->cleanupCountSkipped(),
173
            ];
174 2
            $markup = $this->renderTemplate($backupTpl, $data);
175
        }
176 2
        return $markup;
177
    }
178
179
    /**
180
     * Replace %name% placeholders in a string with [name => value].
181
     *
182
     * @param  string $template
183
     * @param  array  $data
184
     * @return string
185
     */
186 2
    private function renderTemplate(string $template, array $data) : string
187
    {
188 2
        foreach ($data as $name => $value) {
189 2
            $template = str_replace('%' . $name . '%', $value, $template);
190
        }
191 2
        return $template;
192
    }
193
194
    /**
195
     * Replace a loop placeholder %%loopname%% with some pre rendered markup.
196
     *
197
     * @param  string $loop
198
     * @param  string $markup
199
     */
200 2
    private function renderLoop(string $loop, string $markup)
201
    {
202 2
        $this->template = preg_replace('#%%' . $loop . '%%[\w\W\s]*%%' . $loop . '%%#im', $markup, $this->template);
203 2
    }
204
}
205