Completed
Push — master ( f65d8f...4f3de5 )
by Pavel
04:14 queued 01:54
created

MailRenderer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace App\Common;
3
4
class MailRenderer
5
{
6
    /**
7
     * @var string
8
     */
9
    protected $templatePath;
10
11
    /**
12
     * @var array
13
     */
14
    protected $attributes;
15
16
    /**
17
     * MailRenderer constructor.
18
     *
19
     * @param string $templatePath
20
     * @param array $attributes
21
     */
22
    public function __construct($templatePath = '', $attributes = [])
23
    {
24
        $this->templatePath = rtrim($templatePath, '/\\') . '/';
25
        $this->attributes = $attributes;
26
    }
27
28
    /**
29
     * Render a template
30
     * @param string $template
31
     * @param array $data
32
     *
33
     * @return string
34
     * @throws \Exception
35
     * @throws \Throwable
36
     */
37
    public function render($template, array $data = [])
38
    {
39
        if (isset($data['template'])) {
40
            throw new \InvalidArgumentException('Duplicate template key found');
41
        }
42
43
        if (!is_file($this->templatePath . $template)) {
44
            throw new \RuntimeException('View cannot render `$template` because the template does not exist');
45
        }
46
47
        $data = array_merge($this->attributes, $data);
48
49
        try {
50
            ob_start();
51
            $this->protectedIncludeScope($this->templatePath . $template, $data);
52
            $output = ob_get_clean();
53
        } catch(\Throwable $e) { // PHP 7+
54
            ob_end_clean();
55
            throw $e;
56
        } catch(\Exception $e) { // PHP < 7
57
            ob_end_clean();
58
            throw $e;
59
        }
60
61
        return $output;
62
    }
63
64
    /**
65
     * @param string $template
66
     * @param array $data
67
     */
68
    protected function protectedIncludeScope ($template, array $data)
69
    {
70
        extract($data);
71
        include $template;
72
    }
73
}
74