MailRenderer::__construct()   A
last analyzed

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(sprintf('View cannot render template `%s` because it does not exist', $template));
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) {
54
            // PHP 7+
55
            ob_end_clean();
56
            throw $e;
57
        } catch (\Exception $e) {
58
            // PHP < 7
59
            ob_end_clean();
60
            throw $e;
61
        }
62
63
        return $output;
64
    }
65
66
    /**
67
     * @param string $template
68
     * @param array $data
69
     */
70
    protected function protectedIncludeScope($template, array $data)
71
    {
72
        extract($data);
73
        include $template;
74
    }
75
}
76