Removed Silex tests

This commit is contained in:
R. Eric Wheeler 2016-07-18 06:08:07 -07:00
parent 534cc2d6d1
commit a5baed4da1
58 changed files with 117 additions and 6189 deletions

View File

@ -56,7 +56,8 @@
"symfony/debug-bundle": "^3.1",
"friendsofphp/php-cs-fixer": "^1.11",
"heroku/heroku-buildpack-php": "^108.0",
"phpunit/phpunit": "^5.4"
"phpunit/phpunit": "^5.4",
"symfony/browser-kit": "^3.1"
},
"autoload": {
"psr-4": {

117
composer.lock generated
View File

@ -4,8 +4,8 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "58b6f8f80e5846af7b9ae23a628a0861",
"content-hash": "9d13427d982ec276ccfba5e7fdc2cd8a",
"hash": "a2365b7d252a9d6b3c1f07ffdc28eaa9",
"content-hash": "8f9ef005ff2350ecc35eba47c04f9873",
"packages": [
{
"name": "google/recaptcha",
@ -4293,6 +4293,63 @@
"homepage": "https://github.com/sebastianbergmann/version",
"time": "2016-02-04 12:56:52"
},
{
"name": "symfony/browser-kit",
"version": "v3.1.2",
"source": {
"type": "git",
"url": "https://github.com/symfony/browser-kit.git",
"reference": "dcf41ed026b0499254385b5c88f03247b2ba010b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/browser-kit/zipball/dcf41ed026b0499254385b5c88f03247b2ba010b",
"reference": "dcf41ed026b0499254385b5c88f03247b2ba010b",
"shasum": ""
},
"require": {
"php": ">=5.5.9",
"symfony/dom-crawler": "~2.8|~3.0"
},
"require-dev": {
"symfony/css-selector": "~2.8|~3.0",
"symfony/process": "~2.8|~3.0"
},
"suggest": {
"symfony/process": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.1-dev"
}
},
"autoload": {
"psr-4": {
"Symfony\\Component\\BrowserKit\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony BrowserKit Component",
"homepage": "https://symfony.com",
"time": "2016-06-29 05:41:56"
},
{
"name": "symfony/debug-bundle",
"version": "v3.1.2",
@ -4354,6 +4411,62 @@
"homepage": "https://symfony.com",
"time": "2016-02-13 09:24:02"
},
{
"name": "symfony/dom-crawler",
"version": "v3.1.2",
"source": {
"type": "git",
"url": "https://github.com/symfony/dom-crawler.git",
"reference": "99ec4a23330fcd0c8667095f3ef7aa204ffd9dc0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/dom-crawler/zipball/99ec4a23330fcd0c8667095f3ef7aa204ffd9dc0",
"reference": "99ec4a23330fcd0c8667095f3ef7aa204ffd9dc0",
"shasum": ""
},
"require": {
"php": ">=5.5.9",
"symfony/polyfill-mbstring": "~1.0"
},
"require-dev": {
"symfony/css-selector": "~2.8|~3.0"
},
"suggest": {
"symfony/css-selector": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.1-dev"
}
},
"autoload": {
"psr-4": {
"Symfony\\Component\\DomCrawler\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony DomCrawler Component",
"homepage": "https://symfony.com",
"time": "2016-06-29 05:41:56"
},
{
"name": "symfony/finder",
"version": "v3.1.2",

View File

@ -1,19 +0,0 @@
<?php
/*
* This file is part of Resume.PHP.
*
* (copyleft) R. Eric Wheeler <sikofitt@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require_once 'vendor/autoload.php';
$decoder = new Webmozart\Json\JsonDecoder();
$json = $decoder->decodeFile('data/resume.json');
dump($json);

View File

@ -1,19 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Application;
class FormApplication extends Application
{
use Application\FormTrait;
}

View File

@ -1,35 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Provider\FormServiceProvider;
/**
* FormTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FormTraitTest extends \PHPUnit_Framework_TestCase
{
public function testForm()
{
$this->assertInstanceOf('Symfony\Component\Form\FormBuilder', $this->createApplication()->form());
}
public function createApplication()
{
$app = new FormApplication();
$app->register(new FormServiceProvider());
return $app;
}
}

View File

@ -1,19 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Application;
class MonologApplication extends Application
{
use Application\MonologTrait;
}

View File

@ -1,47 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Provider\MonologServiceProvider;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
/**
* MonologTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class MonologTraitTest extends \PHPUnit_Framework_TestCase
{
public function testLog()
{
$app = $this->createApplication();
$app->log('Foo');
$app->log('Bar', array(), Logger::DEBUG);
$this->assertTrue($app['monolog.handler']->hasInfo('Foo'));
$this->assertTrue($app['monolog.handler']->hasDebug('Bar'));
}
public function createApplication()
{
$app = new MonologApplication();
$app->register(new MonologServiceProvider(), array(
'monolog.handler' => function () use ($app) {
return new TestHandler($app['monolog.level']);
},
'monolog.logfile' => 'php://memory',
));
return $app;
}
}

View File

@ -1,19 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Application;
class SecurityApplication extends Application
{
use Application\SecurityTrait;
}

View File

@ -1,90 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Provider\SecurityServiceProvider;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\HttpFoundation\Request;
/**
* SecurityTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SecurityTraitTest extends \PHPUnit_Framework_TestCase
{
public function testEncodePassword()
{
$app = $this->createApplication(array(
'fabien' => array('ROLE_ADMIN', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
));
$user = new User('foo', 'bar');
$password = 'foo';
$encoded = $app->encodePassword($user, $password);
$this->assertTrue(
$app['security.encoder_factory']->getEncoder($user)->isPasswordValid($encoded, $password, $user->getSalt())
);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testIsGrantedWithoutTokenThrowsException()
{
$app = $this->createApplication();
$app->get('/', function () { return 'foo'; });
$app->handle(Request::create('/'));
$app->isGranted('ROLE_ADMIN');
}
public function testIsGranted()
{
$request = Request::create('/');
$app = $this->createApplication(array(
'fabien' => array('ROLE_ADMIN', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
'monique' => array('ROLE_USER', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
));
$app->get('/', function () { return 'foo'; });
// User is Monique (ROLE_USER)
$request->headers->set('PHP_AUTH_USER', 'monique');
$request->headers->set('PHP_AUTH_PW', 'foo');
$app->handle($request);
$this->assertTrue($app->isGranted('ROLE_USER'));
$this->assertFalse($app->isGranted('ROLE_ADMIN'));
// User is Fabien (ROLE_ADMIN)
$request->headers->set('PHP_AUTH_USER', 'fabien');
$request->headers->set('PHP_AUTH_PW', 'foo');
$app->handle($request);
$this->assertFalse($app->isGranted('ROLE_USER'));
$this->assertTrue($app->isGranted('ROLE_ADMIN'));
}
public function createApplication($users = array())
{
$app = new SecurityApplication();
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'default' => array(
'http' => true,
'users' => $users,
),
),
));
return $app;
}
}

View File

@ -1,19 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Application;
class SwiftmailerApplication extends Application
{
use Application\SwiftmailerTrait;
}

View File

@ -1,44 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Provider\SwiftmailerServiceProvider;
/**
* SwiftmailerTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SwiftmailerTraitTest extends \PHPUnit_Framework_TestCase
{
public function testMail()
{
$app = $this->createApplication();
$message = $this->getMockBuilder('Swift_Message')->disableOriginalConstructor()->getMock();
$app['mailer'] = $mailer = $this->getMockBuilder('Swift_Mailer')->disableOriginalConstructor()->getMock();
$mailer->expects($this->once())
->method('send')
->with($message)
;
$app->mail($message);
}
public function createApplication()
{
$app = new SwiftmailerApplication();
$app->register(new SwiftmailerServiceProvider());
return $app;
}
}

View File

@ -1,19 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Application;
class TranslationApplication extends Application
{
use Application\TranslationTrait;
}

View File

@ -1,46 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Provider\TranslationServiceProvider;
/**
* TranslationTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TranslationTraitTest extends \PHPUnit_Framework_TestCase
{
public function testTrans()
{
$app = $this->createApplication();
$app['translator'] = $translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')->disableOriginalConstructor()->getMock();
$translator->expects($this->once())->method('trans');
$app->trans('foo');
}
public function testTransChoice()
{
$app = $this->createApplication();
$app['translator'] = $translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')->disableOriginalConstructor()->getMock();
$translator->expects($this->once())->method('transChoice');
$app->transChoice('foo', 2);
}
public function createApplication()
{
$app = new TranslationApplication();
$app->register(new TranslationServiceProvider());
return $app;
}
}

View File

@ -1,19 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Application;
class TwigApplication extends Application
{
use Application\TwigTrait;
}

View File

@ -1,80 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Provider\TwigServiceProvider;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* TwigTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TwigTraitTest extends \PHPUnit_Framework_TestCase
{
public function testRender()
{
$app = $this->createApplication();
$app['twig'] = $mailer = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock();
$mailer->expects($this->once())->method('render')->will($this->returnValue('foo'));
$response = $app->render('view');
$this->assertEquals('Symfony\Component\HttpFoundation\Response', get_class($response));
$this->assertEquals('foo', $response->getContent());
}
public function testRenderKeepResponse()
{
$app = $this->createApplication();
$app['twig'] = $mailer = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock();
$mailer->expects($this->once())->method('render')->will($this->returnValue('foo'));
$response = $app->render('view', array(), new Response('', 404));
$this->assertEquals(404, $response->getStatusCode());
}
public function testRenderForStream()
{
$app = $this->createApplication();
$app['twig'] = $mailer = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock();
$mailer->expects($this->once())->method('display')->will($this->returnCallback(function () { echo 'foo'; }));
$response = $app->render('view', array(), new StreamedResponse());
$this->assertEquals('Symfony\Component\HttpFoundation\StreamedResponse', get_class($response));
ob_start();
$response->send();
$this->assertEquals('foo', ob_get_clean());
}
public function testRenderView()
{
$app = $this->createApplication();
$app['twig'] = $mailer = $this->getMockBuilder('Twig_Environment')->disableOriginalConstructor()->getMock();
$mailer->expects($this->once())->method('render');
$app->renderView('view');
}
public function createApplication()
{
$app = new TwigApplication();
$app->register(new TwigServiceProvider());
return $app;
}
}

View File

@ -1,19 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Silex\Application;
class UrlGeneratorApplication extends Application
{
use Application\UrlGeneratorTrait;
}

View File

@ -1,38 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Application;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* UrlGeneratorTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class UrlGeneratorTraitTest extends \PHPUnit_Framework_TestCase
{
public function testUrl()
{
$app = new UrlGeneratorApplication();
$app['url_generator'] = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->disableOriginalConstructor()->getMock();
$app['url_generator']->expects($this->once())->method('generate')->with('foo', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$app->url('foo');
}
public function testPath()
{
$app = new UrlGeneratorApplication();
$app['url_generator'] = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->disableOriginalConstructor()->getMock();
$app['url_generator']->expects($this->once())->method('generate')->with('foo', array(), UrlGeneratorInterface::ABSOLUTE_PATH);
$app->path('foo');
}
}

View File

@ -1,701 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Silex\ControllerCollection;
use Silex\Api\ControllerProviderInterface;
use Silex\Route;
use Silex\Provider\MonologServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Routing\RouteCollection;
/**
* Application test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class ApplicationTest extends \PHPUnit_Framework_TestCase
{
public function testMatchReturnValue()
{
$app = new Application();
$returnValue = $app->match('/foo', function () {});
$this->assertInstanceOf('Silex\Controller', $returnValue);
$returnValue = $app->get('/foo', function () {});
$this->assertInstanceOf('Silex\Controller', $returnValue);
$returnValue = $app->post('/foo', function () {});
$this->assertInstanceOf('Silex\Controller', $returnValue);
$returnValue = $app->put('/foo', function () {});
$this->assertInstanceOf('Silex\Controller', $returnValue);
$returnValue = $app->patch('/foo', function () {});
$this->assertInstanceOf('Silex\Controller', $returnValue);
$returnValue = $app->delete('/foo', function () {});
$this->assertInstanceOf('Silex\Controller', $returnValue);
}
public function testConstructorInjection()
{
// inject a custom parameter
$params = array('param' => 'value');
$app = new Application($params);
$this->assertSame($params['param'], $app['param']);
// inject an existing parameter
$params = array('locale' => 'value');
$app = new Application($params);
$this->assertSame($params['locale'], $app['locale']);
}
public function testGetRequest()
{
$request = Request::create('/');
$app = new Application();
$app->get('/', function (Request $req) use ($request) {
return $request === $req ? 'ok' : 'ko';
});
$this->assertEquals('ok', $app->handle($request)->getContent());
}
public function testGetRoutesWithNoRoutes()
{
$app = new Application();
$routes = $app['routes'];
$this->assertInstanceOf('Symfony\Component\Routing\RouteCollection', $routes);
$this->assertEquals(0, count($routes->all()));
}
public function testGetRoutesWithRoutes()
{
$app = new Application();
$app->get('/foo', function () {
return 'foo';
});
$app->get('/bar')->run(function () {
return 'bar';
});
$routes = $app['routes'];
$this->assertInstanceOf('Symfony\Component\Routing\RouteCollection', $routes);
$this->assertEquals(0, count($routes->all()));
$app->flush();
$this->assertEquals(2, count($routes->all()));
}
public function testOnCoreController()
{
$app = new Application();
$app->get('/foo/{foo}', function (\ArrayObject $foo) {
return $foo['foo'];
})->convert('foo', function ($foo) { return new \ArrayObject(array('foo' => $foo)); });
$response = $app->handle(Request::create('/foo/bar'));
$this->assertEquals('bar', $response->getContent());
$app->get('/foo/{foo}/{bar}', function (\ArrayObject $foo) {
return $foo['foo'];
})->convert('foo', function ($foo, Request $request) { return new \ArrayObject(array('foo' => $foo.$request->attributes->get('bar'))); });
$response = $app->handle(Request::create('/foo/foo/bar'));
$this->assertEquals('foobar', $response->getContent());
}
public function testOn()
{
$app = new Application();
$app['pass'] = false;
$app->on('test', function (Event $e) use ($app) {
$app['pass'] = true;
});
$app['dispatcher']->dispatch('test');
$this->assertTrue($app['pass']);
}
public function testAbort()
{
$app = new Application();
try {
$app->abort(404);
$this->fail();
} catch (HttpException $e) {
$this->assertEquals(404, $e->getStatusCode());
}
}
/**
* @dataProvider escapeProvider
*/
public function testEscape($expected, $text)
{
$app = new Application();
$this->assertEquals($expected, $app->escape($text));
}
public function escapeProvider()
{
return array(
array('&lt;', '<'),
array('&gt;', '>'),
array('&quot;', '"'),
array("'", "'"),
array('abc', 'abc'),
);
}
public function testControllersAsMethods()
{
$app = new Application();
$app->get('/{name}', 'Silex\Tests\FooController::barAction');
$this->assertEquals('Hello Fabien', $app->handle(Request::create('/Fabien'))->getContent());
}
public function testApplicationTypeHintWorks()
{
$app = new SpecialApplication();
$app->get('/{name}', 'Silex\Tests\FooController::barSpecialAction');
$this->assertEquals('Hello Fabien in Silex\Tests\SpecialApplication', $app->handle(Request::create('/Fabien'))->getContent());
}
public function testHttpSpec()
{
$app = new Application();
$app['charset'] = 'ISO-8859-1';
$app->get('/', function () {
return 'hello';
});
// content is empty for HEAD requests
$response = $app->handle(Request::create('/', 'HEAD'));
$this->assertEquals('', $response->getContent());
// charset is appended to Content-Type
$response = $app->handle(Request::create('/'));
$this->assertEquals('text/html; charset=ISO-8859-1', $response->headers->get('Content-Type'));
}
public function testRoutesMiddlewares()
{
$app = new Application();
$test = $this;
$middlewareTarget = array();
$beforeMiddleware1 = function (Request $request) use (&$middlewareTarget, $test) {
$test->assertEquals('/reached', $request->getRequestUri());
$middlewareTarget[] = 'before_middleware1_triggered';
};
$beforeMiddleware2 = function (Request $request) use (&$middlewareTarget, $test) {
$test->assertEquals('/reached', $request->getRequestUri());
$middlewareTarget[] = 'before_middleware2_triggered';
};
$beforeMiddleware3 = function (Request $request) use (&$middlewareTarget, $test) {
throw new \Exception('This middleware shouldn\'t run!');
};
$afterMiddleware1 = function (Request $request, Response $response) use (&$middlewareTarget, $test) {
$test->assertEquals('/reached', $request->getRequestUri());
$middlewareTarget[] = 'after_middleware1_triggered';
};
$afterMiddleware2 = function (Request $request, Response $response) use (&$middlewareTarget, $test) {
$test->assertEquals('/reached', $request->getRequestUri());
$middlewareTarget[] = 'after_middleware2_triggered';
};
$afterMiddleware3 = function (Request $request, Response $response) use (&$middlewareTarget, $test) {
throw new \Exception('This middleware shouldn\'t run!');
};
$app->get('/reached', function () use (&$middlewareTarget) {
$middlewareTarget[] = 'route_triggered';
return 'hello';
})
->before($beforeMiddleware1)
->before($beforeMiddleware2)
->after($afterMiddleware1)
->after($afterMiddleware2);
$app->get('/never-reached', function () use (&$middlewareTarget) {
throw new \Exception('This route shouldn\'t run!');
})
->before($beforeMiddleware3)
->after($afterMiddleware3);
$result = $app->handle(Request::create('/reached'));
$this->assertSame(array('before_middleware1_triggered', 'before_middleware2_triggered', 'route_triggered', 'after_middleware1_triggered', 'after_middleware2_triggered'), $middlewareTarget);
$this->assertEquals('hello', $result->getContent());
}
public function testRoutesBeforeMiddlewaresWithResponseObject()
{
$app = new Application();
$app->get('/foo', function () {
throw new \Exception('This route shouldn\'t run!');
})
->before(function () {
return new Response('foo');
});
$request = Request::create('/foo');
$result = $app->handle($request);
$this->assertEquals('foo', $result->getContent());
}
public function testRoutesAfterMiddlewaresWithResponseObject()
{
$app = new Application();
$app->get('/foo', function () {
return new Response('foo');
})
->after(function () {
return new Response('bar');
});
$request = Request::create('/foo');
$result = $app->handle($request);
$this->assertEquals('bar', $result->getContent());
}
public function testRoutesBeforeMiddlewaresWithRedirectResponseObject()
{
$app = new Application();
$app->get('/foo', function () {
throw new \Exception('This route shouldn\'t run!');
})
->before(function () use ($app) {
return $app->redirect('/bar');
});
$request = Request::create('/foo');
$result = $app->handle($request);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $result);
$this->assertEquals('/bar', $result->getTargetUrl());
}
public function testRoutesBeforeMiddlewaresTriggeredAfterSilexBeforeFilters()
{
$app = new Application();
$middlewareTarget = array();
$middleware = function (Request $request) use (&$middlewareTarget) {
$middlewareTarget[] = 'middleware_triggered';
};
$app->get('/foo', function () use (&$middlewareTarget) {
$middlewareTarget[] = 'route_triggered';
})
->before($middleware);
$app->before(function () use (&$middlewareTarget) {
$middlewareTarget[] = 'before_triggered';
});
$app->handle(Request::create('/foo'));
$this->assertSame(array('before_triggered', 'middleware_triggered', 'route_triggered'), $middlewareTarget);
}
public function testRoutesAfterMiddlewaresTriggeredBeforeSilexAfterFilters()
{
$app = new Application();
$middlewareTarget = array();
$middleware = function (Request $request) use (&$middlewareTarget) {
$middlewareTarget[] = 'middleware_triggered';
};
$app->get('/foo', function () use (&$middlewareTarget) {
$middlewareTarget[] = 'route_triggered';
})
->after($middleware);
$app->after(function () use (&$middlewareTarget) {
$middlewareTarget[] = 'after_triggered';
});
$app->handle(Request::create('/foo'));
$this->assertSame(array('route_triggered', 'middleware_triggered', 'after_triggered'), $middlewareTarget);
}
public function testFinishFilter()
{
$containerTarget = array();
$app = new Application();
$app->finish(function () use (&$containerTarget) {
$containerTarget[] = '4_filterFinish';
});
$app->get('/foo', function () use (&$containerTarget) {
$containerTarget[] = '1_routeTriggered';
return new StreamedResponse(function () use (&$containerTarget) {
$containerTarget[] = '3_responseSent';
});
});
$app->after(function () use (&$containerTarget) {
$containerTarget[] = '2_filterAfter';
});
$app->run(Request::create('/foo'));
$this->assertSame(array('1_routeTriggered', '2_filterAfter', '3_responseSent', '4_filterFinish'), $containerTarget);
}
/**
* @expectedException \RuntimeException
*/
public function testNonResponseAndNonNullReturnFromRouteBeforeMiddlewareShouldThrowRuntimeException()
{
$app = new Application();
$middleware = function (Request $request) {
return 'string return';
};
$app->get('/', function () {
return 'hello';
})
->before($middleware);
$app->handle(Request::create('/'), HttpKernelInterface::MASTER_REQUEST, false);
}
/**
* @expectedException \RuntimeException
*/
public function testNonResponseAndNonNullReturnFromRouteAfterMiddlewareShouldThrowRuntimeException()
{
$app = new Application();
$middleware = function (Request $request) {
return 'string return';
};
$app->get('/', function () {
return 'hello';
})
->after($middleware);
$app->handle(Request::create('/'), HttpKernelInterface::MASTER_REQUEST, false);
}
public function testSubRequest()
{
$app = new Application();
$app->get('/sub', function (Request $request) {
return new Response('foo');
});
$app->get('/', function (Request $request) use ($app) {
return $app->handle(Request::create('/sub'), HttpKernelInterface::SUB_REQUEST);
});
$this->assertEquals('foo', $app->handle(Request::create('/'))->getContent());
}
public function testRegisterShouldReturnSelf()
{
$app = new Application();
$provider = $this->getMock('Pimple\ServiceProviderInterface');
$this->assertSame($app, $app->register($provider));
}
public function testMountShouldReturnSelf()
{
$app = new Application();
$mounted = new ControllerCollection(new Route());
$mounted->get('/{name}', function ($name) { return new Response($name); });
$this->assertSame($app, $app->mount('/hello', $mounted));
}
public function testMountPreservesOrder()
{
$app = new Application();
$mounted = new ControllerCollection(new Route());
$mounted->get('/mounted')->bind('second');
$app->get('/before')->bind('first');
$app->mount('/', $mounted);
$app->get('/after')->bind('third');
$app->flush();
$this->assertEquals(array('first', 'second', 'third'), array_keys(iterator_to_array($app['routes'])));
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage The "mount" method takes either a "ControllerCollection" instance, "ControllerProviderInterface" instance, or a callable.
*/
public function testMountNullException()
{
$app = new Application();
$app->mount('/exception', null);
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage The method "Silex\Tests\IncorrectControllerCollection::connect" must return a "ControllerCollection" instance. Got: "NULL"
*/
public function testMountWrongConnectReturnValueException()
{
$app = new Application();
$app->mount('/exception', new IncorrectControllerCollection());
}
public function testMountCallable()
{
$app = new Application();
$app->mount('/prefix', function (ControllerCollection $coll) {
$coll->get('/path');
});
$app->flush();
$this->assertEquals(1, $app['routes']->count());
}
public function testSendFile()
{
$app = new Application();
$response = $app->sendFile(__FILE__, 200, array('Content-Type: application/php'));
$this->assertInstanceOf('Symfony\Component\HttpFoundation\BinaryFileResponse', $response);
$this->assertEquals(__FILE__, (string) $response->getFile());
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage The "homepage" route must have code to run when it matches.
*/
public function testGetRouteCollectionWithRouteWithoutController()
{
$app = new Application();
unset($app['exception_handler']);
$app->match('/')->bind('homepage');
$app->handle(Request::create('/'));
}
public function testRedirectDoesNotRaisePHPNoticesWhenMonologIsRegistered()
{
$app = new Application();
ErrorHandler::register(null, false);
$app['monolog.logfile'] = 'php://memory';
$app->register(new MonologServiceProvider());
$app->get('/foo/', function () { return 'ok'; });
$response = $app->handle(Request::create('/foo'));
$this->assertEquals(301, $response->getStatusCode());
}
public function testBeforeFilterOnMountedControllerGroupIsolatedToGroup()
{
$app = new Application();
$app->match('/', function () { return new Response('ok'); });
$mounted = $app['controllers_factory'];
$mounted->before(function () { return new Response('not ok'); });
$app->mount('/group', $mounted);
$response = $app->handle(Request::create('/'));
$this->assertEquals('ok', $response->getContent());
}
public function testViewListenerWithPrimitive()
{
$app = new Application();
$app->get('/foo', function () { return 123; });
$app->view(function ($view, Request $request) {
return new Response($view);
});
$response = $app->handle(Request::create('/foo'));
$this->assertEquals('123', $response->getContent());
}
public function testViewListenerWithArrayTypeHint()
{
$app = new Application();
$app->get('/foo', function () { return array('ok'); });
$app->view(function (array $view) {
return new Response($view[0]);
});
$response = $app->handle(Request::create('/foo'));
$this->assertEquals('ok', $response->getContent());
}
public function testViewListenerWithObjectTypeHint()
{
$app = new Application();
$app->get('/foo', function () { return (object) array('name' => 'world'); });
$app->view(function (\stdClass $view) {
return new Response('Hello '.$view->name);
});
$response = $app->handle(Request::create('/foo'));
$this->assertEquals('Hello world', $response->getContent());
}
public function testViewListenerWithCallableTypeHint()
{
$app = new Application();
$app->get('/foo', function () { return function () { return 'world'; }; });
$app->view(function (callable $view) {
return new Response('Hello '.$view());
});
$response = $app->handle(Request::create('/foo'));
$this->assertEquals('Hello world', $response->getContent());
}
public function testViewListenersCanBeChained()
{
$app = new Application();
$app->get('/foo', function () { return (object) array('name' => 'world'); });
$app->view(function (\stdClass $view) {
return array('msg' => 'Hello '.$view->name);
});
$app->view(function (array $view) {
return $view['msg'];
});
$response = $app->handle(Request::create('/foo'));
$this->assertEquals('Hello world', $response->getContent());
}
public function testViewListenersAreIgnoredIfNotSuitable()
{
$app = new Application();
$app->get('/foo', function () { return 'Hello world'; });
$app->view(function (\stdClass $view) {
throw new \Exception('View listener was called');
});
$app->view(function (array $view) {
throw new \Exception('View listener was called');
});
$response = $app->handle(Request::create('/foo'));
$this->assertEquals('Hello world', $response->getContent());
}
public function testViewListenersResponsesAreNotUsedIfNull()
{
$app = new Application();
$app->get('/foo', function () { return 'Hello world'; });
$app->view(function ($view) {
return 'Hello view listener';
});
$app->view(function ($view) {
return;
});
$response = $app->handle(Request::create('/foo'));
$this->assertEquals('Hello view listener', $response->getContent());
}
public function testDefaultRoutesFactory()
{
$app = new Application();
$this->assertInstanceOf('Symfony\Component\Routing\RouteCollection', $app['routes']);
}
public function testOverriddenRoutesFactory()
{
$app = new Application();
$app['routes_factory'] = $app->factory(function () {
return new RouteCollectionSubClass();
});
$this->assertInstanceOf('Silex\Tests\RouteCollectionSubClass', $app['routes']);
}
}
class FooController
{
public function barAction(Application $app, $name)
{
return 'Hello '.$app->escape($name);
}
public function barSpecialAction(SpecialApplication $app, $name)
{
return 'Hello '.$app->escape($name).' in '.get_class($app);
}
}
class IncorrectControllerCollection implements ControllerProviderInterface
{
public function connect(Application $app)
{
return;
}
}
class RouteCollectionSubClass extends RouteCollection
{
}
class SpecialApplication extends Application
{
}

View File

@ -1,81 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (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 Silex\Tests;
use Pimple\Container;
use Silex\CallbackResolver;
class CallbackResolverTest extends \PHPUnit_Framework_Testcase
{
private $app;
private $resolver;
public function setup()
{
$this->app = new Container();
$this->resolver = new CallbackResolver($this->app);
}
public function testShouldResolveCallback()
{
$callable = function () {};
$this->app['some_service'] = function () { return new \ArrayObject(); };
$this->app['callable_service'] = function () use ($callable) {
return $callable;
};
$this->assertTrue($this->resolver->isValid('some_service:methodName'));
$this->assertTrue($this->resolver->isValid('callable_service'));
$this->assertEquals(
array($this->app['some_service'], 'append'),
$this->resolver->convertCallback('some_service:append')
);
$this->assertSame($callable, $this->resolver->convertCallback('callable_service'));
}
/**
* @dataProvider nonStringsAreNotValidProvider
*/
public function testNonStringsAreNotValid($name)
{
$this->assertFalse($this->resolver->isValid($name));
}
public function nonStringsAreNotValidProvider()
{
return array(
array(null),
array('some_service::methodName'),
array('missing_service'),
);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp /Service "[a-z_]+" is not callable./
* @dataProvider shouldThrowAnExceptionIfServiceIsNotCallableProvider
*/
public function testShouldThrowAnExceptionIfServiceIsNotCallable($name)
{
$this->app['non_callable_obj'] = function () { return new \stdClass(); };
$this->app['non_callable'] = function () { return array(); };
$this->resolver->convertCallback($name);
}
public function shouldThrowAnExceptionIfServiceIsNotCallableProvider()
{
return array(
array('non_callable_obj:methodA'),
array('non_callable'),
);
}
}

View File

@ -1,109 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Silex\Provider\ServiceControllerServiceProvider;
/**
* Callback as services test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class CallbackServicesTest extends \PHPUnit_Framework_TestCase
{
public $called = array();
public function testCallbacksAsServices()
{
$app = new Application();
$app->register(new ServiceControllerServiceProvider());
$app['service'] = function () {
return new CallbackServicesTest();
};
$app->before('service:beforeApp');
$app->after('service:afterApp');
$app->finish('service:finishApp');
$app->error('service:error');
$app->on('kernel.request', 'service:onRequest');
$app
->match('/', 'service:controller')
->convert('foo', 'service:convert')
->before('service:before')
->after('service:after')
;
$request = Request::create('/');
$response = $app->handle($request);
$app->terminate($request, $response);
$this->assertEquals(array(
'BEFORE APP',
'ON REQUEST',
'BEFORE',
'CONVERT',
'ERROR',
'AFTER',
'AFTER APP',
'FINISH APP',
), $app['service']->called);
}
public function controller(Application $app)
{
$app->abort(404);
}
public function before()
{
$this->called[] = 'BEFORE';
}
public function after()
{
$this->called[] = 'AFTER';
}
public function beforeApp()
{
$this->called[] = 'BEFORE APP';
}
public function afterApp()
{
$this->called[] = 'AFTER APP';
}
public function finishApp()
{
$this->called[] = 'FINISH APP';
}
public function error()
{
$this->called[] = 'ERROR';
}
public function convert()
{
$this->called[] = 'CONVERT';
}
public function onRequest()
{
$this->called[] = 'ON REQUEST';
}
}

View File

@ -1,327 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Silex\Controller;
use Silex\ControllerCollection;
use Silex\Exception\ControllerFrozenException;
use Silex\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* ControllerCollection test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class ControllerCollectionTest extends \PHPUnit_Framework_TestCase
{
public function testGetRouteCollectionWithNoRoutes()
{
$controllers = new ControllerCollection(new Route());
$routes = $controllers->flush();
$this->assertEquals(0, count($routes->all()));
}
public function testGetRouteCollectionWithRoutes()
{
$controllers = new ControllerCollection(new Route());
$controllers->match('/foo', function () {});
$controllers->match('/bar', function () {});
$routes = $controllers->flush();
$this->assertEquals(2, count($routes->all()));
}
public function testControllerFreezing()
{
$controllers = new ControllerCollection(new Route());
$fooController = $controllers->match('/foo', function () {})->bind('foo');
$barController = $controllers->match('/bar', function () {})->bind('bar');
$controllers->flush();
try {
$fooController->bind('foo2');
$this->fail();
} catch (ControllerFrozenException $e) {
}
try {
$barController->bind('bar2');
$this->fail();
} catch (ControllerFrozenException $e) {
}
}
public function testConflictingRouteNames()
{
$controllers = new ControllerCollection(new Route());
$mountedRootController = $controllers->match('/', function () {});
$mainRootController = new Controller(new Route('/'));
$mainRootController->bind($mainRootController->generateRouteName('main_1'));
$controllers->flush();
$this->assertNotEquals($mainRootController->getRouteName(), $mountedRootController->getRouteName());
}
public function testUniqueGeneratedRouteNames()
{
$controllers = new ControllerCollection(new Route());
$controllers->match('/a-a', function () {});
$controllers->match('/a_a', function () {});
$controllers->match('/a/a', function () {});
$routes = $controllers->flush();
$this->assertCount(3, $routes->all());
$this->assertEquals(array('_a_a', '_a_a_1', '_a_a_2'), array_keys($routes->all()));
}
public function testUniqueGeneratedRouteNamesAmongMounts()
{
$controllers = new ControllerCollection(new Route());
$controllers->mount('/root-a', $rootA = new ControllerCollection(new Route()));
$controllers->mount('/root_a', $rootB = new ControllerCollection(new Route()));
$rootA->match('/leaf', function () {});
$rootB->match('/leaf', function () {});
$routes = $controllers->flush();
$this->assertCount(2, $routes->all());
$this->assertEquals(array('_root_a_leaf', '_root_a_leaf_1'), array_keys($routes->all()));
}
public function testUniqueGeneratedRouteNamesAmongNestedMounts()
{
$controllers = new ControllerCollection(new Route());
$controllers->mount('/root-a', $rootA = new ControllerCollection(new Route()));
$controllers->mount('/root_a', $rootB = new ControllerCollection(new Route()));
$rootA->mount('/tree', $treeA = new ControllerCollection(new Route()));
$rootB->mount('/tree', $treeB = new ControllerCollection(new Route()));
$treeA->match('/leaf', function () {});
$treeB->match('/leaf', function () {});
$routes = $controllers->flush();
$this->assertCount(2, $routes->all());
$this->assertEquals(array('_root_a_tree_leaf', '_root_a_tree_leaf_1'), array_keys($routes->all()));
}
public function testMountCallable()
{
$controllers = new ControllerCollection(new Route());
$controllers->mount('/prefix', function (ControllerCollection $coll) {
$coll->mount('/path', function ($coll) {
$coll->get('/part');
});
});
$routes = $controllers->flush();
$this->assertEquals('/prefix/path/part', current($routes->all())->getPath());
}
public function testMountCallableProperClone()
{
$controllers = new ControllerCollection(new Route(), new RouteCollection());
$controllers->get('/');
$subControllers = null;
$controllers->mount('/prefix', function (ControllerCollection $coll) use (&$subControllers) {
$subControllers = $coll;
$coll->get('/');
});
$routes = $controllers->flush();
$subRoutes = $subControllers->flush();
$this->assertTrue($routes->count() == 2 && $subRoutes->count() == 0);
}
public function testMountControllersFactory()
{
$testControllers = new ControllerCollection(new Route());
$controllers = new ControllerCollection(new Route(), null, function () use ($testControllers) {
return $testControllers;
});
$controllers->mount('/prefix', function ($mounted) use ($testControllers) {
$this->assertSame($mounted, $testControllers);
});
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage The "mount" method takes either a "ControllerCollection" instance or callable.
*/
public function testMountCallableException()
{
$controllers = new ControllerCollection(new Route());
$controllers->mount('/prefix', '');
}
public function testAssert()
{
$controllers = new ControllerCollection(new Route());
$controllers->assert('id', '\d+');
$controller = $controllers->match('/{id}/{name}/{extra}', function () {})->assert('name', '\w+')->assert('extra', '.*');
$controllers->assert('extra', '\w+');
$this->assertEquals('\d+', $controller->getRoute()->getRequirement('id'));
$this->assertEquals('\w+', $controller->getRoute()->getRequirement('name'));
$this->assertEquals('\w+', $controller->getRoute()->getRequirement('extra'));
}
public function testValue()
{
$controllers = new ControllerCollection(new Route());
$controllers->value('id', '1');
$controller = $controllers->match('/{id}/{name}/{extra}', function () {})->value('name', 'Fabien')->value('extra', 'Symfony');
$controllers->value('extra', 'Twig');
$this->assertEquals('1', $controller->getRoute()->getDefault('id'));
$this->assertEquals('Fabien', $controller->getRoute()->getDefault('name'));
$this->assertEquals('Twig', $controller->getRoute()->getDefault('extra'));
}
public function testConvert()
{
$controllers = new ControllerCollection(new Route());
$controllers->convert('id', '1');
$controller = $controllers->match('/{id}/{name}/{extra}', function () {})->convert('name', 'Fabien')->convert('extra', 'Symfony');
$controllers->convert('extra', 'Twig');
$this->assertEquals(array('id' => '1', 'name' => 'Fabien', 'extra' => 'Twig'), $controller->getRoute()->getOption('_converters'));
}
public function testRequireHttp()
{
$controllers = new ControllerCollection(new Route());
$controllers->requireHttp();
$controller = $controllers->match('/{id}/{name}/{extra}', function () {})->requireHttps();
$this->assertEquals(array('https'), $controller->getRoute()->getSchemes());
$controllers->requireHttp();
$this->assertEquals(array('http'), $controller->getRoute()->getSchemes());
}
public function testBefore()
{
$controllers = new ControllerCollection(new Route());
$controllers->before('mid1');
$controller = $controllers->match('/{id}/{name}/{extra}', function () {})->before('mid2');
$controllers->before('mid3');
$this->assertEquals(array('mid1', 'mid2', 'mid3'), $controller->getRoute()->getOption('_before_middlewares'));
}
public function testAfter()
{
$controllers = new ControllerCollection(new Route());
$controllers->after('mid1');
$controller = $controllers->match('/{id}/{name}/{extra}', function () {})->after('mid2');
$controllers->after('mid3');
$this->assertEquals(array('mid1', 'mid2', 'mid3'), $controller->getRoute()->getOption('_after_middlewares'));
}
public function testWhen()
{
$controllers = new ControllerCollection(new Route());
$controller = $controllers->match('/{id}/{name}/{extra}', function () {})->when('request.isSecure() == true');
$this->assertEquals('request.isSecure() == true', $controller->getRoute()->getCondition());
}
public function testRouteExtension()
{
$route = new MyRoute1();
$controller = new ControllerCollection($route);
$controller->foo('foo');
$this->assertEquals('foo', $route->foo);
}
/**
* @expectedException \BadMethodCallException
*/
public function testRouteMethodDoesNotExist()
{
$route = new MyRoute1();
$controller = new ControllerCollection($route);
$controller->bar();
}
public function testNestedCollectionRouteCallbacks()
{
$cl1 = new ControllerCollection(new MyRoute1());
$cl2 = new ControllerCollection(new MyRoute1());
$c1 = $cl2->match('/c1', function () {});
$cl1->mount('/foo', $cl2);
$c2 = $cl2->match('/c2', function () {});
$cl1->before('before');
$c3 = $cl2->match('/c3', function () {});
$cl1->flush();
$this->assertEquals(array('before'), $c1->getRoute()->getOption('_before_middlewares'));
$this->assertEquals(array('before'), $c2->getRoute()->getOption('_before_middlewares'));
$this->assertEquals(array('before'), $c3->getRoute()->getOption('_before_middlewares'));
}
public function testRoutesFactoryOmitted()
{
$controllers = new ControllerCollection(new Route());
$routes = $controllers->flush();
$this->assertInstanceOf('Symfony\Component\Routing\RouteCollection', $routes);
}
public function testRoutesFactoryInConstructor()
{
$app = new Application();
$app['routes_factory'] = $app->factory(function () {
return new RouteCollectionSubClass2();
});
$controllers = new ControllerCollection(new Route(), $app['routes_factory']);
$routes = $controllers->flush();
$this->assertInstanceOf('Silex\Tests\RouteCollectionSubClass2', $routes);
}
}
class MyRoute1 extends Route
{
public $foo;
public function foo($value)
{
$this->foo = $value;
}
}
class RouteCollectionSubClass2 extends RouteCollection
{
}

View File

@ -1,38 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\ControllerResolver;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
/**
* ControllerResolver test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ControllerResolverTest extends \PHPUnit_Framework_TestCase
{
/**
* @group legacy
*/
public function testGetArguments()
{
$app = new Application();
$resolver = new ControllerResolver($app);
$controller = function (Application $app) {};
$args = $resolver->getArguments(Request::create('/'), $controller);
$this->assertSame($app, $args[0]);
}
}

View File

@ -1,132 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Controller;
use Silex\Route;
/**
* Controller test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class ControllerTest extends \PHPUnit_Framework_TestCase
{
public function testBind()
{
$controller = new Controller(new Route('/foo'));
$ret = $controller->bind('foo');
$this->assertSame($ret, $controller);
$this->assertEquals('foo', $controller->getRouteName());
}
/**
* @expectedException \Silex\Exception\ControllerFrozenException
*/
public function testBindOnFrozenControllerShouldThrowException()
{
$controller = new Controller(new Route('/foo'));
$controller->bind('foo');
$controller->freeze();
$controller->bind('bar');
}
public function testAssert()
{
$controller = new Controller(new Route('/foo/{bar}'));
$ret = $controller->assert('bar', '\d+');
$this->assertSame($ret, $controller);
$this->assertEquals(array('bar' => '\d+'), $controller->getRoute()->getRequirements());
}
public function testValue()
{
$controller = new Controller(new Route('/foo/{bar}'));
$ret = $controller->value('bar', 'foo');
$this->assertSame($ret, $controller);
$this->assertEquals(array('bar' => 'foo'), $controller->getRoute()->getDefaults());
}
public function testConvert()
{
$controller = new Controller(new Route('/foo/{bar}'));
$ret = $controller->convert('bar', $func = function ($bar) { return $bar; });
$this->assertSame($ret, $controller);
$this->assertEquals(array('bar' => $func), $controller->getRoute()->getOption('_converters'));
}
public function testRun()
{
$controller = new Controller(new Route('/foo/{bar}'));
$ret = $controller->run($cb = function () { return 'foo'; });
$this->assertSame($ret, $controller);
$this->assertEquals($cb, $controller->getRoute()->getDefault('_controller'));
}
/**
* @dataProvider provideRouteAndExpectedRouteName
*/
public function testDefaultRouteNameGeneration(Route $route, $prefix, $expectedRouteName)
{
$controller = new Controller($route);
$controller->bind($controller->generateRouteName($prefix));
$this->assertEquals($expectedRouteName, $controller->getRouteName());
}
public function provideRouteAndExpectedRouteName()
{
return array(
array(new Route('/Invalid%Symbols#Stripped', array(), array(), array(), '', array(), array('POST')), '', 'POST_InvalidSymbolsStripped'),
array(new Route('/post/{id}', array(), array(), array(), '', array(), array('GET')), '', 'GET_post_id'),
array(new Route('/colon:pipe|dashes-escaped'), '', '_colon_pipe_dashes_escaped'),
array(new Route('/underscores_and.periods'), '', '_underscores_and.periods'),
array(new Route('/post/{id}', array(), array(), array(), '', array(), array('GET')), 'prefix', 'GET_prefix_post_id'),
);
}
public function testRouteExtension()
{
$route = new MyRoute();
$controller = new Controller($route);
$controller->foo('foo');
$this->assertEquals('foo', $route->foo);
}
/**
* @expectedException \BadMethodCallException
*/
public function testRouteMethodDoesNotExist()
{
$route = new MyRoute();
$controller = new Controller($route);
$controller->bar();
}
}
class MyRoute extends Route
{
public $foo;
public function foo($value)
{
$this->foo = $value;
}
}

View File

@ -1,93 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\EventListener;
use Psr\Log\LogLevel;
use Silex\EventListener\LogListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* LogListener.
*
* @author Jérôme Tamarelle <jerome@tamarelle.net>
*/
class LogListenerTest extends \PHPUnit_Framework_TestCase
{
public function testRequestListener()
{
$logger = $this->getMock('Psr\\Log\\LoggerInterface');
$logger
->expects($this->once())
->method('log')
->with(LogLevel::DEBUG, '> GET /foo')
;
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new LogListener($logger));
$kernel = $this->getMock('Symfony\\Component\\HttpKernel\\HttpKernelInterface');
$dispatcher->dispatch(KernelEvents::REQUEST, new GetResponseEvent($kernel, Request::create('/subrequest'), HttpKernelInterface::SUB_REQUEST), 'Skip sub requests');
$dispatcher->dispatch(KernelEvents::REQUEST, new GetResponseEvent($kernel, Request::create('/foo'), HttpKernelInterface::MASTER_REQUEST), 'Log master requests');
}
public function testResponseListener()
{
$logger = $this->getMock('Psr\\Log\\LoggerInterface');
$logger
->expects($this->once())
->method('log')
->with(LogLevel::DEBUG, '< 301')
;
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new LogListener($logger));
$kernel = $this->getMock('Symfony\\Component\\HttpKernel\\HttpKernelInterface');
$dispatcher->dispatch(KernelEvents::RESPONSE, new FilterResponseEvent($kernel, Request::create('/foo'), HttpKernelInterface::SUB_REQUEST, Response::create('subrequest', 200)), 'Skip sub requests');
$dispatcher->dispatch(KernelEvents::RESPONSE, new FilterResponseEvent($kernel, Request::create('/foo'), HttpKernelInterface::MASTER_REQUEST, Response::create('bar', 301)), 'Log master requests');
}
public function testExceptionListener()
{
$logger = $this->getMock('Psr\\Log\\LoggerInterface');
$logger
->expects($this->at(0))
->method('log')
->with(LogLevel::CRITICAL, 'RuntimeException: Fatal error (uncaught exception) at '.__FILE__.' line '.(__LINE__ + 13))
;
$logger
->expects($this->at(1))
->method('log')
->with(LogLevel::ERROR, 'Symfony\Component\HttpKernel\Exception\HttpException: Http error (uncaught exception) at '.__FILE__.' line '.(__LINE__ + 9))
;
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new LogListener($logger));
$kernel = $this->getMock('Symfony\\Component\\HttpKernel\\HttpKernelInterface');
$dispatcher->dispatch(KernelEvents::EXCEPTION, new GetResponseForExceptionEvent($kernel, Request::create('/foo'), HttpKernelInterface::SUB_REQUEST, new \RuntimeException('Fatal error')));
$dispatcher->dispatch(KernelEvents::EXCEPTION, new GetResponseForExceptionEvent($kernel, Request::create('/foo'), HttpKernelInterface::SUB_REQUEST, new HttpException(400, 'Http error')));
}
}

View File

@ -1,406 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Error handler test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class ExceptionHandlerTest extends \PHPUnit_Framework_TestCase
{
public function testExceptionHandlerExceptionNoDebug()
{
$app = new Application();
$app['debug'] = false;
$app->match('/foo', function () {
throw new \RuntimeException('foo exception');
});
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertContains('<h1>Whoops, looks like something went wrong.</h1>', $response->getContent());
$this->assertEquals(500, $response->getStatusCode());
}
public function testExceptionHandlerExceptionDebug()
{
$app = new Application();
$app['debug'] = true;
$app->match('/foo', function () {
throw new \RuntimeException('foo exception');
});
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertContains('foo exception', $response->getContent());
$this->assertEquals(500, $response->getStatusCode());
}
public function testExceptionHandlerNotFoundNoDebug()
{
$app = new Application();
$app['debug'] = false;
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertContains('<h1>Sorry, the page you are looking for could not be found.</h1>', $response->getContent());
$this->assertEquals(404, $response->getStatusCode());
}
public function testExceptionHandlerNotFoundDebug()
{
$app = new Application();
$app['debug'] = true;
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertContains('No route found for "GET /foo"', html_entity_decode($response->getContent()));
$this->assertEquals(404, $response->getStatusCode());
}
public function testExceptionHandlerMethodNotAllowedNoDebug()
{
$app = new Application();
$app['debug'] = false;
$app->get('/foo', function () { return 'foo'; });
$request = Request::create('/foo', 'POST');
$response = $app->handle($request);
$this->assertContains('<h1>Whoops, looks like something went wrong.</h1>', $response->getContent());
$this->assertEquals(405, $response->getStatusCode());
$this->assertEquals('GET', $response->headers->get('Allow'));
}
public function testExceptionHandlerMethodNotAllowedDebug()
{
$app = new Application();
$app['debug'] = true;
$app->get('/foo', function () { return 'foo'; });
$request = Request::create('/foo', 'POST');
$response = $app->handle($request);
$this->assertContains('No route found for "POST /foo": Method Not Allowed (Allow: GET)', html_entity_decode($response->getContent()));
$this->assertEquals(405, $response->getStatusCode());
$this->assertEquals('GET', $response->headers->get('Allow'));
}
public function testNoExceptionHandler()
{
$app = new Application();
unset($app['exception_handler']);
$app->match('/foo', function () {
throw new \RuntimeException('foo exception');
});
try {
$request = Request::create('/foo');
$app->handle($request);
$this->fail('->handle() should not catch exceptions where no error handler was supplied');
} catch (\RuntimeException $e) {
$this->assertEquals('foo exception', $e->getMessage());
}
}
public function testOneExceptionHandler()
{
$app = new Application();
$app->match('/500', function () {
throw new \RuntimeException('foo exception');
});
$app->match('/404', function () {
throw new NotFoundHttpException('foo exception');
});
$app->get('/405', function () { return 'foo'; });
$app->error(function ($e, $code) {
return new Response('foo exception handler');
});
$response = $this->checkRouteResponse($app, '/500', 'foo exception handler');
$this->assertEquals(500, $response->getStatusCode());
$response = $app->handle(Request::create('/404'));
$this->assertEquals(404, $response->getStatusCode());
$response = $app->handle(Request::create('/405', 'POST'));
$this->assertEquals(405, $response->getStatusCode());
$this->assertEquals('GET', $response->headers->get('Allow'));
}
public function testMultipleExceptionHandlers()
{
$app = new Application();
$app->match('/foo', function () {
throw new \RuntimeException('foo exception');
});
$errors = 0;
$app->error(function ($e) use (&$errors) {
++$errors;
});
$app->error(function ($e) use (&$errors) {
++$errors;
});
$app->error(function ($e) use (&$errors) {
++$errors;
return new Response('foo exception handler');
});
$app->error(function ($e) use (&$errors) {
// should not execute
++$errors;
});
$request = Request::create('/foo');
$this->checkRouteResponse($app, '/foo', 'foo exception handler', 'should return the first response returned by an exception handler');
$this->assertEquals(3, $errors, 'should execute error handlers until a response is returned');
}
public function testNoResponseExceptionHandler()
{
$app = new Application();
unset($app['exception_handler']);
$app->match('/foo', function () {
throw new \RuntimeException('foo exception');
});
$errors = 0;
$app->error(function ($e) use (&$errors) {
++$errors;
});
try {
$request = Request::create('/foo');
$app->handle($request);
$this->fail('->handle() should not catch exceptions where an empty error handler was supplied');
} catch (\RuntimeException $e) {
$this->assertEquals('foo exception', $e->getMessage());
} catch (\LogicException $e) {
$this->assertEquals('foo exception', $e->getPrevious()->getMessage());
}
$this->assertEquals(1, $errors, 'should execute the error handler');
}
public function testStringResponseExceptionHandler()
{
$app = new Application();
$app->match('/foo', function () {
throw new \RuntimeException('foo exception');
});
$app->error(function ($e) {
return 'foo exception handler';
});
$request = Request::create('/foo');
$this->checkRouteResponse($app, '/foo', 'foo exception handler', 'should accept a string response from the error handler');
}
public function testExceptionHandlerException()
{
$app = new Application();
$app->match('/foo', function () {
throw new \RuntimeException('foo exception');
});
$app->error(function ($e) {
throw new \RuntimeException('foo exception handler exception');
});
try {
$request = Request::create('/foo');
$app->handle($request);
$this->fail('->handle() should not catch exceptions thrown from an error handler');
} catch (\RuntimeException $e) {
$this->assertEquals('foo exception handler exception', $e->getMessage());
}
}
public function testRemoveExceptionHandlerAfterDispatcherAccess()
{
$app = new Application();
$app->match('/foo', function () {
throw new \RuntimeException('foo exception');
});
$app->before(function () {
// just making sure the dispatcher gets created
});
unset($app['exception_handler']);
try {
$request = Request::create('/foo');
$app->handle($request);
$this->fail('default exception handler should have been removed');
} catch (\RuntimeException $e) {
$this->assertEquals('foo exception', $e->getMessage());
}
}
public function testExceptionHandlerWithDefaultException()
{
$app = new Application();
$app['debug'] = false;
$app->match('/foo', function () {
throw new \Exception();
});
$app->error(function (\Exception $e) {
return new Response('Exception thrown', 500);
});
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertContains('Exception thrown', $response->getContent());
$this->assertEquals(500, $response->getStatusCode());
}
public function testExceptionHandlerWithStandardException()
{
$app = new Application();
$app['debug'] = false;
$app->match('/foo', function () {
// Throw a normal exception
throw new \Exception();
});
// Register 2 error handlers, each with a specified Exception class
// Since we throw a standard Exception above only
// the second error handler should fire
$app->error(function (\LogicException $e) { // Extends \Exception
return 'Caught LogicException';
});
$app->error(function (\Exception $e) {
return 'Caught Exception';
});
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertContains('Caught Exception', $response->getContent());
}
public function testExceptionHandlerWithSpecifiedException()
{
$app = new Application();
$app['debug'] = false;
$app->match('/foo', function () {
// Throw a specified exception
throw new \LogicException();
});
// Register 2 error handlers, each with a specified Exception class
// Since we throw a LogicException above
// the first error handler should fire
$app->error(function (\LogicException $e) { // Extends \Exception
return 'Caught LogicException';
});
$app->error(function (\Exception $e) {
return 'Caught Exception';
});
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertContains('Caught LogicException', $response->getContent());
}
public function testExceptionHandlerWithSpecifiedExceptionInReverseOrder()
{
$app = new Application();
$app['debug'] = false;
$app->match('/foo', function () {
// Throw a specified exception
throw new \LogicException();
});
// Register the \Exception error handler first, since the
// error handler works with an instanceof mechanism the
// second more specific error handler should not fire since
// the \Exception error handler is registered first and also
// captures all exceptions that extend it
$app->error(function (\Exception $e) {
return 'Caught Exception';
});
$app->error(function (\LogicException $e) { // Extends \Exception
return 'Caught LogicException';
});
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertContains('Caught Exception', $response->getContent());
}
public function testExceptionHandlerWithArrayStyleCallback()
{
$app = new Application();
$app['debug'] = false;
$app->match('/foo', function () {
throw new \Exception();
});
// Array style callback for error handler
$app->error(array($this, 'exceptionHandler'));
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertContains('Caught Exception', $response->getContent());
}
protected function checkRouteResponse($app, $path, $expectedContent, $method = 'get', $message = null)
{
$request = Request::create($path, $method);
$response = $app->handle($request);
$this->assertEquals($expectedContent, $response->getContent(), $message);
return $response;
}
public function exceptionHandler()
{
return 'Caught Exception';
}
}

View File

@ -1,58 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Silex\Route;
use Silex\ControllerCollection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Functional test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class FunctionalTest extends \PHPUnit_Framework_TestCase
{
public function testBind()
{
$app = new Application();
$app->get('/', function () {
return 'hello';
})
->bind('homepage');
$app->get('/foo', function () {
return 'foo';
})
->bind('foo_abc');
$app->flush();
$routes = $app['routes'];
$this->assertInstanceOf('Symfony\Component\Routing\Route', $routes->get('homepage'));
$this->assertInstanceOf('Symfony\Component\Routing\Route', $routes->get('foo_abc'));
}
public function testMount()
{
$mounted = new ControllerCollection(new Route());
$mounted->get('/{name}', function ($name) { return new Response($name); });
$app = new Application();
$app->mount('/hello', $mounted);
$response = $app->handle(Request::create('/hello/Silex'));
$this->assertEquals('Silex', $response->getContent());
}
}

View File

@ -1,56 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
/**
* JSON test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class JsonTest extends \PHPUnit_Framework_TestCase
{
public function testJsonReturnsJsonResponse()
{
$app = new Application();
$response = $app->json();
$this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
$response = json_decode($response->getContent(), true);
$this->assertSame(array(), $response);
}
public function testJsonUsesData()
{
$app = new Application();
$response = $app->json(array('foo' => 'bar'));
$this->assertSame('{"foo":"bar"}', $response->getContent());
}
public function testJsonUsesStatus()
{
$app = new Application();
$response = $app->json(array(), 202);
$this->assertSame(202, $response->getStatusCode());
}
public function testJsonUsesHeaders()
{
$app = new Application();
$response = $app->json(array(), 200, array('ETag' => 'foo'));
$this->assertSame('foo', $response->headers->get('ETag'));
}
}

View File

@ -1,59 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
class LazyDispatcherTest extends \PHPUnit_Framework_TestCase
{
/** @test */
public function beforeMiddlewareShouldNotCreateDispatcherEarly()
{
$dispatcherCreated = false;
$app = new Application();
$app->extend('dispatcher', function ($dispatcher, $app) use (&$dispatcherCreated) {
$dispatcherCreated = true;
return $dispatcher;
});
$app->before(function () {});
$this->assertFalse($dispatcherCreated);
$request = Request::create('/');
$app->handle($request);
$this->assertTrue($dispatcherCreated);
}
/** @test */
public function eventHelpersShouldDirectlyAddListenersAfterBoot()
{
$app = new Application();
$fired = false;
$app->get('/', function () use ($app, &$fired) {
$app->finish(function () use (&$fired) {
$fired = true;
});
});
$request = Request::create('/');
$response = $app->handle($request);
$app->terminate($request, $response);
$this->assertTrue($fired, 'Event was not fired');
}
}

View File

@ -1,77 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Symfony\Component\HttpFoundation\Request;
use Silex\Provider\Routing\LazyRequestMatcher;
/**
* LazyRequestMatcher test case.
*
* @author Leszek Prabucki <leszek.prabucki@gmail.com>
*/
class LazyRequestMatcherTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers Silex\LazyRequestMatcher::getRequestMatcher
*/
public function testUserMatcherIsCreatedLazily()
{
$callCounter = 0;
$requestMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
$matcher = new LazyRequestMatcher(function () use ($requestMatcher, &$callCounter) {
++$callCounter;
return $requestMatcher;
});
$this->assertEquals(0, $callCounter);
$request = Request::create('path');
$matcher->matchRequest($request);
$this->assertEquals(1, $callCounter);
}
/**
* @expectedException LogicException
* @expectedExceptionMessage Factory supplied to LazyRequestMatcher must return implementation of Symfony\Component\Routing\RequestMatcherInterface.
*/
public function testThatCanInjectRequestMatcherOnly()
{
$matcher = new LazyRequestMatcher(function () {
return 'someMatcher';
});
$request = Request::create('path');
$matcher->matchRequest($request);
}
/**
* @covers Silex\LazyRequestMatcher::matchRequest
*/
public function testMatchIsProxy()
{
$request = Request::create('path');
$matcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
$matcher->expects($this->once())
->method('matchRequest')
->with($request)
->will($this->returnValue('matcherReturnValue'));
$matcher = new LazyRequestMatcher(function () use ($matcher) {
return $matcher;
});
$result = $matcher->matchRequest($request);
$this->assertEquals('matcherReturnValue', $result);
}
}

View File

@ -1,83 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Silex\Provider\LocaleServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Locale test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class LocaleTest extends \PHPUnit_Framework_TestCase
{
public function testLocale()
{
$app = new Application();
$app->register(new LocaleServiceProvider());
$app->get('/', function (Request $request) { return $request->getLocale(); });
$response = $app->handle(Request::create('/'));
$this->assertEquals('en', $response->getContent());
$app = new Application();
$app->register(new LocaleServiceProvider());
$app['locale'] = 'fr';
$app->get('/', function (Request $request) { return $request->getLocale(); });
$response = $app->handle(Request::create('/'));
$this->assertEquals('fr', $response->getContent());
$app = new Application();
$app->register(new LocaleServiceProvider());
$app->get('/{_locale}', function (Request $request) { return $request->getLocale(); });
$response = $app->handle(Request::create('/es'));
$this->assertEquals('es', $response->getContent());
}
public function testLocaleInSubRequests()
{
$app = new Application();
$app->register(new LocaleServiceProvider());
$app->get('/embed/{_locale}', function (Request $request) { return $request->getLocale(); });
$app->get('/{_locale}', function (Request $request) use ($app) {
return $request->getLocale().$app->handle(Request::create('/embed/es'), HttpKernelInterface::SUB_REQUEST)->getContent().$request->getLocale();
});
$response = $app->handle(Request::create('/fr'));
$this->assertEquals('fresfr', $response->getContent());
$app = new Application();
$app->register(new LocaleServiceProvider());
$app->get('/embed', function (Request $request) { return $request->getLocale(); });
$app->get('/{_locale}', function (Request $request) use ($app) {
return $request->getLocale().$app->handle(Request::create('/embed'), HttpKernelInterface::SUB_REQUEST)->getContent().$request->getLocale();
});
$response = $app->handle(Request::create('/fr'));
// locale in sub-request must be "en" as this is the value if the sub-request is converted to an ESI
$this->assertEquals('frenfr', $response->getContent());
}
public function testLocaleWithBefore()
{
$app = new Application();
$app->register(new LocaleServiceProvider());
$app->before(function (Request $request) use ($app) { $request->setLocale('fr'); });
$app->get('/embed', function (Request $request) { return $request->getLocale(); });
$app->get('/', function (Request $request) use ($app) {
return $request->getLocale().$app->handle(Request::create('/embed'), HttpKernelInterface::SUB_REQUEST)->getContent().$request->getLocale();
});
$response = $app->handle(Request::create('/'));
// locale in sub-request is "en" as the before filter is only executed for the main request
$this->assertEquals('frenfr', $response->getContent());
}
}

View File

@ -1,307 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Middleware test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class MiddlewareTest extends \PHPUnit_Framework_TestCase
{
public function testBeforeAndAfterFilter()
{
$i = 0;
$test = $this;
$app = new Application();
$app->before(function () use (&$i, $test) {
$test->assertEquals(0, $i);
++$i;
});
$app->match('/foo', function () use (&$i, $test) {
$test->assertEquals(1, $i);
++$i;
});
$app->after(function () use (&$i, $test) {
$test->assertEquals(2, $i);
++$i;
});
$request = Request::create('/foo');
$app->handle($request);
$this->assertEquals(3, $i);
}
public function testAfterFilterWithResponseObject()
{
$i = 0;
$app = new Application();
$app->match('/foo', function () use (&$i) {
++$i;
return new Response('foo');
});
$app->after(function () use (&$i) {
++$i;
});
$request = Request::create('/foo');
$app->handle($request);
$this->assertEquals(2, $i);
}
public function testMultipleFilters()
{
$i = 0;
$test = $this;
$app = new Application();
$app->before(function () use (&$i, $test) {
$test->assertEquals(0, $i);
++$i;
});
$app->before(function () use (&$i, $test) {
$test->assertEquals(1, $i);
++$i;
});
$app->match('/foo', function () use (&$i, $test) {
$test->assertEquals(2, $i);
++$i;
});
$app->after(function () use (&$i, $test) {
$test->assertEquals(3, $i);
++$i;
});
$app->after(function () use (&$i, $test) {
$test->assertEquals(4, $i);
++$i;
});
$request = Request::create('/foo');
$app->handle($request);
$this->assertEquals(5, $i);
}
public function testFiltersShouldFireOnException()
{
$i = 0;
$app = new Application();
$app->before(function () use (&$i) {
++$i;
});
$app->match('/foo', function () {
throw new \RuntimeException();
});
$app->after(function () use (&$i) {
++$i;
});
$app->error(function () {
return 'error handled';
});
$request = Request::create('/foo');
$app->handle($request);
$this->assertEquals(2, $i);
}
public function testFiltersShouldFireOnHttpException()
{
$i = 0;
$app = new Application();
$app->before(function () use (&$i) {
++$i;
}, Application::EARLY_EVENT);
$app->after(function () use (&$i) {
++$i;
});
$app->error(function () {
return 'error handled';
});
$request = Request::create('/nowhere');
$app->handle($request);
$this->assertEquals(2, $i);
}
public function testBeforeFilterPreventsBeforeMiddlewaresToBeExecuted()
{
$app = new Application();
$app->before(function () { return new Response('app before'); });
$app->get('/', function () {
return new Response('test');
})->before(function () {
return new Response('middleware before');
});
$this->assertEquals('app before', $app->handle(Request::create('/'))->getContent());
}
public function testBeforeFilterExceptionsWhenHandlingAnException()
{
$app = new Application();
$app->before(function () { throw new \RuntimeException(''); });
// even if the before filter throws an exception, we must have the 404
$this->assertEquals(404, $app->handle(Request::create('/'))->getStatusCode());
}
public function testRequestShouldBePopulatedOnBefore()
{
$app = new Application();
$app->before(function (Request $request) use ($app) {
$app['project'] = $request->get('project');
});
$app->match('/foo/{project}', function () use ($app) {
return $app['project'];
});
$request = Request::create('/foo/bar');
$this->assertEquals('bar', $app->handle($request)->getContent());
$request = Request::create('/foo/baz');
$this->assertEquals('baz', $app->handle($request)->getContent());
}
public function testBeforeFilterAccessesRequestAndCanReturnResponse()
{
$app = new Application();
$app->before(function (Request $request) {
return new Response($request->get('name'));
});
$app->match('/', function () use ($app) { throw new \Exception('Should never be executed'); });
$request = Request::create('/?name=Fabien');
$this->assertEquals('Fabien', $app->handle($request)->getContent());
}
public function testAfterFilterAccessRequestResponse()
{
$app = new Application();
$app->after(function (Request $request, Response $response) {
$response->setContent($response->getContent().'---');
});
$app->match('/', function () { return new Response('foo'); });
$request = Request::create('/');
$this->assertEquals('foo---', $app->handle($request)->getContent());
}
public function testAfterFilterCanReturnResponse()
{
$app = new Application();
$app->after(function (Request $request, Response $response) {
return new Response('bar');
});
$app->match('/', function () { return new Response('foo'); });
$request = Request::create('/');
$this->assertEquals('bar', $app->handle($request)->getContent());
}
public function testRouteAndApplicationMiddlewareParameterInjection()
{
$app = new Application();
$test = $this;
$middlewareTarget = array();
$applicationBeforeMiddleware = function ($request, $app) use (&$middlewareTarget, $test) {
$test->assertInstanceOf('\Symfony\Component\HttpFoundation\Request', $request);
$test->assertInstanceOf('\Silex\Application', $app);
$middlewareTarget[] = 'application_before_middleware_triggered';
};
$applicationAfterMiddleware = function ($request, $response, $app) use (&$middlewareTarget, $test) {
$test->assertInstanceOf('\Symfony\Component\HttpFoundation\Request', $request);
$test->assertInstanceOf('\Symfony\Component\HttpFoundation\Response', $response);
$test->assertInstanceOf('\Silex\Application', $app);
$middlewareTarget[] = 'application_after_middleware_triggered';
};
$applicationFinishMiddleware = function ($request, $response, $app) use (&$middlewareTarget, $test) {
$test->assertInstanceOf('\Symfony\Component\HttpFoundation\Request', $request);
$test->assertInstanceOf('\Symfony\Component\HttpFoundation\Response', $response);
$test->assertInstanceOf('\Silex\Application', $app);
$middlewareTarget[] = 'application_finish_middleware_triggered';
};
$routeBeforeMiddleware = function ($request, $app) use (&$middlewareTarget, $test) {
$test->assertInstanceOf('\Symfony\Component\HttpFoundation\Request', $request);
$test->assertInstanceOf('\Silex\Application', $app);
$middlewareTarget[] = 'route_before_middleware_triggered';
};
$routeAfterMiddleware = function ($request, $response, $app) use (&$middlewareTarget, $test) {
$test->assertInstanceOf('\Symfony\Component\HttpFoundation\Request', $request);
$test->assertInstanceOf('\Symfony\Component\HttpFoundation\Response', $response);
$test->assertInstanceOf('\Silex\Application', $app);
$middlewareTarget[] = 'route_after_middleware_triggered';
};
$app->before($applicationBeforeMiddleware);
$app->after($applicationAfterMiddleware);
$app->finish($applicationFinishMiddleware);
$app->match('/', function () {
return new Response('foo');
})
->before($routeBeforeMiddleware)
->after($routeAfterMiddleware);
$request = Request::create('/');
$response = $app->handle($request);
$app->terminate($request, $response);
$this->assertSame(array('application_before_middleware_triggered', 'route_before_middleware_triggered', 'route_after_middleware_triggered', 'application_after_middleware_triggered', 'application_finish_middleware_triggered'), $middlewareTarget);
}
}

View File

@ -1,35 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\Provider\AssetServiceProvider;
class AssetServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testGenerateAssetUrl()
{
$app = new Application();
$app->register(new AssetServiceProvider(), array(
'assets.version' => 'v1',
'assets.version_format' => '%s?version=%s',
'assets.named_packages' => array(
'css' => array('version' => 'css2', 'base_path' => '/whatever-makes-sense'),
'images' => array('base_urls' => array('https://img.example.com')),
),
));
$this->assertEquals('/foo.png?version=v1', $app['assets.packages']->getUrl('/foo.png'));
$this->assertEquals('/whatever-makes-sense/foo.css?css2', $app['assets.packages']->getUrl('/foo.css', 'css'));
$this->assertEquals('https://img.example.com/foo.png', $app['assets.packages']->getUrl('/foo.png', 'images'));
}
}

