This commit is contained in:
Xes
2025-08-14 22:41:49 +02:00
parent 2de81ccc46
commit 8ce45119b6
39774 changed files with 4309466 additions and 0 deletions

View File

@@ -0,0 +1,187 @@
<?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\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Component\ClassLoader\ClassLoader;
class ControllerNameParserTest extends TestCase
{
protected $loader;
protected function setUp()
{
$this->loader = new ClassLoader();
$this->loader->addPrefixes(array(
'TestBundle' => __DIR__.'/../Fixtures',
'TestApplication' => __DIR__.'/../Fixtures',
));
$this->loader->register();
}
protected function tearDown()
{
spl_autoload_unregister(array($this->loader, 'loadClass'));
$this->loader = null;
}
public function testParse()
{
$parser = $this->createParser();
$this->assertEquals('TestBundle\FooBundle\Controller\DefaultController::indexAction', $parser->parse('FooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\FooBundle\Controller\Sub\DefaultController::indexAction', $parser->parse('FooBundle:Sub\Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\Fabpot\FooBundle\Controller\DefaultController::indexAction', $parser->parse('SensioFooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\Sensio\Cms\FooBundle\Controller\DefaultController::indexAction', $parser->parse('SensioCmsFooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\FooBundle\Controller\Test\DefaultController::indexAction', $parser->parse('FooBundle:Test\\Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
$this->assertEquals('TestBundle\FooBundle\Controller\Test\DefaultController::indexAction', $parser->parse('FooBundle:Test/Default:index'), '->parse() converts a short a:b:c notation string to a class::method string');
try {
$parser->parse('foo:');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an a:b:c string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an a:b:c string');
}
}
public function testBuild()
{
$parser = $this->createParser();
$this->assertEquals('FoooooBundle:Default:index', $parser->build('TestBundle\FooBundle\Controller\DefaultController::indexAction'), '->parse() converts a class::method string to a short a:b:c notation string');
$this->assertEquals('FoooooBundle:Sub\Default:index', $parser->build('TestBundle\FooBundle\Controller\Sub\DefaultController::indexAction'), '->parse() converts a class::method string to a short a:b:c notation string');
try {
$parser->build('TestBundle\FooBundle\Controller\DefaultController::index');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
}
try {
$parser->build('TestBundle\FooBundle\Controller\Default::indexAction');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
}
try {
$parser->build('Foo\Controller\DefaultController::indexAction');
$this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string');
}
}
/**
* @dataProvider getMissingControllersTest
*/
public function testMissingControllers($name)
{
$parser = $this->createParser();
try {
$parser->parse($name);
$this->fail('->parse() throws a \InvalidArgumentException if the string is in the valid format, but not matching class can be found');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws a \InvalidArgumentException if the class is found but does not exist');
}
}
public function getMissingControllersTest()
{
return array(
array('FooBundle:Fake:index'), // a normal bundle
array('SensioFooBundle:Fake:index'), // a bundle with children
);
}
/**
* @expectedException
* @dataProvider getInvalidBundleNameTests
*/
public function testInvalidBundleName($bundleName, $suggestedBundleName)
{
$parser = $this->createParser();
try {
$parser->parse($bundleName);
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws a \InvalidArgumentException if the bundle does not exist');
if (false === $suggestedBundleName) {
// make sure we don't have a suggestion
$this->assertNotContains('Did you mean', $e->getMessage());
} else {
$this->assertContains(sprintf('Did you mean "%s"', $suggestedBundleName), $e->getMessage());
}
}
}
public function getInvalidBundleNameTests()
{
return array(
'Alternative will be found using levenshtein' => array('FoodBundle:Default:index', 'FooBundle:Default:index'),
'Alternative will be found using partial match' => array('FabpotFooBund:Default:index', 'FabpotFooBundle:Default:index'),
'Bundle does not exist at all' => array('CrazyBundle:Default:index', false),
);
}
private function createParser()
{
$bundles = array(
'SensioFooBundle' => array($this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')),
'SensioCmsFooBundle' => array($this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle')),
'FooBundle' => array($this->getBundle('TestBundle\FooBundle', 'FooBundle')),
'FabpotFooBundle' => array($this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'), $this->getBundle('TestBundle\Sensio\FooBundle', 'SensioFooBundle')),
);
$kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
$kernel
->expects($this->any())
->method('getBundle')
->will($this->returnCallback(function ($bundle) use ($bundles) {
if (!isset($bundles[$bundle])) {
throw new \InvalidArgumentException(sprintf('Invalid bundle name "%s"', $bundle));
}
return $bundles[$bundle];
}))
;
$bundles = array(
'SensioFooBundle' => $this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'),
'SensioCmsFooBundle' => $this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle'),
'FoooooBundle' => $this->getBundle('TestBundle\FooBundle', 'FoooooBundle'),
'FooBundle' => $this->getBundle('TestBundle\FooBundle', 'FooBundle'),
'FabpotFooBundle' => $this->getBundle('TestBundle\Fabpot\FooBundle', 'FabpotFooBundle'),
);
$kernel
->expects($this->any())
->method('getBundles')
->will($this->returnValue($bundles))
;
return new ControllerNameParser($kernel);
}
private function getBundle($namespace, $name)
{
$bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
$bundle->expects($this->any())->method('getName')->will($this->returnValue($name));
$bundle->expects($this->any())->method('getNamespace')->will($this->returnValue($namespace));
return $bundle;
}
}

View File

@@ -0,0 +1,223 @@
<?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\Bundle\FrameworkBundle\Tests\Controller;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest as BaseControllerResolverTest;
class ControllerResolverTest extends BaseControllerResolverTest
{
public function testGetControllerOnContainerAware()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', 'Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::testAction');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller[0]->getContainer());
$this->assertSame('testAction', $controller[1]);
}
public function testGetControllerOnContainerAwareInvokable()
{
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', 'Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController');
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController', $controller);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller->getContainer());
}
public function testGetControllerWithBundleNotation()
{
$shortName = 'FooBundle:Default:test';
$parser = $this->createMockParser();
$parser->expects($this->once())
->method('parse')
->with($shortName)
->will($this->returnValue('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::testAction'))
;
$resolver = $this->createControllerResolver(null, $parser);
$request = Request::create('/');
$request->attributes->set('_controller', $shortName);
$controller = $resolver->getController($request);
$this->assertInstanceOf('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController', $controller[0]);
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller[0]->getContainer());
$this->assertSame('testAction', $controller[1]);
}
public function testGetControllerService()
{
$container = $this->createMockContainer();
$container->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($this))
;
$resolver = $this->createControllerResolver(null, null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'foo:controllerMethod1');
$controller = $resolver->getController($request);
$this->assertInstanceOf(get_class($this), $controller[0]);
$this->assertSame('controllerMethod1', $controller[1]);
}
public function testGetControllerInvokableService()
{
$invokableController = new InvokableController('bar');
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with('foo')
->will($this->returnValue(true))
;
$container->expects($this->once())
->method('get')
->with('foo')
->will($this->returnValue($invokableController))
;
$resolver = $this->createControllerResolver(null, null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', 'foo');
$controller = $resolver->getController($request);
$this->assertEquals($invokableController, $controller);
}
public function testGetControllerInvokableServiceWithClassNameAsName()
{
$invokableController = new InvokableController('bar');
$className = __NAMESPACE__.'\InvokableController';
$container = $this->createMockContainer();
$container->expects($this->once())
->method('has')
->with($className)
->will($this->returnValue(true))
;
$container->expects($this->once())
->method('get')
->with($className)
->will($this->returnValue($invokableController))
;
$resolver = $this->createControllerResolver(null, null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', $className);
$controller = $resolver->getController($request);
$this->assertEquals($invokableController, $controller);
}
/**
* @dataProvider getUndefinedControllers
*/
public function testGetControllerOnNonUndefinedFunction($controller, $exceptionName = null, $exceptionMessage = null)
{
// All this logic needs to be duplicated, since calling parent::testGetControllerOnNonUndefinedFunction will override the expected excetion and not use the regex
$resolver = $this->createControllerResolver();
$this->setExpectedExceptionRegExp($exceptionName, $exceptionMessage);
$request = Request::create('/');
$request->attributes->set('_controller', $controller);
$resolver->getController($request);
}
public function getUndefinedControllers()
{
return array(
array('foo', '\LogicException', '/Unable to parse the controller name "foo"\./'),
array('oof::bar', '\InvalidArgumentException', '/Class "oof" does not exist\./'),
array('stdClass', '\LogicException', '/Unable to parse the controller name "stdClass"\./'),
array(
'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest::bar',
'\InvalidArgumentException',
'/.?[cC]ontroller(.*?) for URI "\/" is not callable\.( Expected method(.*) Available methods)?/',
),
);
}
protected function createControllerResolver(LoggerInterface $logger = null, ControllerNameParser $parser = null, ContainerInterface $container = null)
{
if (!$parser) {
$parser = $this->createMockParser();
}
if (!$container) {
$container = $this->createMockContainer();
}
return new ControllerResolver($container, $parser, $logger);
}
protected function createMockParser()
{
return $this->getMock('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser', array(), array(), '', false);
}
protected function createMockContainer()
{
return $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
}
}
class ContainerAwareController implements ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function getContainer()
{
return $this->container;
}
public function testAction()
{
}
public function __invoke()
{
}
}
class InvokableController
{
public function __construct($bar) // mandatory argument to prevent automatic instantiation
{
}
public function __invoke()
{
}
}

View File

@@ -0,0 +1,475 @@
<?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\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;
class ControllerTest extends TestCase
{
public function testForward()
{
$request = Request::create('/');
$request->setLocale('fr');
$request->setRequestFormat('xml');
$requestStack = new RequestStack();
$requestStack->push($request);
$kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
return new Response($request->getRequestFormat().'--'.$request->getLocale());
}));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($requestStack));
$container->expects($this->at(1))->method('get')->will($this->returnValue($kernel));
$controller = new TestController();
$controller->setContainer($container);
$response = $controller->forward('a_controller');
$this->assertEquals('xml--fr', $response->getContent());
}
public function testGetUser()
{
$user = new User('user', 'pass');
$token = new UsernamePasswordToken($user, 'pass', 'default', array('ROLE_USER'));
$controller = new TestController();
$controller->setContainer($this->getContainerWithTokenStorage($token));
$this->assertSame($controller->getUser(), $user);
}
public function testGetUserAnonymousUserConvertedToNull()
{
$token = new AnonymousToken('default', 'anon.');
$controller = new TestController();
$controller->setContainer($this->getContainerWithTokenStorage($token));
$this->assertNull($controller->getUser());
}
public function testGetUserWithEmptyTokenStorage()
{
$controller = new TestController();
$controller->setContainer($this->getContainerWithTokenStorage(null));
$this->assertNull($controller->getUser());
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage The SecurityBundle is not registered in your application.
*/
public function testGetUserWithEmptyContainer()
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('has')
->with('security.token_storage')
->will($this->returnValue(false));
$controller = new TestController();
$controller->setContainer($container);
$controller->getUser();
}
/**
* @param $token
*
* @return ContainerInterface
*/
private function getContainerWithTokenStorage($token = null)
{
$tokenStorage = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage');
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue($token));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('has')
->with('security.token_storage')
->will($this->returnValue(true));
$container
->expects($this->once())
->method('get')
->with('security.token_storage')
->will($this->returnValue($tokenStorage));
return $container;
}
public function testIsGranted()
{
$authorizationChecker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(true);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($authorizationChecker));
$controller = new TestController();
$controller->setContainer($container);
$this->assertTrue($controller->isGranted('foo'));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
*/
public function testdenyAccessUnlessGranted()
{
$authorizationChecker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
$authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($authorizationChecker));
$controller = new TestController();
$controller->setContainer($container);
$controller->denyAccessUnlessGranted('foo');
}
public function testRenderViewTwig()
{
$twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(false));
$container->expects($this->at(1))->method('has')->will($this->returnValue(true));
$container->expects($this->at(2))->method('get')->will($this->returnValue($twig));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->renderView('foo'));
}
public function testRenderTwig()
{
$twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock();
$twig->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(false));
$container->expects($this->at(1))->method('has')->will($this->returnValue(true));
$container->expects($this->at(2))->method('get')->will($this->returnValue($twig));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->render('foo')->getContent());
}
public function testStreamTwig()
{
$twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock();
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(false));
$container->expects($this->at(1))->method('has')->will($this->returnValue(true));
$container->expects($this->at(2))->method('get')->will($this->returnValue($twig));
$controller = new TestController();
$controller->setContainer($container);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo'));
}
public function testRedirectToRoute()
{
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($router));
$controller = new TestController();
$controller->setContainer($container);
$response = $controller->redirectToRoute('foo');
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertSame('/foo', $response->getTargetUrl());
$this->assertSame(302, $response->getStatusCode());
}
public function testAddFlash()
{
$flashBag = new FlashBag();
$session = $this->getMock('Symfony\Component\HttpFoundation\Session\Session');
$session->expects($this->once())->method('getFlashBag')->willReturn($flashBag);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($session));
$controller = new TestController();
$controller->setContainer($container);
$controller->addFlash('foo', 'bar');
$this->assertSame(array('bar'), $flashBag->get('foo'));
}
public function testCreateAccessDeniedException()
{
$controller = new TestController();
$this->assertInstanceOf('Symfony\Component\Security\Core\Exception\AccessDeniedException', $controller->createAccessDeniedException());
}
public function testIsCsrfTokenValid()
{
$tokenManager = $this->getMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
$tokenManager->expects($this->once())->method('isTokenValid')->willReturn(true);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($tokenManager));
$controller = new TestController();
$controller->setContainer($container);
$this->assertTrue($controller->isCsrfTokenValid('foo', 'bar'));
}
public function testGenerateUrl()
{
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router->expects($this->once())->method('generate')->willReturn('/foo');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($router));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals('/foo', $controller->generateUrl('foo'));
}
public function testRedirect()
{
$controller = new TestController();
$response = $controller->redirect('http://dunglas.fr', 301);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertSame('http://dunglas.fr', $response->getTargetUrl());
$this->assertSame(301, $response->getStatusCode());
}
public function testRenderViewTemplating()
{
$templating = $this->getMock('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface');
$templating->expects($this->once())->method('render')->willReturn('bar');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->will($this->returnValue($templating));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->renderView('foo'));
}
public function testRenderTemplating()
{
$templating = $this->getMock('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface');
$templating->expects($this->once())->method('renderResponse')->willReturn(new Response('bar'));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->will($this->returnValue($templating));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals('bar', $controller->render('foo')->getContent());
}
public function testStreamTemplating()
{
$templating = $this->getMock('Symfony\Component\Routing\RouterInterface');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->willReturn(true);
$container->expects($this->at(1))->method('get')->will($this->returnValue($templating));
$controller = new TestController();
$controller->setContainer($container);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo'));
}
public function testCreateNotFoundException()
{
$controller = new TestController();
$this->assertInstanceOf('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', $controller->createNotFoundException());
}
public function testCreateForm()
{
$form = $this->getMock('Symfony\Component\Form\FormInterface');
$formFactory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
$formFactory->expects($this->once())->method('create')->willReturn($form);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($formFactory));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals($form, $controller->createForm('foo'));
}
public function testCreateFormBuilder()
{
$formBuilder = $this->getMock('Symfony\Component\Form\FormBuilderInterface');
$formFactory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
$formFactory->expects($this->once())->method('createBuilder')->willReturn($formBuilder);
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('get')->will($this->returnValue($formFactory));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals($formBuilder, $controller->createFormBuilder('foo'));
}
public function testGetDoctrine()
{
$doctrine = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container->expects($this->at(0))->method('has')->will($this->returnValue(true));
$container->expects($this->at(1))->method('get')->will($this->returnValue($doctrine));
$controller = new TestController();
$controller->setContainer($container);
$this->assertEquals($doctrine, $controller->getDoctrine());
}
}
class TestController extends Controller
{
public function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
return parent::generateUrl($route, $parameters, $referenceType);
}
public function redirect($url, $status = 302)
{
return parent::redirect($url, $status);
}
public function forward($controller, array $path = array(), array $query = array())
{
return parent::forward($controller, $path, $query);
}
public function getUser()
{
return parent::getUser();
}
public function isGranted($attributes, $object = null)
{
return parent::isGranted($attributes, $object);
}
public function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')
{
parent::denyAccessUnlessGranted($attributes, $object, $message);
}
public function redirectToRoute($route, array $parameters = array(), $status = 302)
{
return parent::redirectToRoute($route, $parameters, $status);
}
public function addFlash($type, $message)
{
parent::addFlash($type, $message);
}
public function isCsrfTokenValid($id, $token)
{
return parent::isCsrfTokenValid($id, $token);
}
public function renderView($view, array $parameters = array())
{
return parent::renderView($view, $parameters);
}
public function render($view, array $parameters = array(), Response $response = null)
{
return parent::render($view, $parameters, $response);
}
public function stream($view, array $parameters = array(), StreamedResponse $response = null)
{
return parent::stream($view, $parameters, $response);
}
public function createNotFoundException($message = 'Not Found', \Exception $previous = null)
{
return parent::createNotFoundException($message, $previous);
}
public function createAccessDeniedException($message = 'Access Denied.', \Exception $previous = null)
{
return parent::createAccessDeniedException($message, $previous);
}
public function createForm($type, $data = null, array $options = array())
{
return parent::createForm($type, $data, $options);
}
public function createFormBuilder($data = null, array $options = array())
{
return parent::createFormBuilder($data, $options);
}
public function getDoctrine()
{
return parent::getDoctrine();
}
}

