Completed
Pull Request — master (#399)
by Elan
01:09
created

AbstractController::render()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace XHGui;
4
5
use Psr\Container\ContainerInterface;
6
use Slim\Http\Response;
7
use Slim\Slim as App;
8
use Slim\Views\Twig;
9
10
abstract class AbstractController
11
{
12
    /**
13
     * @var array
14
     */
15
    protected $_templateVars = [];
16
17
    /**
18
     * @var string|null
19
     */
20
    protected $_template = null;
21
22
    /**
23
     * @var App
24
     */
25
    protected $app;
26
27
    public function __construct(App $app)
28
    {
29
        $this->app = $app;
30
    }
31
32
    public function set($vars)
33
    {
34
        $this->_templateVars = array_merge($this->_templateVars, $vars);
35
    }
36
37
    public function templateVars()
38
    {
39
        return $this->_templateVars;
40
    }
41
42
    /** @see RenderMiddleware */
43
    public function renderView()
44
    {
45
        // We want to render the specified Twig template to the output buffer.
46
        // The simplest way to do that is Slim::render, but that is not allowed
47
        // in middleware, because it uses Slim\View::display which prints
48
        // directly to the native PHP output buffer.
49
        // Doing that is problematic, because the HTTP headers set via $app->response()
50
        // must be output first, which won't happen until after the middleware
51
        // is completed. Output of headers and body is done by the Slim::run entry point.
52
53
        // The below is copied from Slim::render (slim/[email protected]).
54
        // Modified to use View::fetch + Response::write, instead of View::display.
55
        $this->render($this->_template, $this->_templateVars);
56
    }
57
58
    protected function config(string $key)
59
    {
60
        return $this->app->config($key);
61
    }
62
63
    protected function render(string $template, array $data = [])
64
    {
65
        /** @var Response $response */
66
        $response = $this->app->response;
67
        /** @var Twig $renderer */
68
        $renderer = $this->app->view;
69
70
        $renderer->appendData($data);
71
        $body = $renderer->fetch($template);
72
        $response->write($body);
73
    }
74
}
75