View File

@ -1,116 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Pimple\Container;
use Silex\Application;
use Silex\Provider\DoctrineServiceProvider;
/**
* DoctrineProvider test cases.
*
* Fabien Potencier <fabien@symfony.com>
*/
class DoctrineServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testOptionsInitializer()
{
$app = new Application();
$app->register(new DoctrineServiceProvider());
$this->assertEquals($app['db.default_options'], $app['db']->getParams());
}
public function testSingleConnection()
{
if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
$this->markTestSkipped('pdo_sqlite is not available');
}
$app = new Application();
$app->register(new DoctrineServiceProvider(), array(
'db.options' => array('driver' => 'pdo_sqlite', 'memory' => true),
));
$db = $app['db'];
$params = $db->getParams();
$this->assertTrue(array_key_exists('memory', $params));
$this->assertTrue($params['memory']);
$this->assertInstanceof('Doctrine\DBAL\Driver\PDOSqlite\Driver', $db->getDriver());
$this->assertEquals(22, $app['db']->fetchColumn('SELECT 22'));
$this->assertSame($app['dbs']['default'], $db);
}
public function testMultipleConnections()
{
if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
$this->markTestSkipped('pdo_sqlite is not available');
}
$app = new Application();
$app->register(new DoctrineServiceProvider(), array(
'dbs.options' => array(
'sqlite1' => array('driver' => 'pdo_sqlite', 'memory' => true),
'sqlite2' => array('driver' => 'pdo_sqlite', 'path' => sys_get_temp_dir().'/silex'),
),
));
$db = $app['db'];
$params = $db->getParams();
$this->assertTrue(array_key_exists('memory', $params));
$this->assertTrue($params['memory']);
$this->assertInstanceof('Doctrine\DBAL\Driver\PDOSqlite\Driver', $db->getDriver());
$this->assertEquals(22, $app['db']->fetchColumn('SELECT 22'));
$this->assertSame($app['dbs']['sqlite1'], $db);
$db2 = $app['dbs']['sqlite2'];
$params = $db2->getParams();
$this->assertTrue(array_key_exists('path', $params));
$this->assertEquals(sys_get_temp_dir().'/silex', $params['path']);
}
public function testLoggerLoading()
{
if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
$this->markTestSkipped('pdo_sqlite is not available');
}
$app = new Application();
$this->assertTrue(isset($app['logger']));
$this->assertNull($app['logger']);
$app->register(new DoctrineServiceProvider(), array(
'dbs.options' => array(
'sqlite1' => array('driver' => 'pdo_sqlite', 'memory' => true),
),
));
$this->assertEquals(22, $app['db']->fetchColumn('SELECT 22'));
$this->assertNull($app['db']->getConfiguration()->getSQLLogger());
}
public function testLoggerNotLoaded()
{
if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
$this->markTestSkipped('pdo_sqlite is not available');
}
$app = new Container();
$app->register(new DoctrineServiceProvider(), array(
'dbs.options' => array(
'sqlite1' => array('driver' => 'pdo_sqlite', 'memory' => true),
),
));
$this->assertEquals(22, $app['db']->fetchColumn('SELECT 22'));
$this->assertNull($app['db']->getConfiguration()->getSQLLogger());
}
}

