Completed
Push — master ( 003c1a...870291 )
by Tomáš
06:24
created

ControllerRenderTrait::renderView()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Symplify
7
 * Copyright (c) 2016 Tomas Votruba (http://tomasvotruba.cz).
8
 */
9
10
namespace Symplify\ControllerAutowire\Controller\Templating;
11
12
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
13
use Symfony\Component\HttpFoundation\Response;
14
use Symfony\Component\HttpFoundation\StreamedResponse;
15
use Twig_Environment;
16
17
trait ControllerRenderTrait
18
{
19
    /**
20
     * @var EngineInterface
21
     */
22
    private $templating;
23
24
    /**
25
     * @var Twig_Environment
26
     */
27
    private $twig;
28
29
    public function setTemplating(EngineInterface $templating)
30
    {
31
        $this->templating = $templating;
32
    }
33
34
    public function setTwig(Twig_Environment $twig)
35
    {
36
        $this->twig = $twig;
37
    }
38
39
    protected function renderView(string $view, array $parameters = []) : string
40
    {
41
        if ($this->templating) {
42
            return $this->templating->render($view, $parameters);
43
        }
44
45
        return $this->twig->render($view, $parameters);
46
    }
47
48
    protected function render(string $view, array $parameters = [], Response $response = null) : Response
49
    {
50
        if ($this->templating) {
51
            return $this->templating->renderResponse($view, $parameters, $response);
52
        }
53
54
        if (null === $response) {
55
            $response = new Response();
56
        }
57
58
        return $response->setContent($this->twig->render($view, $parameters));
59
    }
60
61
    protected function stream(
62
        string $view,
63
        array $parameters = [],
64
        StreamedResponse $response = null
65
    ) : StreamedResponse {
66
        if ($this->templating) {
67
            $callback = function () use ($view, $parameters) {
68
                $this->templating->stream($view, $parameters);
69
            };
70
        } else {
71
            $callback = function () use ($view, $parameters) {
72
                $this->twig->display($view, $parameters);
73
            };
74
        }
75
76
        if ($response === null) {
77
            return new StreamedResponse($callback);
78
        }
79
80
        $response->setCallback($callback);
81
82
        return $response;
83
    }
84
}
85