Completed
Push — master ( 8efac5...a0c6e2 )
by Gabor
04:36
created

TwigRendererAdapter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 0
cts 9
cp 0
rs 9.4285
cc 1
eloc 7
nc 1
nop 2
crap 2
1
<?php
2
/**
3
 * WebHemi.
4
 *
5
 * PHP version 5.6
6
 *
7
 * @copyright 2012 - 2016 Gixx-web (http://www.gixx-web.com)
8
 * @license   https://opensource.org/licenses/MIT The MIT License (MIT)
9
 *
10
 * @link      http://www.gixx-web.com
11
 */
12
namespace WebHemi\Adapter\Renderer\Twig;
13
14
use InvalidArgumentException;
15
use Psr\Http\Message\StreamInterface;
16
use Twig_Environment;
17
use Twig_Extension_Debug;
18
use Twig_Loader_Filesystem;
19
use WebHemi\Adapter\Renderer\RendererAdapterInterface;
20
use WebHemi\Config\ConfigInterface;
21
22
/**
23
 * Class TwigRendererAdapter.
24
 */
25
class TwigRendererAdapter implements RendererAdapterInterface
26
{
27
    private $adapter;
28
    /** @var ConfigInterface */
29
    private $config;
30
    /** @var string */
31
    private $templateViewPath;
32
    /** @var string */
33
    private $templateResourcePath;
34
35
    /**
36
     * RendererAdapterInterface constructor.
37
     *
38
     * @param ConfigInterface $templateConfig
39
     * @param string          $templatePath
40
     */
41
    public function __construct(ConfigInterface $templateConfig, $templatePath)
42
    {
43
        $this->config = $templateConfig;
44
        $this->templateViewPath = realpath(__DIR__.'/../../../../../').$templatePath.'/view';
45
        $this->templateResourcePath = $templatePath.'/static';
46
47
        $loader = new Twig_Loader_Filesystem($this->templateViewPath);
48
        $this->adapter = new Twig_Environment($loader, array('debug' => true));
49
        $this->adapter->addExtension(new Twig_Extension_Debug());
50
    }
51
52
    /**
53
     * Renders the template for the output.
54
     *
55
     * @param string $template
56
     * @param array  $parameters
57
     *
58
     * @throws InvalidArgumentException
59
     *
60
     * @return StreamInterface
61
     */
62
    public function render($template, $parameters = [])
63
    {
64
        if ($this->config->has('map/'.$template)) {
65
            $template = $this->config->getData('map/'.$template);
66
        }
67
68
        if (!file_exists($this->templateViewPath.'/'.$template)) {
69
            throw new InvalidArgumentException(sprintf('Unable to render file: "%s". No such file.', $template));
70
        }
71
72
        // Tell the template where the resources are.
73
        $parameters['template_resource_path'] = $this->templateResourcePath;
74
75
        $output = $this->adapter->render($template, $parameters);
76
77
        // The ugliest shit ever. But that is how they made it... :/
78
        return \GuzzleHttp\Psr7\stream_for($output);
79
    }
80
}
81