View File

@ -1,355 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\Provider\FormServiceProvider;
use Silex\Provider\CsrfServiceProvider;
use Silex\Provider\SessionServiceProvider;
use Silex\Provider\TranslationServiceProvider;
use Silex\Provider\ValidatorServiceProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormTypeGuesserChain;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Translation\Exception\NotFoundResourceException;
class FormServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testFormFactoryServiceIsFormFactory()
{
$app = new Application();
$app->register(new FormServiceProvider());
$this->assertInstanceOf('Symfony\Component\Form\FormFactory', $app['form.factory']);
}
public function testFormServiceProviderWillLoadTypes()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->extend('form.types', function ($extensions) {
$extensions[] = new DummyFormType();
return $extensions;
});
$form = $app['form.factory']->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array())
->add('dummy', 'Silex\Tests\Provider\DummyFormType')
->getForm();
$this->assertInstanceOf('Symfony\Component\Form\Form', $form);
}
public function testFormServiceProviderWillLoadTypesServices()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app['dummy'] = function () {
return new DummyFormType();
};
$app->extend('form.types', function ($extensions) {
$extensions[] = 'dummy';
return $extensions;
});
$form = $app['form.factory']
->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array())
->add('dummy', 'dummy')
->getForm();
$this->assertInstanceOf('Symfony\Component\Form\Form', $form);
}
/**
* @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException
* @expectedExceptionMessage Invalid form type. The silex service "dummy" does not exist.
*/
public function testNonExistentTypeService()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->extend('form.types', function ($extensions) {
$extensions[] = 'dummy';
return $extensions;
});
$app['form.factory']
->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array())
->add('dummy', 'dummy')
->getForm();
}
public function testFormServiceProviderWillLoadTypeExtensions()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->extend('form.type.extensions', function ($extensions) {
$extensions[] = new DummyFormTypeExtension();
return $extensions;
});
$form = $app['form.factory']->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array())
->add('file', 'Symfony\Component\Form\Extension\Core\Type\FileType', array('image_path' => 'webPath'))
->getForm();
$this->assertInstanceOf('Symfony\Component\Form\Form', $form);
}
public function testFormServiceProviderWillLoadTypeExtensionsServices()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app['dummy.form.type.extension'] = function () {
return new DummyFormTypeExtension();
};
$app->extend('form.type.extensions', function ($extensions) {
$extensions[] = 'dummy.form.type.extension';
return $extensions;
});
$form = $app['form.factory']
->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array())
->add('file', 'Symfony\Component\Form\Extension\Core\Type\FileType', array('image_path' => 'webPath'))
->getForm();
$this->assertInstanceOf('Symfony\Component\Form\Form', $form);
}
/**
* @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException
* @expectedExceptionMessage Invalid form type extension. The silex service "dummy.form.type.extension" does not exist.
*/
public function testNonExistentTypeExtensionService()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->extend('form.type.extensions', function ($extensions) {
$extensions[] = 'dummy.form.type.extension';
return $extensions;
});
$app['form.factory']
->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array())
->add('dummy', 'dummy.form.type')
->getForm();
}
public function testFormServiceProviderWillLoadTypeGuessers()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->extend('form.type.guessers', function ($guessers) {
$guessers[] = new FormTypeGuesserChain(array());
return $guessers;
});
$this->assertInstanceOf('Symfony\Component\Form\FormFactory', $app['form.factory']);
}
public function testFormServiceProviderWillLoadTypeGuessersServices()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app['dummy.form.type.guesser'] = function () {
return new FormTypeGuesserChain(array());
};
$app->extend('form.type.guessers', function ($guessers) {
$guessers[] = 'dummy.form.type.guesser';
return $guessers;
});
$this->assertInstanceOf('Symfony\Component\Form\FormFactory', $app['form.factory']);
}
/**
* @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException
* @expectedExceptionMessage Invalid form type guesser. The silex service "dummy.form.type.guesser" does not exist.
*/
public function testNonExistentTypeGuesserService()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->extend('form.type.guessers', function ($extensions) {
$extensions[] = 'dummy.form.type.guesser';
return $extensions;
});
$factory = $app['form.factory'];
}
public function testFormServiceProviderWillUseTranslatorIfAvailable()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->register(new TranslationServiceProvider());
$app['translator.domains'] = array(
'messages' => array(
'de' => array(
'The CSRF token is invalid. Please try to resubmit the form.' => 'German translation',
),
),
);
$app['locale'] = 'de';
$app['csrf.token_manager'] = function () {
return $this->getMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
};
$form = $app['form.factory']->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array())
->getForm();
$form->handleRequest($req = Request::create('/', 'POST', array('form' => array(
'_token' => 'the wrong token',
))));
$this->assertFalse($form->isValid());
$r = new \ReflectionMethod($form, 'getErrors');
if (!$r->getNumberOfParameters()) {
$this->assertContains('ERROR: German translation', $form->getErrorsAsString());
} else {
// as of 2.5
$this->assertContains('ERROR: German translation', (string) $form->getErrors(true, false));
}
}
public function testFormServiceProviderWillNotAddNonexistentTranslationFiles()
{
$app = new Application(array(
'locale' => 'nonexistent',
));
$app->register(new FormServiceProvider());
$app->register(new ValidatorServiceProvider());
$app->register(new TranslationServiceProvider(), array(
'locale_fallbacks' => array(),
));
$app['form.factory'];
$translator = $app['translator'];
try {
$translator->trans('test');
} catch (NotFoundResourceException $e) {
$this->fail('Form factory should not add a translation resource that does not exist');
}
}
public function testFormCsrf()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->register(new SessionServiceProvider());
$app->register(new CsrfServiceProvider());
$app['session.test'] = true;
$form = $app['form.factory']->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array())->getForm();
$this->assertTrue(isset($form->createView()['_token']));
}
public function testUserExtensionCanConfigureDefaultExtensions()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->register(new SessionServiceProvider());
$app->register(new CsrfServiceProvider());
$app['session.test'] = true;
$app->extend('form.type.extensions', function ($extensions) {
$extensions[] = new FormServiceProviderTest\DisableCsrfExtension();
return $extensions;
});
$form = $app['form.factory']->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array())->getForm();
$this->assertFalse($form->getConfig()->getOption('csrf_protection'));
}
}
if (!class_exists('Symfony\Component\Form\Deprecated\FormEvents')) {
class DummyFormType extends AbstractType
{
}
} else {
// FormTypeInterface::getName() is needed by the form component 2.8.x
class DummyFormType extends AbstractType
{
/**
* @return string The name of this type
*/
public function getName()
{
return 'dummy';
}
}
}
if (method_exists('Symfony\Component\Form\AbstractType', 'configureOptions')) {
class DummyFormTypeExtension extends AbstractTypeExtension
{
public function getExtendedType()
{
return 'Symfony\Component\Form\Extension\Core\Type\FileType';
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefined(array('image_path'));
}
}
} else {
class DummyFormTypeExtension extends AbstractTypeExtension
{
public function getExtendedType()
{
return 'Symfony\Component\Form\Extension\Core\Type\FileType';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
if (!method_exists($resolver, 'setDefined')) {
$resolver->setOptional(array('image_path'));
} else {
$resolver->setDefined(array('image_path'));
}
}
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace Silex\Tests\Provider\FormServiceProviderTest;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class DisableCsrfExtension extends AbstractTypeExtension
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'csrf_protection' => false,
));
}
public function getExtendedType()
{
return FormType::class;
}
}