View File

@@ -0,0 +1,297 @@
<?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\Bundle\FrameworkBundle\Tests\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
/**
* @author Marcin Sikon <marcin.sikon@gmail.com>
*/
class RedirectControllerTest extends TestCase
{
public function testEmptyRoute()
{
$request = new Request();
$controller = new RedirectController();
try {
$controller->redirectAction($request, '', true);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(410, $e->getStatusCode());
}
try {
$controller->redirectAction($request, '', false);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(404, $e->getStatusCode());
}
}
/**
* @dataProvider provider
*/
public function testRoute($permanent, $ignoreAttributes, $expectedCode, $expectedAttributes)
{
$request = new Request();
$route = 'new-route';
$url = '/redirect-url';
$attributes = array(
'route' => $route,
'permanent' => $permanent,
'_route' => 'current-route',
'_route_params' => array(
'route' => $route,
'permanent' => $permanent,
'additional-parameter' => 'value',
'ignoreAttributes' => $ignoreAttributes,
),
);
$request->attributes = new ParameterBag($attributes);
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router
->expects($this->once())
->method('generate')
->with($this->equalTo($route), $this->equalTo($expectedAttributes))
->will($this->returnValue($url));
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
$container
->expects($this->once())
->method('get')
->with($this->equalTo('router'))
->will($this->returnValue($router));
$controller = new RedirectController();
$controller->setContainer($container);
$returnResponse = $controller->redirectAction($request, $route, $permanent, $ignoreAttributes);
$this->assertRedirectUrl($returnResponse, $url);
$this->assertEquals($expectedCode, $returnResponse->getStatusCode());
}
public function provider()
{
return array(
array(true, false, 301, array('additional-parameter' => 'value')),
array(false, false, 302, array('additional-parameter' => 'value')),
array(false, true, 302, array()),
array(false, array('additional-parameter'), 302, array()),
);
}
public function testEmptyPath()
{
$request = new Request();
$controller = new RedirectController();
try {
$controller->urlRedirectAction($request, '', true);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(410, $e->getStatusCode());
}
try {
$controller->urlRedirectAction($request, '', false);
$this->fail('Expected Symfony\Component\HttpKernel\Exception\HttpException to be thrown');
} catch (HttpException $e) {
$this->assertSame(404, $e->getStatusCode());
}
}
public function testFullURL()
{
$request = new Request();
$controller = new RedirectController();
$returnResponse = $controller->urlRedirectAction($request, 'http://foo.bar/');
$this->assertRedirectUrl($returnResponse, 'http://foo.bar/');
$this->assertEquals(302, $returnResponse->getStatusCode());
}
public function testUrlRedirectDefaultPortParameters()
{
$host = 'www.example.com';
$baseUrl = '/base';
$path = '/redirect-path';
$httpPort = 1080;
$httpsPort = 1443;
$expectedUrl = "https://$host:$httpsPort$baseUrl$path";
$request = $this->createRequestObject('http', $host, $httpPort, $baseUrl);
$controller = $this->createRedirectController(null, $httpsPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'https');
$this->assertRedirectUrl($returnValue, $expectedUrl);
$expectedUrl = "http://$host:$httpPort$baseUrl$path";
$request = $this->createRequestObject('https', $host, $httpPort, $baseUrl);
$controller = $this->createRedirectController($httpPort);
$returnValue = $controller->urlRedirectAction($request, $path, false, 'http');
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
public function urlRedirectProvider()
{
return array(
// Standard ports
array('http', null, null, 'http', 80, ''),
array('http', 80, null, 'http', 80, ''),
array('https', null, null, 'http', 80, ''),
array('https', 80, null, 'http', 80, ''),
array('http', null, null, 'https', 443, ''),
array('http', null, 443, 'https', 443, ''),
array('https', null, null, 'https', 443, ''),
array('https', null, 443, 'https', 443, ''),
// Non-standard ports
array('http', null, null, 'http', 8080, ':8080'),
array('http', 4080, null, 'http', 8080, ':4080'),
array('http', 80, null, 'http', 8080, ''),
array('https', null, null, 'http', 8080, ''),
array('https', null, 8443, 'http', 8080, ':8443'),
array('https', null, 443, 'http', 8080, ''),
array('https', null, null, 'https', 8443, ':8443'),
array('https', null, 4443, 'https', 8443, ':4443'),
array('https', null, 443, 'https', 8443, ''),
array('http', null, null, 'https', 8443, ''),
array('http', 8080, 4443, 'https', 8443, ':8080'),
array('http', 80, 4443, 'https', 8443, ''),
);
}
/**
* @dataProvider urlRedirectProvider
*/
public function testUrlRedirect($scheme, $httpPort, $httpsPort, $requestScheme, $requestPort, $expectedPort)
{
$host = 'www.example.com';
$baseUrl = '/base';
$path = '/redirect-path';
$expectedUrl = "$scheme://$host$expectedPort$baseUrl$path";
$request = $this->createRequestObject($requestScheme, $host, $requestPort, $baseUrl);
$controller = $this->createRedirectController();
$returnValue = $controller->urlRedirectAction($request, $path, false, $scheme, $httpPort, $httpsPort);
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
public function pathQueryParamsProvider()
{
return array(
array('http://www.example.com/base/redirect-path', '/redirect-path', ''),
array('http://www.example.com/base/redirect-path?foo=bar', '/redirect-path?foo=bar', ''),
array('http://www.example.com/base/redirect-path?foo=bar', '/redirect-path', 'foo=bar'),
array('http://www.example.com/base/redirect-path?foo=bar&abc=example', '/redirect-path?foo=bar', 'abc=example'),
array('http://www.example.com/base/redirect-path?foo=bar&abc=example&baz=def', '/redirect-path?foo=bar', 'abc=example&baz=def'),
);
}
/**
* @dataProvider pathQueryParamsProvider
*/
public function testPathQueryParams($expectedUrl, $path, $queryString)
{
$scheme = 'http';
$host = 'www.example.com';
$baseUrl = '/base';
$port = 80;
$request = $this->createRequestObject($scheme, $host, $port, $baseUrl, $queryString);
$controller = $this->createRedirectController();
$returnValue = $controller->urlRedirectAction($request, $path, false, $scheme, $port, null);
$this->assertRedirectUrl($returnValue, $expectedUrl);
}
private function createRequestObject($scheme, $host, $port, $baseUrl, $queryString = '')
{
$request = $this->getMock('Symfony\Component\HttpFoundation\Request');
$request
->expects($this->any())
->method('getScheme')
->will($this->returnValue($scheme));
$request
->expects($this->any())
->method('getHost')
->will($this->returnValue($host));
$request
->expects($this->any())
->method('getPort')
->will($this->returnValue($port));
$request
->expects($this->any())
->method('getBaseUrl')
->will($this->returnValue($baseUrl));
$request
->expects($this->any())
->method('getQueryString')
->will($this->returnValue($queryString));
return $request;
}
private function createRedirectController($httpPort = null, $httpsPort = null)
{
$container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
if (null !== $httpPort) {
$container
->expects($this->once())
->method('hasParameter')
->with($this->equalTo('request_listener.http_port'))
->will($this->returnValue(true));
$container
->expects($this->once())
->method('getParameter')
->with($this->equalTo('request_listener.http_port'))
->will($this->returnValue($httpPort));
}
if (null !== $httpsPort) {
$container
->expects($this->once())
->method('hasParameter')
->with($this->equalTo('request_listener.https_port'))
->will($this->returnValue(true));
$container
->expects($this->once())
->method('getParameter')
->with($this->equalTo('request_listener.https_port'))
->will($this->returnValue($httpsPort));
}
$controller = new RedirectController();
$controller->setContainer($container);
return $controller;
}
public function assertRedirectUrl(Response $returnResponse, $expectedUrl)
{
$this->assertTrue($returnResponse->isRedirect($expectedUrl), "Expected: $expectedUrl\nGot: ".$returnResponse->headers->get('Location'));
}
}