forked from symfony/symfony
/
InlineFragmentRenderer.php
104 lines (87 loc) · 2.84 KB
/
InlineFragmentRenderer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Fragment;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
/**
* Implements the inline rendering strategy where the Request is rendered by the current HTTP kernel.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class InlineFragmentRenderer extends RoutableFragmentRenderer
{
private $kernel;
/**
* Constructor.
*
* @param HttpKernelInterface $kernel A HttpKernelInterface instance
*/
public function __construct(HttpKernelInterface $kernel)
{
$this->kernel = $kernel;
}
/**
* {@inheritdoc}
*
* Additional available options:
*
* * alt: an alternative URI to render in case of an error
*/
public function render($uri, Request $request, array $options = array())
{
$reference = null;
if ($uri instanceof ControllerReference) {
$reference = $uri;
$uri = $this->generateFragmentUri($uri, $request);
}
$subRequest = $this->createSubRequest($uri, $request);
// override Request attributes as they can be objects (which are not supported by the generated URI)
if (null !== $reference) {
$subRequest->attributes->add($reference->attributes);
}
$level = ob_get_level();
try {
return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
} catch (\Exception $e) {
// let's clean up the output buffers that were created by the sub-request
while (ob_get_level() > $level) {
ob_get_clean();
}
if (isset($options['alt'])) {
$alt = $options['alt'];
unset($options['alt']);
return $this->render($alt, $request, $options);
}
if (!isset($options['ignore_errors']) || !$options['ignore_errors']) {
throw $e;
}
return new Response();
}
}
protected function createSubRequest($uri, Request $request)
{
$cookies = $request->cookies->all();
$server = $request->server->all();
$subRequest = $request::create($uri, 'get', array(), $cookies, array(), $server);
if ($session = $request->getSession()) {
$subRequest->setSession($session);
}
return $subRequest;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'inline';
}
}