View File

@ -1,80 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\Provider\HttpCacheServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* HttpCacheProvider test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class HttpCacheServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testRegister()
{
$app = new Application();
$app->register(new HttpCacheServiceProvider(), array(
'http_cache.cache_dir' => sys_get_temp_dir().'/silex_http_cache_'.uniqid(),
));
$this->assertInstanceOf('Silex\Provider\HttpCache\HttpCache', $app['http_cache']);
return $app;
}
/**
* @depends testRegister
*/
public function testRunCallsShutdown($app)
{
$finished = false;
$app->finish(function () use (&$finished) {
$finished = true;
});
$app->get('/', function () use ($app) {
return new UnsendableResponse('will do something after finish');
});
$request = Request::create('/');
$app['http_cache']->run($request);
$this->assertTrue($finished);
}
public function testDebugDefaultsToThatOfApp()
{
$app = new Application();
$app->register(new HttpCacheServiceProvider(), array(
'http_cache.cache_dir' => sys_get_temp_dir().'/silex_http_cache_'.uniqid(),
));
$app['debug'] = true;
$app['http_cache'];
$this->assertTrue($app['http_cache.options']['debug']);
}
}
class UnsendableResponse extends Response
{
public function send()
{
// do nothing
}
}

View File

@ -1,47 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\Provider\HttpCacheServiceProvider;
use Silex\Provider\HttpFragmentServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Symfony\Component\HttpFoundation\Request;
class HttpFragmentServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testRenderFunction()
{
$app = new Application();
$app->register(new HttpFragmentServiceProvider());
$app->register(new HttpCacheServiceProvider(), array('http_cache.cache_dir' => sys_get_temp_dir()));
$app->register(new TwigServiceProvider(), array(
'twig.templates' => array(
'hello' => '{{ render("/foo") }}{{ render_esi("/foo") }}{{ render_hinclude("/foo") }}',
'foo' => 'foo',
),
));
$app->get('/hello', function () use ($app) {
return $app['twig']->render('hello');
});
$app->get('/foo', function () use ($app) {
return $app['twig']->render('foo');
});
$response = $app['http_cache']->handle(Request::create('/hello'));
$this->assertEquals('foofoo<hx:include src="/foo"></hx:include>', $response->getContent());
}
}

