1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\HttpKernel\Tests\Fragment;
13
14use PHPUnit\Framework\TestCase;
15use Symfony\Component\HttpFoundation\Request;
16use Symfony\Component\HttpFoundation\Response;
17use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
18
19/**
20 * @group time-sensitive
21 */
22class FragmentHandlerTest extends TestCase
23{
24    private $requestStack;
25
26    protected function setUp()
27    {
28        $this->requestStack = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\RequestStack')
29            ->disableOriginalConstructor()
30            ->getMock()
31        ;
32        $this->requestStack
33            ->expects($this->any())
34            ->method('getCurrentRequest')
35            ->willReturn(Request::create('/'))
36        ;
37    }
38
39    public function testRenderWhenRendererDoesNotExist()
40    {
41        $this->expectException('InvalidArgumentException');
42        $handler = new FragmentHandler($this->requestStack);
43        $handler->render('/', 'foo');
44    }
45
46    public function testRenderWithUnknownRenderer()
47    {
48        $this->expectException('InvalidArgumentException');
49        $handler = $this->getHandler($this->returnValue(new Response('foo')));
50
51        $handler->render('/', 'bar');
52    }
53
54    public function testDeliverWithUnsuccessfulResponse()
55    {
56        $this->expectException('RuntimeException');
57        $this->expectExceptionMessage('Error when rendering "http://localhost/" (Status code is 404).');
58        $handler = $this->getHandler($this->returnValue(new Response('foo', 404)));
59
60        $handler->render('/', 'foo');
61    }
62
63    public function testRender()
64    {
65        $handler = $this->getHandler($this->returnValue(new Response('foo')), ['/', Request::create('/'), ['foo' => 'foo', 'ignore_errors' => true]]);
66
67        $this->assertEquals('foo', $handler->render('/', 'foo', ['foo' => 'foo']));
68    }
69
70    protected function getHandler($returnValue, $arguments = [])
71    {
72        $renderer = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface')->getMock();
73        $renderer
74            ->expects($this->any())
75            ->method('getName')
76            ->willReturn('foo')
77        ;
78        $e = $renderer
79            ->expects($this->any())
80            ->method('render')
81            ->will($returnValue)
82        ;
83
84        if ($arguments) {
85            \call_user_func_array([$e, 'with'], $arguments);
86        }
87
88        $handler = new FragmentHandler($this->requestStack);
89        $handler->addRenderer($renderer);
90
91        return $handler;
92    }
93}
94