View File

@ -1,218 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
use Silex\Application;
use Silex\Provider\MonologServiceProvider;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Kernel;
/**
* MonologProvider test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class MonologServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testRequestLogging()
{
$app = $this->getApplication();
$app->get('/foo', function () use ($app) {
return 'foo';
});
$this->assertFalse($app['monolog.handler']->hasInfoRecords());
$request = Request::create('/foo');
$app->handle($request);
$this->assertTrue($app['monolog.handler']->hasDebug('> GET /foo'));
$this->assertTrue($app['monolog.handler']->hasDebug('< 200'));
$records = $app['monolog.handler']->getRecords();
if (Kernel::VERSION_ID < 30100) {
$this->assertContains('Matched route "GET_foo"', $records[0]['message']);
} else {
$this->assertContains('Matched route "{route}".', $records[0]['message']);
$this->assertSame('GET_foo', $records[0]['context']['route']);
}
}
public function testManualLogging()
{
$app = $this->getApplication();
$app->get('/log', function () use ($app) {
$app['monolog']->addDebug('logging a message');
});
$this->assertFalse($app['monolog.handler']->hasDebugRecords());
$request = Request::create('/log');
$app->handle($request);
$this->assertTrue($app['monolog.handler']->hasDebug('logging a message'));
}
public function testOverrideFormatter()
{
$app = new Application();
$app->register(new MonologServiceProvider(), array(
'monolog.formatter' => new JsonFormatter(),
'monolog.logfile' => 'php://memory',
));
$this->assertInstanceOf('Monolog\Formatter\JsonFormatter', $app['monolog.handler']->getFormatter());
}
public function testErrorLogging()
{
$app = $this->getApplication();
$app->error(function (\Exception $e) {
return 'error handled';
});
/*
* Simulate 404, logged to error level
*/
$this->assertFalse($app['monolog.handler']->hasErrorRecords());
$request = Request::create('/error');
$app->handle($request);
$records = $app['monolog.handler']->getRecords();
$pattern = "#Symfony\\\\Component\\\\HttpKernel\\\\Exception\\\\NotFoundHttpException: No route found for \"GET /error\" \(uncaught exception\) at .* line \d+#";
$this->assertMatchingRecord($pattern, Logger::ERROR, $app['monolog.handler']);
/*
* Simulate unhandled exception, logged to critical
*/
$app->get('/error', function () {
throw new \RuntimeException('very bad error');
});
$this->assertFalse($app['monolog.handler']->hasCriticalRecords());
$request = Request::create('/error');
$app->handle($request);
$pattern = "#RuntimeException: very bad error \(uncaught exception\) at .* line \d+#";
$this->assertMatchingRecord($pattern, Logger::CRITICAL, $app['monolog.handler']);
}
public function testRedirectLogging()
{
$app = $this->getApplication();
$app->get('/foo', function () use ($app) {
return new RedirectResponse('/bar', 302);
});
$this->assertFalse($app['monolog.handler']->hasInfoRecords());
$request = Request::create('/foo');
$app->handle($request);
$this->assertTrue($app['monolog.handler']->hasDebug('< 302 /bar'));
}
public function testErrorLoggingGivesWayToSecurityExceptionHandling()
{
$app = $this->getApplication();
$app['monolog.level'] = Logger::ERROR;
$app->register(new \Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'admin' => array(
'pattern' => '^/admin',
'http' => true,
'users' => array(),
),
),
));
$app->get('/admin', function () {
return 'SECURE!';
});
$request = Request::create('/admin');
$app->run($request);
$this->assertEmpty($app['monolog.handler']->getRecords(), 'Expected no logging to occur');
}
public function testStringErrorLevel()
{
$app = $this->getApplication();
$app['monolog.level'] = 'info';
$this->assertSame(Logger::INFO, $app['monolog.handler']->getLevel());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Provided logging level 'foo' does not exist. Must be a valid monolog logging level.
*/
public function testNonExistentStringErrorLevel()
{
$app = $this->getApplication();
$app['monolog.level'] = 'foo';
$app['monolog.handler']->getLevel();
}
public function testDisableListener()
{
$app = $this->getApplication();
unset($app['monolog.listener']);
$app->handle(Request::create('/404'));
$this->assertEmpty($app['monolog.handler']->getRecords(), 'Expected no logging to occur');
}
protected function assertMatchingRecord($pattern, $level, $handler)
{
$found = false;
$records = $handler->getRecords();
foreach ($records as $record) {
if (preg_match($pattern, $record['message']) && $record['level'] == $level) {
$found = true;
continue;
}
}
$this->assertTrue($found, "Trying to find record matching $pattern with level $level");
}
protected function getApplication()
{
$app = new Application();
$app->register(new MonologServiceProvider(), array(
'monolog.handler' => function () use ($app) {
$level = MonologServiceProvider::translateLevel($app['monolog.level']);
return new TestHandler($level);
},
'monolog.logfile' => 'php://memory',
));
return $app;
}
}

View File

@ -1,107 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\WebTestCase;
use Silex\Provider\RememberMeServiceProvider;
use Silex\Provider\SecurityServiceProvider;
use Silex\Provider\SessionServiceProvider;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* SecurityServiceProvider.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RememberMeServiceProviderTest extends WebTestCase
{
public function testRememberMeAuthentication()
{
$app = $this->createApplication();
$interactiveLogin = new InteractiveLoginTriggered();
$app->on(SecurityEvents::INTERACTIVE_LOGIN, array($interactiveLogin, 'onInteractiveLogin'));
$client = new Client($app);
$client->request('get', '/');
$this->assertFalse($interactiveLogin->triggered, 'The interactive login has not been triggered yet');
$client->request('post', '/login_check', array('_username' => 'fabien', '_password' => 'foo', '_remember_me' => 'true'));
$client->followRedirect();
$this->assertEquals('AUTHENTICATED_FULLY', $client->getResponse()->getContent());
$this->assertTrue($interactiveLogin->triggered, 'The interactive login has been triggered');
$this->assertNotNull($client->getCookiejar()->get('REMEMBERME'), 'The REMEMBERME cookie is set');
$event = false;
$client->getCookiejar()->expire('MOCKSESSID');
$client->request('get', '/');
$this->assertEquals('AUTHENTICATED_REMEMBERED', $client->getResponse()->getContent());
$this->assertTrue($interactiveLogin->triggered, 'The interactive login has been triggered');
$client->request('get', '/logout');
$client->followRedirect();
$this->assertNull($client->getCookiejar()->get('REMEMBERME'), 'The REMEMBERME cookie has been removed');
}
public function createApplication($authenticationMethod = 'form')
{
$app = new Application();
$app['debug'] = true;
unset($app['exception_handler']);
$app->register(new SessionServiceProvider(), array(
'session.test' => true,
));
$app->register(new SecurityServiceProvider());
$app->register(new RememberMeServiceProvider());
$app['security.firewalls'] = array(
'http-auth' => array(
'pattern' => '^.*$',
'form' => true,
'remember_me' => array(),
'logout' => true,
'users' => array(
'fabien' => array('ROLE_USER', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
),
),
);
$app->get('/', function () use ($app) {
if ($app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_FULLY')) {
return 'AUTHENTICATED_FULLY';
} elseif ($app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return 'AUTHENTICATED_REMEMBERED';
} else {
return 'AUTHENTICATED_ANONYMOUSLY';
}
});
return $app;
}
}
class InteractiveLoginTriggered
{
public $triggered = false;
public function onInteractiveLogin()
{
$this->triggered = true;
}
}

View File

@ -1,121 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Pimple\Container;
use Silex\Application;
use Silex\Provider\RoutingServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* RoutingProvider test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class RoutingServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testRegister()
{
$app = new Application();
$app->get('/hello/{name}', function ($name) {})
->bind('hello');
$app->get('/', function () {});
$request = Request::create('/');
$app->handle($request);
$this->assertInstanceOf('Symfony\Component\Routing\Generator\UrlGenerator', $app['url_generator']);
}
public function testUrlGeneration()
{
$app = new Application();
$app->get('/hello/{name}', function ($name) {})
->bind('hello');
$app->get('/', function () use ($app) {
return $app['url_generator']->generate('hello', array('name' => 'john'));
});
$request = Request::create('/');
$response = $app->handle($request);
$this->assertEquals('/hello/john', $response->getContent());
}
public function testAbsoluteUrlGeneration()
{
$app = new Application();
$app->get('/hello/{name}', function ($name) {})
->bind('hello');
$app->get('/', function () use ($app) {
return $app['url_generator']->generate('hello', array('name' => 'john'), UrlGeneratorInterface::ABSOLUTE_URL);
});
$request = Request::create('https://localhost:81/');
$response = $app->handle($request);
$this->assertEquals('https://localhost:81/hello/john', $response->getContent());
}
public function testUrlGenerationWithHttp()
{
$app = new Application();
$app->get('/insecure', function () {})
->bind('insecure_page')
->requireHttp();
$app->get('/', function () use ($app) {
return $app['url_generator']->generate('insecure_page');
});
$request = Request::create('https://localhost/');
$response = $app->handle($request);
$this->assertEquals('http://localhost/insecure', $response->getContent());
}
public function testUrlGenerationWithHttps()
{
$app = new Application();
$app->get('/secure', function () {})
->bind('secure_page')
->requireHttps();
$app->get('/', function () use ($app) {
return $app['url_generator']->generate('secure_page');
});
$request = Request::create('http://localhost/');
$response = $app->handle($request);
$this->assertEquals('https://localhost/secure', $response->getContent());
}
public function testControllersFactory()
{
$app = new Container();
$app->register(new RoutingServiceProvider());
$coll = $app['controllers_factory'];
$coll->mount('/blog', function ($blog) {
$this->assertInstanceOf('Silex\ControllerCollection', $blog);
});
}
}

View File

@ -1,440 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\WebTestCase;
use Silex\Provider\SecurityServiceProvider;
use Silex\Provider\SessionServiceProvider;
use Silex\Provider\ValidatorServiceProvider;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpFoundation\Request;
/**
* SecurityServiceProvider.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SecurityServiceProviderTest extends WebTestCase
{
/**
* @expectedException \LogicException
*/
public function testWrongAuthenticationType()
{
$app = new Application();
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'wrong' => array(
'foobar' => true,
'users' => array(),
),
),
));
$app->get('/', function () {});
$app->handle(Request::create('/'));
}
public function testFormAuthentication()
{
$app = $this->createApplication('form');
$client = new Client($app);
$client->request('get', '/');
$this->assertEquals('ANONYMOUS', $client->getResponse()->getContent());
$client->request('post', '/login_check', array('_username' => 'fabien', '_password' => 'bar'));
$this->assertContains('Bad credentials', $app['security.last_error']($client->getRequest()));
// hack to re-close the session as the previous assertions re-opens it
$client->getRequest()->getSession()->save();
$client->request('post', '/login_check', array('_username' => 'fabien', '_password' => 'foo'));
$this->assertEquals('', $app['security.last_error']($client->getRequest()));
$client->getRequest()->getSession()->save();
$this->assertEquals(302, $client->getResponse()->getStatusCode());
$this->assertEquals('http://localhost/', $client->getResponse()->getTargetUrl());
$client->request('get', '/');
$this->assertEquals('fabienAUTHENTICATED', $client->getResponse()->getContent());
$client->request('get', '/admin');
$this->assertEquals(403, $client->getResponse()->getStatusCode());
$client->request('get', '/logout');
$this->assertEquals(302, $client->getResponse()->getStatusCode());
$this->assertEquals('http://localhost/', $client->getResponse()->getTargetUrl());
$client->request('get', '/');
$this->assertEquals('ANONYMOUS', $client->getResponse()->getContent());
$client->request('get', '/admin');
$this->assertEquals(302, $client->getResponse()->getStatusCode());
$this->assertEquals('http://localhost/login', $client->getResponse()->getTargetUrl());
$client->request('post', '/login_check', array('_username' => 'admin', '_password' => 'foo'));
$this->assertEquals('', $app['security.last_error']($client->getRequest()));
$client->getRequest()->getSession()->save();
$this->assertEquals(302, $client->getResponse()->getStatusCode());
$this->assertEquals('http://localhost/admin', $client->getResponse()->getTargetUrl());
$client->request('get', '/');
$this->assertEquals('adminAUTHENTICATEDADMIN', $client->getResponse()->getContent());
$client->request('get', '/admin');
$this->assertEquals('admin', $client->getResponse()->getContent());
}
public function testHttpAuthentication()
{
$app = $this->createApplication('http');
$client = new Client($app);
$client->request('get', '/');
$this->assertEquals(401, $client->getResponse()->getStatusCode());
$this->assertEquals('Basic realm="Secured"', $client->getResponse()->headers->get('www-authenticate'));
$client->request('get', '/', array(), array(), array('PHP_AUTH_USER' => 'dennis', 'PHP_AUTH_PW' => 'foo'));
$this->assertEquals('dennisAUTHENTICATED', $client->getResponse()->getContent());
$client->request('get', '/admin');
$this->assertEquals(403, $client->getResponse()->getStatusCode());
$client->restart();
$client->request('get', '/');
$this->assertEquals(401, $client->getResponse()->getStatusCode());
$this->assertEquals('Basic realm="Secured"', $client->getResponse()->headers->get('www-authenticate'));
$client->request('get', '/', array(), array(), array('PHP_AUTH_USER' => 'admin', 'PHP_AUTH_PW' => 'foo'));
$this->assertEquals('adminAUTHENTICATEDADMIN', $client->getResponse()->getContent());
$client->request('get', '/admin');
$this->assertEquals('admin', $client->getResponse()->getContent());
}
public function testGuardAuthentication()
{
$app = $this->createApplication('guard');
$client = new Client($app);
$client->request('get', '/');
$this->assertEquals(401, $client->getResponse()->getStatusCode(), 'The entry point is configured');
$this->assertEquals('{"message":"Authentication Required"}', $client->getResponse()->getContent());
$client->request('get', '/', array(), array(), array('HTTP_X_AUTH_TOKEN' => 'lili:not the secret'));
$this->assertEquals(403, $client->getResponse()->getStatusCode(), 'User not found');
$this->assertEquals('{"message":"Username could not be found."}', $client->getResponse()->getContent());
$client->request('get', '/', array(), array(), array('HTTP_X_AUTH_TOKEN' => 'victoria:not the secret'));
$this->assertEquals(403, $client->getResponse()->getStatusCode(), 'Invalid credentials');
$this->assertEquals('{"message":"Invalid credentials."}', $client->getResponse()->getContent());
$client->request('get', '/', array(), array(), array('HTTP_X_AUTH_TOKEN' => 'victoria:victoriasecret'));
$this->assertEquals('victoria', $client->getResponse()->getContent());
}
public function testUserPasswordValidatorIsRegistered()
{
$app = new Application();
$app->register(new ValidatorServiceProvider());
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'admin' => array(
'pattern' => '^/admin',
'http' => true,
'users' => array(
'admin' => array('ROLE_ADMIN', '513aeb0121909'),
),
),
),
));
$app->boot();
$this->assertInstanceOf('Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator', $app['security.validator.user_password_validator']);
}
public function testExposedExceptions()
{
$app = $this->createApplication('form');
$app['security.hide_user_not_found'] = false;
$client = new Client($app);
$client->request('get', '/');
$this->assertEquals('ANONYMOUS', $client->getResponse()->getContent());
$client->request('post', '/login_check', array('_username' => 'fabien', '_password' => 'bar'));
$this->assertEquals('The presented password is invalid.', $app['security.last_error']($client->getRequest()));
$client->getRequest()->getSession()->save();
$client->request('post', '/login_check', array('_username' => 'unknown', '_password' => 'bar'));
$this->assertEquals('Username "unknown" does not exist.', $app['security.last_error']($client->getRequest()));
$client->getRequest()->getSession()->save();
}
public function testFakeRoutesAreSerializable()
{
$app = new Application();
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'admin' => array(
'logout' => true,
),
),
));
$app->boot();
$app->flush();
$this->assertCount(1, unserialize(serialize($app['routes'])));
}
public function testUser()
{
$app = new Application();
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'default' => array(
'http' => true,
'users' => array(
'fabien' => array('ROLE_ADMIN', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
),
),
),
));
$app->get('/', function () { return 'foo'; });
$request = Request::create('/');
$app->handle($request);
$this->assertNull($app['user']);
$request->headers->set('PHP_AUTH_USER', 'fabien');
$request->headers->set('PHP_AUTH_PW', 'foo');
$app->handle($request);
$this->assertInstanceOf('Symfony\Component\Security\Core\User\UserInterface', $app['user']);
$this->assertEquals('fabien', $app['user']->getUsername());
}
public function testUserWithNoToken()
{
$app = new Application();
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'default' => array(
'http' => true,
),
),
));
$request = Request::create('/');
$app->get('/', function () { return 'foo'; });
$app->handle($request);
$this->assertNull($app['user']);
}
public function testUserWithInvalidUser()
{
$app = new Application();
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'default' => array(
'http' => true,
),
),
));
$request = Request::create('/');
$app->boot();
$app['security.token_storage']->setToken(new UsernamePasswordToken('foo', 'foo', 'foo'));
$app->get('/', function () { return 'foo'; });
$app->handle($request);
$this->assertNull($app['user']);
}
public function testAccessRulePathArray()
{
$app = new Application();
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'default' => array(
'http' => true,
),
),
'security.access_rules' => array(
array(array(
'path' => '^/admin',
), 'ROLE_ADMIN'),
),
));
$request = Request::create('/admin');
$app->boot();
$accessMap = $app['security.access_map'];
$this->assertEquals($accessMap->getPatterns($request), array(
array('ROLE_ADMIN'),
'',
));
}
public function createApplication($authenticationMethod = 'form')
{
$app = new Application();
$app->register(new SessionServiceProvider());
$app = call_user_func(array($this, 'add'.ucfirst($authenticationMethod).'Authentication'), $app);
$app['session.test'] = true;
return $app;
}
private function addFormAuthentication($app)
{
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'login' => array(
'pattern' => '^/login$',
),
'default' => array(
'pattern' => '^.*$',
'anonymous' => true,
'form' => array(
'require_previous_session' => false,
),
'logout' => true,
'users' => array(
// password is foo
'fabien' => array('ROLE_USER', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
'admin' => array('ROLE_ADMIN', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
),
),
),
'security.access_rules' => array(
array('^/admin', 'ROLE_ADMIN'),
),
'security.role_hierarchy' => array(
'ROLE_ADMIN' => array('ROLE_USER'),
),
));
$app->get('/login', function (Request $request) use ($app) {
$app['session']->start();
return $app['security.last_error']($request);
});
$app->get('/', function () use ($app) {
$user = $app['security.token_storage']->getToken()->getUser();
$content = is_object($user) ? $user->getUsername() : 'ANONYMOUS';
if ($app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_FULLY')) {
$content .= 'AUTHENTICATED';
}
if ($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
$content .= 'ADMIN';
}
return $content;
});
$app->get('/admin', function () use ($app) {
return 'admin';
});
return $app;
}
private function addHttpAuthentication($app)
{
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'http-auth' => array(
'pattern' => '^.*$',
'http' => true,
'users' => array(
// password is foo
'dennis' => array('ROLE_USER', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
'admin' => array('ROLE_ADMIN', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
),
),
),
'security.access_rules' => array(
array('^/admin', 'ROLE_ADMIN'),
),
'security.role_hierarchy' => array(
'ROLE_ADMIN' => array('ROLE_USER'),
),
));
$app->get('/', function () use ($app) {
$user = $app['security.token_storage']->getToken()->getUser();
$content = is_object($user) ? $user->getUsername() : 'ANONYMOUS';
if ($app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_FULLY')) {
$content .= 'AUTHENTICATED';
}
if ($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
$content .= 'ADMIN';
}
return $content;
});
$app->get('/admin', function () use ($app) {
return 'admin';
});
return $app;
}
private function addGuardAuthentication($app)
{
$app['app.authenticator.token'] = function ($app) {
return new SecurityServiceProviderTest\TokenAuthenticator($app);
};
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'guard' => array(
'pattern' => '^.*$',
'form' => true,
'guard' => array(
'authenticators' => array(
'app.authenticator.token',
),
),
'users' => array(
'victoria' => array('ROLE_USER', 'victoriasecret'),
),
),
),
));
$app->get('/', function () use ($app) {
$user = $app['security.token_storage']->getToken()->getUser();
$content = is_object($user) ? $user->getUsername() : 'ANONYMOUS';
return $content;
})->bind('homepage');
return $app;
}
}

View File

@ -1,79 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider\SecurityServiceProviderTest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
* This class is used to test "guard" authentication with the SecurityServiceProvider.
*/
class TokenAuthenticator extends AbstractGuardAuthenticator
{
public function getCredentials(Request $request)
{
if (!$token = $request->headers->get('X-AUTH-TOKEN')) {
return;
}
list($username, $secret) = explode(':', $token);
return array(
'username' => $username,
'secret' => $secret,
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
return $userProvider->loadUserByUsername($credentials['username']);
}
public function checkCredentials($credentials, UserInterface $user)
{
// This is not a safe way of validating a password.
return $user->getPassword() === $credentials['secret'];
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
);
return new JsonResponse($data, 403);
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
'message' => 'Authentication Required',
);
return new JsonResponse($data, 401);
}
public function supportsRememberMe()
{
return false;
}
}

View File

@ -1,36 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\Provider\SerializerServiceProvider;
/**
* SerializerServiceProvider test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SerializerServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testRegister()
{
$app = new Application();
$app->register(new SerializerServiceProvider());
$this->assertInstanceOf("Symfony\Component\Serializer\Serializer", $app['serializer']);
$this->assertTrue($app['serializer']->supportsEncoding('xml'));
$this->assertTrue($app['serializer']->supportsEncoding('json'));
$this->assertTrue($app['serializer']->supportsDecoding('xml'));
$this->assertTrue($app['serializer']->supportsDecoding('json'));
}
}

View File

@ -1,126 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\WebTestCase;
use Silex\Provider\SessionServiceProvider;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpFoundation\Session;
/**
* SessionProvider test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
* @author Fabien Potencier <fabien@symfony.com>
*/
class SessionServiceProviderTest extends WebTestCase
{
public function testRegister()
{
/*
* Smoke test
*/
$defaultStorage = $this->app['session.storage.native'];
$client = $this->createClient();
$client->request('get', '/login');
$this->assertEquals('Logged in successfully.', $client->getResponse()->getContent());
$client->request('get', '/account');
$this->assertEquals('This is your account.', $client->getResponse()->getContent());
$client->request('get', '/logout');
$this->assertEquals('Logged out successfully.', $client->getResponse()->getContent());
$client->request('get', '/account');
$this->assertEquals('You are not logged in.', $client->getResponse()->getContent());
}
public function createApplication()
{
$app = new Application();
$app->register(new SessionServiceProvider(), array(
'session.test' => true,
));
$app->get('/login', function () use ($app) {
$app['session']->set('logged_in', true);
return 'Logged in successfully.';
});
$app->get('/account', function () use ($app) {
if (!$app['session']->get('logged_in')) {
return 'You are not logged in.';
}
return 'This is your account.';
});
$app->get('/logout', function () use ($app) {
$app['session']->invalidate();
return 'Logged out successfully.';
});
return $app;
}
public function testWithRoutesThatDoesNotUseSession()
{
$app = new Application();
$app->register(new SessionServiceProvider(), array(
'session.test' => true,
));
$app->get('/', function () {
return 'A welcome page.';
});
$app->get('/robots.txt', function () {
return 'Informations for robots.';
});
$app['debug'] = true;
unset($app['exception_handler']);
$client = new Client($app);
$client->request('get', '/');
$this->assertEquals('A welcome page.', $client->getResponse()->getContent());
$client->request('get', '/robots.txt');
$this->assertEquals('Informations for robots.', $client->getResponse()->getContent());
}
public function testSessionRegister()
{
$app = new Application();
$attrs = new Session\Attribute\AttributeBag();
$flash = new Session\Flash\FlashBag();
$app->register(new SessionServiceProvider(), array(
'session.attribute_bag' => $attrs,
'session.flash_bag' => $flash,
'session.test' => true,
));
$session = $app['session'];
$this->assertSame($flash, $session->getBag('flashes'));
$this->assertSame($attrs, $session->getBag('attributes'));
}
}

View File

@ -1,47 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
class SpoolStub implements \Swift_Spool
{
private $messages = array();
public $hasFlushed = false;
public function getMessages()
{
return $this->messages;
}
public function start()
{
}
public function stop()
{
}
public function isStarted()
{
return count($this->messages) > 0;
}
public function queueMessage(\Swift_Mime_Message $message)
{
$this->messages[] = $message;
}
public function flushQueue(\Swift_Transport $transport, &$failedRecipients = null)
{
$this->hasFlushed = true;
$this->messages = array();
}
}

View File

@ -1,92 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\Provider\SwiftmailerServiceProvider;
use Symfony\Component\HttpFoundation\Request;
class SwiftmailerServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testSwiftMailerServiceIsSwiftMailer()
{
$app = new Application();
$app->register(new SwiftmailerServiceProvider());
$app->boot();
$this->assertInstanceOf('Swift_Mailer', $app['mailer']);
}
public function testSwiftMailerIgnoresSpoolIfDisabled()
{
$app = new Application();
$app->register(new SwiftmailerServiceProvider());
$app->boot();
$app['swiftmailer.use_spool'] = false;
$app['swiftmailer.spooltransport'] = function () {
throw new \Exception('Should not be instantiated');
};
$this->assertInstanceOf('Swift_Mailer', $app['mailer']);
}
public function testSwiftMailerSendsMailsOnFinish()
{
$app = new Application();
$app->register(new SwiftmailerServiceProvider());
$app->boot();
$app['swiftmailer.spool'] = function () {
return new SpoolStub();
};
$app->get('/', function () use ($app) {
$app['mailer']->send(\Swift_Message::newInstance());
});
$this->assertCount(0, $app['swiftmailer.spool']->getMessages());
$request = Request::create('/');
$response = $app->handle($request);
$this->assertCount(1, $app['swiftmailer.spool']->getMessages());
$app->terminate($request, $response);
$this->assertTrue($app['swiftmailer.spool']->hasFlushed);
$this->assertCount(0, $app['swiftmailer.spool']->getMessages());
}
public function testSwiftMailerAvoidsFlushesIfMailerIsUnused()
{
$app = new Application();
$app->register(new SwiftmailerServiceProvider());
$app->boot();
$app['swiftmailer.spool'] = function () {
return new SpoolStub();
};
$app->get('/', function () use ($app) { });
$request = Request::create('/');
$response = $app->handle($request);
$this->assertCount(0, $app['swiftmailer.spool']->getMessages());
$app->terminate($request, $response);
$this->assertFalse($app['swiftmailer.spool']->hasFlushed);
}
}

View File

@ -1,181 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\Provider\TranslationServiceProvider;
use Silex\Provider\LocaleServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* TranslationProvider test cases.
*
* @author Daniel Tschinder <daniel@tschinder.de>
*/
class TranslationServiceProviderTest extends \PHPUnit_Framework_TestCase
{
/**
* @return Application
*/
protected function getPreparedApp()
{
$app = new Application();
$app->register(new LocaleServiceProvider());
$app->register(new TranslationServiceProvider());
$app['translator.domains'] = array(
'messages' => array(
'en' => array(
'key1' => 'The translation',
'key_only_english' => 'Foo',
'key2' => 'One apple|%count% apples',
'test' => array(
'key' => 'It works',
),
),
'de' => array(
'key1' => 'The german translation',
'key2' => 'One german apple|%count% german apples',
'test' => array(
'key' => 'It works in german',
),
),
),
);
return $app;
}
public function transChoiceProvider()
{
return array(
array('key2', 0, null, '0 apples'),
array('key2', 1, null, 'One apple'),
array('key2', 2, null, '2 apples'),
array('key2', 0, 'de', '0 german apples'),
array('key2', 1, 'de', 'One german apple'),
array('key2', 2, 'de', '2 german apples'),
array('key2', 0, 'ru', '0 apples'), // fallback
array('key2', 1, 'ru', 'One apple'), // fallback
array('key2', 2, 'ru', '2 apples'), // fallback
);
}
public function transProvider()
{
return array(
array('key1', null, 'The translation'),
array('key1', 'de', 'The german translation'),
array('key1', 'ru', 'The translation'), // fallback
array('test.key', null, 'It works'),
array('test.key', 'de', 'It works in german'),
array('test.key', 'ru', 'It works'), // fallback
);
}
/**
* @dataProvider transProvider
*/
public function testTransForDefaultLanguage($key, $locale, $expected)
{
$app = $this->getPreparedApp();
$result = $app['translator']->trans($key, array(), null, $locale);
$this->assertEquals($expected, $result);
}
/**
* @dataProvider transChoiceProvider
*/
public function testTransChoiceForDefaultLanguage($key, $number, $locale, $expected)
{
$app = $this->getPreparedApp();
$result = $app['translator']->transChoice($key, $number, array('%count%' => $number), null, $locale);
$this->assertEquals($expected, $result);
}
public function testFallbacks()
{
$app = $this->getPreparedApp();
$app['locale_fallbacks'] = array('de', 'en');
// fallback to english
$result = $app['translator']->trans('key_only_english', array(), null, 'ru');
$this->assertEquals('Foo', $result);
// fallback to german
$result = $app['translator']->trans('key1', array(), null, 'ru');
$this->assertEquals('The german translation', $result);
}
public function testLocale()
{
$app = $this->getPreparedApp();
$app->get('/', function () use ($app) { return $app['translator']->getLocale(); });
$response = $app->handle(Request::create('/'));
$this->assertEquals('en', $response->getContent());
$app = $this->getPreparedApp();
$app->get('/', function () use ($app) { return $app['translator']->getLocale(); });
$request = Request::create('/');
$request->setLocale('fr');
$response = $app->handle($request);
$this->assertEquals('fr', $response->getContent());
$app = $this->getPreparedApp();
$app->get('/{_locale}', function () use ($app) { return $app['translator']->getLocale(); });
$response = $app->handle(Request::create('/es'));
$this->assertEquals('es', $response->getContent());
}
public function testLocaleInSubRequests()
{
$app = $this->getPreparedApp();
$app->get('/embed/{_locale}', function () use ($app) { return $app['translator']->getLocale(); });
$app->get('/{_locale}', function () use ($app) {
return $app['translator']->getLocale().
$app->handle(Request::create('/embed/es'), HttpKernelInterface::SUB_REQUEST)->getContent().
$app['translator']->getLocale();
});
$response = $app->handle(Request::create('/fr'));
$this->assertEquals('fresfr', $response->getContent());
$app = $this->getPreparedApp();
$app->get('/embed', function () use ($app) { return $app['translator']->getLocale(); });
$app->get('/{_locale}', function () use ($app) {
return $app['translator']->getLocale().
$app->handle(Request::create('/embed'), HttpKernelInterface::SUB_REQUEST)->getContent().
$app['translator']->getLocale();
});
$response = $app->handle(Request::create('/fr'));
// locale in sub-request must be "en" as this is the value if the sub-request is converted to an ESI
$this->assertEquals('frenfr', $response->getContent());
}
public function testLocaleWithBefore()
{
$app = $this->getPreparedApp();
$app->before(function (Request $request) { $request->setLocale('fr'); }, Application::EARLY_EVENT);
$app->get('/embed', function () use ($app) { return $app['translator']->getLocale(); });
$app->get('/', function () use ($app) {
return $app['translator']->getLocale().
$app->handle(Request::create('/embed'), HttpKernelInterface::SUB_REQUEST)->getContent().
$app['translator']->getLocale();
});
$response = $app->handle(Request::create('/'));
// locale in sub-request is "en" as the before filter is only executed for the main request
$this->assertEquals('frenfr', $response->getContent());
}
}

View File

@ -1,119 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\Provider\CsrfServiceProvider;
use Silex\Provider\FormServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\AssetServiceProvider;
use Symfony\Component\HttpFoundation\Request;
/**
* TwigProvider test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class TwigServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testRegisterAndRender()
{
$app = new Application();
$app->register(new TwigServiceProvider(), array(
'twig.templates' => array('hello' => 'Hello {{ name }}!'),
));
$app->get('/hello/{name}', function ($name) use ($app) {
return $app['twig']->render('hello', array('name' => $name));
});
$request = Request::create('/hello/john');
$response = $app->handle($request);
$this->assertEquals('Hello john!', $response->getContent());
}
public function testLoaderPriority()
{
$app = new Application();
$app->register(new TwigServiceProvider(), array(
'twig.templates' => array('foo' => 'foo'),
));
$loader = $this->getMock('\Twig_LoaderInterface');
$loader->expects($this->never())->method('getSource');
$app['twig.loader.filesystem'] = function ($app) use ($loader) {
return $loader;
};
$this->assertEquals('foo', $app['twig.loader']->getSource('foo'));
}
public function testHttpFoundationIntegration()
{
$app = new Application();
$app['request_stack']->push(Request::create('/dir1/dir2/file'));
$app->register(new TwigServiceProvider(), array(
'twig.templates' => array(
'absolute' => '{{ absolute_url("foo.css") }}',
'relative' => '{{ relative_path("/dir1/foo.css") }}',
),
));
$this->assertEquals('http://localhost/dir1/dir2/foo.css', $app['twig']->render('absolute'));
$this->assertEquals('../foo.css', $app['twig']->render('relative'));
}
public function testAssetIntegration()
{
$app = new Application();
$app->register(new TwigServiceProvider(), array(
'twig.templates' => array('hello' => '{{ asset("/foo.css") }}'),
));
$app->register(new AssetServiceProvider(), array(
'assets.version' => 1,
));
$this->assertEquals('/foo.css?1', $app['twig']->render('hello'));
}
public function testGlobalVariable()
{
$app = new Application();
$app['request_stack']->push(Request::create('/?name=Fabien'));
$app->register(new TwigServiceProvider(), array(
'twig.templates' => array('hello' => '{{ global.request.get("name") }}'),
));
$this->assertEquals('Fabien', $app['twig']->render('hello'));
}
public function testFormFactory()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->register(new CsrfServiceProvider());
$app->register(new TwigServiceProvider());
$this->assertInstanceOf('Twig_Environment', $app['twig'], 'Service twig is created successful.');
$this->assertInstanceOf('Symfony\Bridge\Twig\Form\TwigRendererEngine', $app['twig.form.engine'], 'Service twig.form.engine is created successful.');
$this->assertInstanceOf('Symfony\Bridge\Twig\Form\TwigRenderer', $app['twig.form.renderer'], 'Service twig.form.renderer is created successful.');
}
public function testFormWithoutCsrf()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->register(new TwigServiceProvider());
$this->assertInstanceOf('Twig_Environment', $app['twig']);
}
}

View File

@ -1,194 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider;
use Silex\Application;
use Silex\Provider\TranslationServiceProvider;
use Silex\Provider\ValidatorServiceProvider;
use Silex\Provider\FormServiceProvider;
use Symfony\Component\Translation\Exception\NotFoundResourceException;
use Symfony\Component\Validator\Constraints as Assert;
use Silex\Tests\Provider\ValidatorServiceProviderTest\Constraint\Custom;
use Silex\Tests\Provider\ValidatorServiceProviderTest\Constraint\CustomValidator;
use Symfony\Component\Validator\ValidatorInterface as LegacyValidatorInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* ValidatorServiceProvider.
*
* Javier Lopez <f12loalf@gmail.com>
*/
class ValidatorServiceProviderTest extends \PHPUnit_Framework_TestCase
{
public function testRegister()
{
$app = new Application();
$app->register(new ValidatorServiceProvider());
$app->register(new FormServiceProvider());
return $app;
}
public function testRegisterWithCustomValidators()
{
$app = new Application();
$app['custom.validator'] = function () {
return new CustomValidator();
};
$app->register(new ValidatorServiceProvider(), array(
'validator.validator_service_ids' => array(
'test.custom.validator' => 'custom.validator',
),
));
return $app;
}
/**
* @depends testRegisterWithCustomValidators
*/
public function testConstraintValidatorFactory($app)
{
$this->assertInstanceOf('Silex\Provider\Validator\ConstraintValidatorFactory', $app['validator.validator_factory']);
$validator = $app['validator.validator_factory']->getInstance(new Custom());
$this->assertInstanceOf('Silex\Tests\Provider\ValidatorServiceProviderTest\Constraint\CustomValidator', $validator);
}
/**
* @depends testRegister
*/
public function testConstraintValidatorFactoryWithExpression($app)
{
$constraint = new Assert\Expression('true');
$validator = $app['validator.validator_factory']->getInstance($constraint);
$this->assertInstanceOf('Symfony\Component\Validator\Constraints\ExpressionValidator', $validator);
}
/**
* @depends testRegister
*/
public function testValidatorServiceIsAValidator($app)
{
$this->assertTrue($app['validator'] instanceof ValidatorInterface || $app['validator'] instanceof LegacyValidatorInterface );
}
/**
* @depends testRegister
* @dataProvider getTestValidatorConstraintProvider
*/
public function testValidatorConstraint($email, $isValid, $nbGlobalError, $nbEmailError, $app)
{
$constraints = new Assert\Collection(array(
'email' => array(
new Assert\NotBlank(),
new Assert\Email(),
),
));
$builder = $app['form.factory']->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', array(), array(
'constraints' => $constraints,
));
$form = $builder
->add('email', 'Symfony\Component\Form\Extension\Core\Type\EmailType', array('label' => 'Email'))
->getForm()
;
$form->submit(array('email' => $email));
$this->assertEquals($isValid, $form->isValid());
$this->assertEquals($nbGlobalError, count($form->getErrors()));
$this->assertEquals($nbEmailError, count($form->offsetGet('email')->getErrors()));
}
public function testValidatorWillNotAddNonexistentTranslationFiles()
{
$app = new Application(array(
'locale' => 'nonexistent',
));
$app->register(new ValidatorServiceProvider());
$app->register(new TranslationServiceProvider(), array(
'locale_fallbacks' => array(),
));
$app['validator'];
$translator = $app['translator'];
try {
$translator->trans('test');
} catch (NotFoundResourceException $e) {
$this->fail('Validator should not add a translation resource that does not exist');
}
}
public function getTestValidatorConstraintProvider()
{
// Email, form is valid, nb global error, nb email error
return array(
array('', false, 0, 1),
array('not an email', false, 0, 1),
array('email@sample.com', true, 0, 0),
);
}
/**
* @dataProvider getAddResourceData
*/
public function testAddResource($registerValidatorFirst)
{
$app = new Application();
$app['locale'] = 'fr';
$app->register(new ValidatorServiceProvider());
$app->register(new TranslationServiceProvider());
$app['translator'] = $app->extend('translator', function ($translator, $app) {
$translator->addResource('array', array('This value should not be blank.' => 'Pas vide'), 'fr', 'validators');
return $translator;
});
if ($registerValidatorFirst) {
$app['validator'];
}
$this->assertEquals('Pas vide', $app['translator']->trans('This value should not be blank.', array(), 'validators', 'fr'));
}
public function getAddResourceData()
{
return array(array(false), array(true));
}
public function testAddResourceAlternate()
{
$app = new Application();
$app['locale'] = 'fr';
$app->register(new ValidatorServiceProvider());
$app->register(new TranslationServiceProvider());
$app->factory($app->extend('translator.resources', function ($resources, $app) {
$resources = array_merge($resources, array(
array('array', array('This value should not be blank.' => 'Pas vide'), 'fr', 'validators'),
));
return $resources;
}));
$app['validator'];
$this->assertEquals('Pas vide', $app['translator']->trans('This value should not be blank.', array(), 'validators', 'fr'));
}
}

View File

@ -1,29 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider\ValidatorServiceProviderTest\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* @author Alex Kalyvitis <alex.kalyvitis@gmail.com>
*/
class Custom extends Constraint
{
public $message = 'This field must be ...';
public $table;
public $field;
public function validatedBy()
{
return 'test.custom.validator';
}
}

View File

@ -1,32 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Provider\ValidatorServiceProviderTest\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* @author Alex Kalyvitis <alex.kalyvitis@gmail.com>
*/
class CustomValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
// Validate...
return true;
}
public function validate($value, Constraint $constraint)
{
return $this->isValid($value, $constraint);
}
}

View File

@ -1,19 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Route;
use Silex\Route;
class SecurityRoute extends Route
{
use Route\SecurityTrait;
}

View File

@ -1,85 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests\Route;
use Silex\Application;
use Silex\Provider\SecurityServiceProvider;
use Symfony\Component\HttpFoundation\Request;
/**
* SecurityTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SecurityTraitTest extends \PHPUnit_Framework_TestCase
{
public function testSecureWithNoAuthenticatedUser()
{
$app = $this->createApplication();
$app->get('/', function () { return 'foo'; })
->secure('ROLE_ADMIN')
;
$request = Request::create('/');
$response = $app->handle($request);
$this->assertEquals(401, $response->getStatusCode());
}
public function testSecureWithAuthorizedRoles()
{
$app = $this->createApplication();
$app->get('/', function () { return 'foo'; })
->secure('ROLE_ADMIN')
;
$request = Request::create('/');
$request->headers->set('PHP_AUTH_USER', 'fabien');
$request->headers->set('PHP_AUTH_PW', 'foo');
$response = $app->handle($request);
$this->assertEquals(200, $response->getStatusCode());
}
public function testSecureWithUnauthorizedRoles()
{
$app = $this->createApplication();
$app->get('/', function () { return 'foo'; })
->secure('ROLE_SUPER_ADMIN')
;
$request = Request::create('/');
$request->headers->set('PHP_AUTH_USER', 'fabien');
$request->headers->set('PHP_AUTH_PW', 'foo');
$response = $app->handle($request);
$this->assertEquals(403, $response->getStatusCode());
}
private function createApplication()
{
$app = new Application();
$app['route_class'] = 'Silex\Tests\Route\SecurityRoute';
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'default' => array(
'http' => true,
'users' => array(
'fabien' => array('ROLE_ADMIN', '$2y$15$lzUNsTegNXvZW3qtfucV0erYBcEqWVeyOmjolB7R1uodsAVJ95vvu'),
),
),
),
));
return $app;
}
}

View File

@ -1,285 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Router test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class RouterTest extends \PHPUnit_Framework_TestCase
{
public function testMapRouting()
{
$app = new Application();
$app->match('/foo', function () {
return 'foo';
});
$app->match('/bar', function () {
return 'bar';
});
$app->match('/', function () {
return 'root';
});
$this->checkRouteResponse($app, '/foo', 'foo');
$this->checkRouteResponse($app, '/bar', 'bar');
$this->checkRouteResponse($app, '/', 'root');
}
public function testStatusCode()
{
$app = new Application();
$app->put('/created', function () {
return new Response('', 201);
});
$app->match('/forbidden', function () {
return new Response('', 403);
});
$app->match('/not_found', function () {
return new Response('', 404);
});
$request = Request::create('/created', 'put');
$response = $app->handle($request);
$this->assertEquals(201, $response->getStatusCode());
$request = Request::create('/forbidden');
$response = $app->handle($request);
$this->assertEquals(403, $response->getStatusCode());
$request = Request::create('/not_found');
$response = $app->handle($request);
$this->assertEquals(404, $response->getStatusCode());
}
public function testRedirect()
{
$app = new Application();
$app->match('/redirect', function () {
return new RedirectResponse('/target');
});
$app->match('/redirect2', function () use ($app) {
return $app->redirect('/target2');
});
$request = Request::create('/redirect');
$response = $app->handle($request);
$this->assertTrue($response->isRedirect('/target'));
$request = Request::create('/redirect2');
$response = $app->handle($request);
$this->assertTrue($response->isRedirect('/target2'));
}
/**
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testMissingRoute()
{
$app = new Application();
unset($app['exception_handler']);
$request = Request::create('/baz');
$app->handle($request);
}
public function testMethodRouting()
{
$app = new Application();
$app->match('/foo', function () {
return 'foo';
});
$app->match('/bar', function () {
return 'bar';
})->method('GET|POST');
$app->get('/resource', function () {
return 'get resource';
});
$app->post('/resource', function () {
return 'post resource';
});
$app->put('/resource', function () {
return 'put resource';
});
$app->patch('/resource', function () {
return 'patch resource';
});
$app->delete('/resource', function () {
return 'delete resource';
});
$this->checkRouteResponse($app, '/foo', 'foo');
$this->checkRouteResponse($app, '/bar', 'bar');
$this->checkRouteResponse($app, '/bar', 'bar', 'post');
$this->checkRouteResponse($app, '/resource', 'get resource');
$this->checkRouteResponse($app, '/resource', 'post resource', 'post');
$this->checkRouteResponse($app, '/resource', 'put resource', 'put');
$this->checkRouteResponse($app, '/resource', 'patch resource', 'patch');
$this->checkRouteResponse($app, '/resource', 'delete resource', 'delete');
}
public function testRequestShouldBeStoredRegardlessOfRouting()
{
$app = new Application();
$app->get('/foo', function (Request $request) use ($app) {
return new Response($request->getRequestUri());
});
$app->error(function ($e, Request $request, $code) use ($app) {
return new Response($request->getRequestUri());
});
foreach (array('/foo', '/bar') as $path) {
$request = Request::create($path);
$response = $app->handle($request);
$this->assertContains($path, $response->getContent());
}
}
public function testTrailingSlashBehavior()
{
$app = new Application();
$app->get('/foo/', function () use ($app) {
return new Response('ok');
});
$request = Request::create('/foo');
$response = $app->handle($request);
$this->assertEquals(301, $response->getStatusCode());
$this->assertEquals('/foo/', $response->getTargetUrl());
}
public function testHostSpecification()
{
$route = new \Silex\Route();
$this->assertSame($route, $route->host('{locale}.example.com'));
$this->assertEquals('{locale}.example.com', $route->getHost());
}
public function testRequireHttpRedirect()
{
$app = new Application();
$app->match('/secured', function () {
return 'secured content';
})
->requireHttp();
$request = Request::create('https://example.com/secured');
$response = $app->handle($request);
$this->assertTrue($response->isRedirect('http://example.com/secured'));
}
public function testRequireHttpsRedirect()
{
$app = new Application();
$app->match('/secured', function () {
return 'secured content';
})
->requireHttps();
$request = Request::create('http://example.com/secured');
$response = $app->handle($request);
$this->assertTrue($response->isRedirect('https://example.com/secured'));
}
public function testRequireHttpsRedirectIncludesQueryString()
{
$app = new Application();
$app->match('/secured', function () {
return 'secured content';
})
->requireHttps();
$request = Request::create('http://example.com/secured?query=string');
$response = $app->handle($request);
$this->assertTrue($response->isRedirect('https://example.com/secured?query=string'));
}
public function testConditionOnRoute()
{
$app = new Application();
$app->match('/secured', function () {
return 'secured content';
})
->when('request.isSecure() == true');
$request = Request::create('http://example.com/secured');
$response = $app->handle($request);
$this->assertEquals(404, $response->getStatusCode());
}
public function testClassNameControllerSyntax()
{
$app = new Application();
$app->get('/foo', 'Silex\Tests\MyController::getFoo');
$this->checkRouteResponse($app, '/foo', 'foo');
}
public function testClassNameControllerSyntaxWithStaticMethod()
{
$app = new Application();
$app->get('/bar', 'Silex\Tests\MyController::getBar');
$this->checkRouteResponse($app, '/bar', 'bar');
}
protected function checkRouteResponse(Application $app, $path, $expectedContent, $method = 'get', $message = null)
{
$request = Request::create($path, $method);
$response = $app->handle($request);
$this->assertEquals($expectedContent, $response->getContent(), $message);
}
}
class MyController
{
public function getFoo()
{
return 'foo';
}
public static function getBar()
{
return 'bar';
}
}

View File

@ -1,43 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Silex\Provider\ServiceControllerServiceProvider;
use Symfony\Component\HttpFoundation\Request;
/**
* Router test cases, using the ServiceControllerResolver.
*/
class ServiceControllerResolverRouterTest extends RouterTest
{
public function testServiceNameControllerSyntax()
{
$app = new Application();
$app->register(new ServiceControllerServiceProvider());
$app['service_name'] = function () {
return new MyController();
};
$app->get('/bar', 'service_name:getBar');
$this->checkRouteResponse($app, '/bar', 'bar');
}
protected function checkRouteResponse(Application $app, $path, $expectedContent, $method = 'get', $message = null)
{
$request = Request::create($path, $method);
$response = $app->handle($request);
$this->assertEquals($expectedContent, $response->getContent(), $message);
}
}

View File

@ -1,89 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (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 Silex\Tests;
use Silex\ServiceControllerResolver;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
/**
* Unit tests for ServiceControllerResolver, see ServiceControllerResolverRouterTest for some
* integration tests.
*/
class ServiceControllerResolverTest extends \PHPUnit_Framework_Testcase
{
private $app;
private $mockCallbackResolver;
private $mockResolver;
private $resolver;
public function setup()
{
$this->mockResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface')
->disableOriginalConstructor()
->getMock();
$this->mockCallbackResolver = $this->getMockBuilder('Silex\CallbackResolver')
->disableOriginalConstructor()
->getMock();
$this->app = new Application();
$this->resolver = new ServiceControllerResolver($this->mockResolver, $this->mockCallbackResolver);
}
public function testShouldResolveServiceController()
{
$this->mockCallbackResolver->expects($this->once())
->method('isValid')
->will($this->returnValue(true));
$this->mockCallbackResolver->expects($this->once())
->method('convertCallback')
->with('some_service:methodName')
->will($this->returnValue(array('callback')));
$this->app['some_service'] = function () { return new \stdClass(); };
$req = Request::create('/');
$req->attributes->set('_controller', 'some_service:methodName');
$this->assertEquals(array('callback'), $this->resolver->getController($req));
}
public function testShouldUnresolvedControllerNames()
{
$req = Request::create('/');
$req->attributes->set('_controller', 'some_class::methodName');
$this->mockCallbackResolver->expects($this->once())
->method('isValid')
->with('some_class::methodName')
->will($this->returnValue(false));
$this->mockResolver->expects($this->once())
->method('getController')
->with($req)
->will($this->returnValue(123));
$this->assertEquals(123, $this->resolver->getController($req));
}
public function testShouldDelegateGetArguments()
{
$req = Request::create('/');
$this->mockResolver->expects($this->once())
->method('getArguments')
->with($req)
->will($this->returnValue(123));
$this->assertEquals(123, $this->resolver->getArguments($req, function () {}));
}
}

View File

@ -1,52 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
/**
* Stream test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class StreamTest extends \PHPUnit_Framework_TestCase
{
public function testStreamReturnsStreamingResponse()
{
$app = new Application();
$response = $app->stream();
$this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $response);
$this->assertSame(false, $response->getContent());
}
public function testStreamActuallyStreams()
{
$i = 0;
$stream = function () use (&$i) {
++$i;
};
$app = new Application();
$response = $app->stream($stream);
$this->assertEquals(0, $i);
$request = Request::create('/stream');
$response->prepare($request);
$response->sendContent();
$this->assertEquals(1, $i);
}
}

View File

@ -1,78 +0,0 @@
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Silex\Tests;
use Silex\Application;
use Silex\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
/**
* Functional test cases.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class WebTestCaseTest extends WebTestCase
{
public function createApplication()
{
$app = new Application();
$app->match('/hello', function () {
return 'world';
});
$app->match('/html', function () {
return '<h1>title</h1>';
});
$app->match('/server', function (Request $request) use ($app) {
$user = $request->server->get('PHP_AUTH_USER');
$pass = $request->server->get('PHP_AUTH_PW');
return "<h1>$user:$pass</h1>";
});
return $app;
}
public function testGetHello()
{
$client = $this->createClient();
$client->request('GET', '/hello');
$response = $client->getResponse();
$this->assertTrue($response->isSuccessful());
$this->assertEquals('world', $response->getContent());
}
public function testCrawlerFilter()
{
$client = $this->createClient();
$crawler = $client->request('GET', '/html');
$this->assertEquals('title', $crawler->filter('h1')->text());
}
public function testServerVariables()
{
$user = 'klaus';
$pass = '123456';
$client = $this->createClient(array(
'PHP_AUTH_USER' => $user,
'PHP_AUTH_PW' => $pass,
));
$crawler = $client->request('GET', '/server');
$this->assertEquals("$user:$pass", $crawler->filter('h1')->text());
}
}