Commit 3be840d4 authored by Fabien Potencier's avatar Fabien Potencier

merged branch fabpot/php54 (PR #378)

Commits
-------

63e660fa added more docs
acf60818 added some unit tests
72ac7c5a merged the render and stream method of TwigTrait
a439ae7f added traits for the routes
3266c735 added application traits for PHP 5.4

Discussion
----------

PHP 5.4 support

This is a first attempt to provide useful shortcut methods on the Application class via traits. It also contains a `secure` method for routes.

Here is how you can make use of these features on PHP 5.4:

    use Silex\Application;
    use Silex\Route;

    class MyApp extends Application
    {
        use Application\TwigTrait;
        use Application\SecurityTrait;
        use Application\FormTrait;
        use Application\UrlGeneratorTrait;
        use Application\SwiftmailerTrait;
        use Application\MonologTrait;
        use Application\TranslationTrait;
    }

    class MyRoute extends Route
    {
        use Route\SecurityTrait;
    }

    $app = new MyApp();
    $app['route_factory'] = function () use ($app) {
        return new MyRoute();
    };

This PR depends on #376.

And here is a sample controller using the traits:

    $app->get('/{name}', function(Application $app, Request $request, $name) {

        $app->mail(\Swift_Message::newInstance()
            ->setSubject('[YourSite] Feedback')
            ->setFrom(array('noreply@yoursite.com'))
            ->setTo(array('feedback@yoursite.com'))
            ->setBody($request->get('message')));

        $app->log('Foo Bar');

        return $app->render('hello', [
            'name' => $name,
            'url'  => $app->url('home', ['name' => 'Fabien']),
            'user' => $app->user(),
        ]);
    })
    ->bind('home')
    ->assert('name', '\w+')
    ->secure('ROLE_ADMIN') // <- method defined in Route\SecurityTrait
    ;

As you can see, it makes things much more readable and easier to understand. And of course, it makes Silex very flexible as you can add any method on Application and Route. You just need to define a trait and register it on your custom Application or Route.

---------------------------------------------------------------------------

by fabpot at 2012-06-17T15:32:15Z

Another option to avoid having to override the route factory is to define a parameter for the route class:

    $app['route_class'] = 'MyRoute';

Most of the time this should be sufficient.

---------------------------------------------------------------------------

by fzaninotto at 2012-06-17T16:56:59Z

VERY readable. This change makes Silex even better. Great idea!

---------------------------------------------------------------------------

by mrmark at 2012-06-18T17:42:57Z

This is really awesome!  Really shows off the power of traits.

I was trying out Silex a while ago, and I wanted to try to extend the Silex\Application class, but this sort of broke down at the [Silex\ControllerProviderInterface](https://github.com/fabpot/Silex/blob/master/src/Silex/ControllerProviderInterface.php#L28) because it expects the Silex\Application class.  This means that IDE's and the like wouldn't know about any new methods in my new class.  This is probably more important now with this PR because the IDE wouldn't know about any of the traits used.

---------------------------------------------------------------------------

by stof at 2012-06-18T17:46:55Z

@mrmark There is nothing we can do for it. We cannot document the doc by mentioning your own application class. It would be wrong as the silex application class is valid, and it would be impossible as your own application class is not part of silex.

---------------------------------------------------------------------------

by mrmark at 2012-06-18T18:17:20Z

@stof Sorry, I wasn't suggesting that Silex be modified to accommodate my application class specifically.  I'm not actually sure of the solution here, perhaps change the interface to look like so:

    public function connect($app);

And then depend upon the PHPDoc to tell the IDE what $app really is?  In the end, it would be nice if we knew what $app really was so we would know what methods and the like are available.

---------------------------------------------------------------------------

by stof at 2012-06-18T18:19:20Z

@mrmark the issue is the same: the phpdoc is still in the Silex code. And removing typehints just because inheritance is allowed is wrong IMO

---------------------------------------------------------------------------

by fabpot at 2012-06-19T07:51:38Z

I've just added a bunch of unit tests for the new traits. Any other thoughts before I merge?

---------------------------------------------------------------------------

by GromNaN at 2012-06-19T08:05:22Z

Trait tests should be skipped for PHP < 5.4

---------------------------------------------------------------------------

by fabpot at 2012-06-19T08:07:38Z

@GromNaN That's already the case.

---------------------------------------------------------------------------

by igorw at 2012-06-19T11:17:26Z

👍 Ship it!
parents 199b6ad4 63e660fa
......@@ -15,6 +15,8 @@ Changelog
// or even better
$controllers = $app['controllers_factory'];
* **2012-06-17**: added application traits for PHP 5.4
* **2012-06-16**: renamed ``request.default_locale`` to ``locale``
* **2012-06-16**: Removed the ``translator.loader`` service. See documentation
......
......@@ -143,5 +143,16 @@ form by adding constraints on the fields::
))
->getForm();
Traits
------
``Silex\Application\FormTrait`` adds the following shortcuts:
* **form**: Creates a FormBuilder instance.
.. code-block:: php
$app->form('form', $data);
For more information, consult the `Symfony2 Forms documentation
<http://symfony.com/doc/2.1/book/forms.html>`_.
......@@ -72,5 +72,16 @@ add log entries for any logging level through ``addDebug()``, ``addInfo()``,
return new Response('', 201);
});
Traits
------
``Silex\Application\MonologTrait`` adds the following shortcuts:
* **log**: Logs a message.
.. code-block:: php
$app->log(sprintf("User '%s' registered.", $username));
For more information, check out the `Monolog documentation
<https://github.com/Seldaek/monolog>`_.
......@@ -466,3 +466,28 @@ sample users::
If you are using the Doctrine ORM, the Symfony bridge for Doctrine
provides a user provider class that is able to load users from your
entities.
Traits
------
``Silex\Application\SecurityTrait`` adds the following shortcuts:
* **user**: Returns the current user.
* **encodePassword**: Encode a given password.
.. code-block:: php
$user = $app->user();
$encoded = $app->encodePassword($user, 'foo');
``Silex\Route\SecurityTrait`` adds the following methods to the controllers:
* **secure**: Secures a controller for the given roles.
.. code-block:: php
$app->get('/', function () {
// do something but only for admins
})->secure('ROLE_ADMIN');
......@@ -86,5 +86,20 @@ The Swiftmailer provider provides a ``mailer`` service::
return new Response('Thank you for your feedback!', 201);
});
Traits
------
``Silex\Application\SwiftmailerTrait`` adds the following shortcuts:
* **mail**: Sends an email.
.. code-block:: php
$app->mail(\Swift_Message::newInstance()
->setSubject('[YourSite] Feedback')
->setFrom(array('noreply@yoursite.com'))
->setTo(array('feedback@yoursite.com'))
->setBody($request->get('message')));
For more information, check out the `Swift Mailer documentation
<http://swiftmailer.org>`_.
......@@ -95,6 +95,22 @@ The above example will result in following routes:
* ``/it/hello/igor`` will return ``Hello igor`` (because of the fallback).
Traits
------
``Silex\Application\TranslationTrait`` adds the following shortcuts:
* **trans**: Translates the given message.
* **transChoice**: Translates the given choice message by choosing a
translation according to a number.
.. code-block:: php
$app->trans('Hello World');
$app->transChoice('Hello World');
Recipes
-------
......
......@@ -120,6 +120,30 @@ from a template:
{# or if you are also using UrlGeneratorServiceProvider with the SymfonyBridgesServiceProvider #}
{{ render(path('sidebar')) }}
Traits
------
``Silex\Application\TwigTrait`` adds the following shortcuts:
* **render**: Renders a view with the given parameters and returns a Response
object.
.. code-block:: php
return $app->render('index.html', ['name': 'Fabien']);
$response = new Response();
$response->setTtl(10);
return $app->render('index.html', ['name': 'Fabien'], $response);
.. code-block:: php
// stream a view
use Symfony\Component\HttpFoundation\StreamedResponse;
return $app->render('index.html', ['name': 'Fabien'], new StreamedResponse());
Customization
-------------
......
......@@ -61,3 +61,17 @@ Moreover, if you use Twig, you will have access to the ``path()`` and
{{ path('homepage') }}
{{ url('homepage') }} {# generates the absolute url http://example.org/ #}
Traits
------
``Silex\Application\UrlGeneratorTrait`` adds the following shortcuts:
* **path**: Generates a path.
* **url**: Generates an absolute URL.
.. code-block:: php
$app->path('homepage');
$app->url('homepage');
......@@ -738,6 +738,47 @@ after every chunk::
fclose($fh);
};
Traits
------
Silex comes with PHP traits that define shortcut methods.
.. caution::
You need to use PHP 5.4 or later to benefit from this feature.
Almost all built-in service providers have some corresponding PHP traits. To
use them, define your own Application class and include the traits you want::
use Silex\Application;
class MyApplication extends Application
{
use Application\TwigTrait;
use Application\SecurityTrait;
use Application\FormTrait;
use Application\UrlGeneratorTrait;
use Application\SwiftmailerTrait;
use Application\MonologTrait;
use Application\TranslationTrait;
}
You can also define your own Route class and use some traits::
use Silex\Route;
class MyRoute extends Route
{
use Route\SecurityTrait;
}
To use your newly defined route, override the ``$app['route_class']``
setting::
$app['route_class'] = 'MyRoute';
Read each provider chapter to learn more about the added methods.
Security
--------
......
<?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\Application;
use Symfony\Component\Form\FormBuilder;
/**
* Form trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait FormTrait
{
/**
* Creates and returns a form builder instance
*
* @param mixed $data The initial data for the form
* @param array $options Options for the form
*
* @return FormBuilder
*/
public function form($data = null, array $options = array())
{
return $this['form.factory']->createBuilder('form', $data, $options);
}
}
<?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\Application;
use Monolog\Logger;
/**
* Monolog trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait MonologTrait
{
/**
* Adds a log record.
*
* @param string $message The log message
* @param array $context The log context
* @param integer $level The logging level
*
* @return Boolean Whether the record has been processed
*/
public function log($message, array $context = array(), $level = Logger::INFO)
{
return $this['monolog']->addRecord($level, $message, $context);
}
}
<?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\Application;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Security trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait SecurityTrait
{
/**
* Gets a user from the Security Context.
*
* @return mixed
*
* @see TokenInterface::getUser()
*/
public function user()
{
if (null === $token = $this['security']->getToken()) {
return null;
}
if (!is_object($user = $token->getUser())) {
return null;
}
return $user;
}
/**
* Encodes the raw password.
*
* @param UserInterface $user A UserInterface instance
* @param string $raw The password to encode
*
* @return string The encoded password
*
* @throws \RuntimeException when no password encoder could be found for the user
*/
public function encodePassword(UserInterface $user, $password)
{
return $this['security.encoder_factory']->getEncoder($user)->encodePassword($password, $user->getSalt());
}
}
<?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\Application;
/**
* Swiftmailer trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait SwiftmailerTrait
{
/**
* Sends an email.
*
* @param \Swift_Message $message A \Swift_Message intance
*/
public function mail(\Swift_Message $message)
{
return $this['mailer']->send($message);
}
}
<?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\Application;
/**
* Translation trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait TranslationTrait
{
/**
* Translates the given message.
*
* @param string $id The message id
* @param array $parameters An array of parameters for the message
* @param string $domain The domain for the message
* @param string $locale The locale
*
* @return string The translated string
*/
public function trans($id, array $parameters = array(), $domain = 'messages', $locale = null)
{
return $this['translator']->trans($id, $parameters, $domain, $locale);
}
/**
* Translates the given choice message by choosing a translation according to a number.
*
* @param string $id The message id
* @param integer $number The number to use to find the indice of the message
* @param array $parameters An array of parameters for the message
* @param string $domain The domain for the message
* @param string $locale The locale
*
* @return string The translated string
*/
public function transChoice($id, $number, array $parameters = array(), $domain = 'messages', $locale = null)
{
return $this['translator']->transChoice($id, $number, $parameters, $domain, $locale);
}
}
<?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\Application;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Twig trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait TwigTrait
{
/**
* Renders a view and returns a Response.
*
* To stream a view, pass an instance of StreamedResponse as a third argument.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
* @param Response $response A Response instance
*
* @return Response A Response instance
*/
public function render($view, array $parameters = array(), Response $response = null)
{
if (null === $response) {
$response = new Response();
}
$twig = $this['twig'];
if ($response instanceof StreamedResponse) {
$response->setCallback(function () use ($twig, $view, $parameters) {
$twig->display($view, $parameters);
});
} else {
$response->setContent($twig->render($view, $parameters));
}
return $response;
}
/**
* Renders a view.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
*
* @return Response A Response instance
*/
public function renderView($view, array $parameters = array())
{
return $this['twig']->render($view, $parameters);
}
}
<?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\Application;
/**
* UrlGenerator trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait UrlGeneratorTrait
{
/**
* Generates a path from the given parameters.
*
* @param string $route The name of the route
* @param mixed $parameters An array of parameters
*
* @return string The generated path
*/
public function path($route, $parameters = array())
{
return $this['url_generator']->generate($route, $parameters, false);
}
/**
* Generates an absolute URL from the given parameters.
*
* @param string $route The name of the route
* @param mixed $parameters An array of parameters
*
* @return string The generated URL
*/
public function url($route, $parameters = array())
{
return $this['url_generator']->generate($route, $parameters, true);
}
}
<?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\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* Security trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait SecurityTrait
{
public function secure($roles)
{
$this->before(function ($request, $app) use ($roles) {
if (!$app['security']->isGranted($roles)) {
throw new AccessDeniedException();
}
});
}
}
<?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;
}
<?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;
use Silex\Provider\FormServiceProvider;
/**
* FormTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FormTraitTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
if (version_compare(phpversion(), '5.4.0', '<')) {
$this->markTestSkipped('PHP 5.4 is required for this test');
}
if (!is_dir(__DIR__.'/../../../../vendor/symfony/form')) {
$this->markTestSkipped('Form dependency was not installed.');
}
}
public function testForm()
{
$this->assertInstanceOf('Symfony\Component\Form\FormBuilder', $this->createApplication()->form());
}
public function createApplication()
{
$app = new FormApplication();
$app->register(new FormServiceProvider());
return $app;
}
}
<?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;
}
<?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;
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 setUp()
{
if (version_compare(phpversion(), '5.4.0', '<')) {
$this->markTestSkipped('PHP 5.4 is required for this test');
}
if (!is_dir(__DIR__.'/../../../../vendor/monolog/monolog/src')) {
$this->markTestSkipped('Monolog dependency was not installed.');
}
}
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' => $app->share(function () use ($app) {
return new TestHandler($app['monolog.level']);
}),
));
return $app;
}
}
<?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;
}
<?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;
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 setUp()
{
if (version_compare(phpversion(), '5.4.0', '<')) {
$this->markTestSkipped('PHP 5.4 is required for this test');
}
if (!is_dir(__DIR__.'/../../../../vendor/symfony/security')) {
$this->markTestSkipped('Security dependency was not installed.');
}
}
public function testUser()
{
$request = Request::create('/');
$app = $this->createApplication();
$app->get('/', function () { return 'foo'; });
$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 testEncodePassword()
{
$app = $this->createApplication();
$user = new User('foo', 'bar');
$this->assertEquals('5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==', $app->encodePassword($user, 'foo'));
}
public function createApplication()
{
$app = new SecurityApplication();
$app->register(new SecurityServiceProvider(), array(
'security.firewalls' => array(
'default' => array(
'http' => true,
'users' => array(
'fabien' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
),
),
),
));
return $app;
}
}
<?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;
}
<?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;
use Silex\Provider\SwiftmailerServiceProvider;
/**
* SwiftmailerTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SwiftmailerTraitTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
if (version_compare(phpversion(), '5.4.0', '<')) {
$this->markTestSkipped('PHP 5.4 is required for this test');
}
if (!is_dir(__DIR__.'/../../../../vendor/swiftmailer/swiftmailer')) {
$this->markTestSkipped('Swiftmailer dependency was not installed.');
}
}
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;
}
}
<?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;
}
<?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;
use Silex\Provider\TranslationServiceProvider;
/**
* TranslationTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TranslationTraitTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
if (version_compare(phpversion(), '5.4.0', '<')) {
$this->markTestSkipped('PHP 5.4 is required for this test');
}
if (!is_dir(__DIR__.'/../../../../vendor/symfony/translation')) {
$this->markTestSkipped('Translation dependency was not installed.');
}
}
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;
}
}
<?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;
}
<?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;
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 setUp()
{
if (version_compare(phpversion(), '5.4.0', '<')) {
$this->markTestSkipped('PHP 5.4 is required for this test');
}
if (!is_dir(__DIR__.'/../../../../vendor/twig/twig')) {
$this->markTestSkipped('Twig dependency was not installed.');
}
}
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;
}
}
<?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;
}
<?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;
use Silex\Provider\UrlGeneratorServiceProvider;
/**
* UrlGeneratorTrait test cases.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class UrlGeneratorTraitTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
if (version_compare(phpversion(), '5.4.0', '<')) {
$this->markTestSkipped('PHP 5.4 is required for this test');
}
}
public function testUrl()
{
$app = $this->createApplication();
$app['url_generator'] = $translator = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->disableOriginalConstructor()->getMock();
$translator->expects($this->once())->method('generate')->with('foo', array(), true);
$app->url('foo');
}
public function testPath()
{
$app = $this->createApplication();
$app['url_generator'] = $translator = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->disableOriginalConstructor()->getMock();
$translator->expects($this->once())->method('generate')->with('foo', array(), false);
$app->path('foo');
}
public function createApplication()
{
$app = new UrlGeneratorApplication();
$app->register(new UrlGeneratorServiceProvider());
return $app;
}
}
<?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;
}
<?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 setUp()
{
if (version_compare(phpversion(), '5.4.0', '<')) {
$this->markTestSkipped('PHP 5.4 is required for this test');
}
if (!is_dir(__DIR__.'/../../../../vendor/symfony/security')) {
$this->markTestSkipped('Security dependency was not installed.');
}
}
public function testSecure()
{
$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', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
),
),
),
));
$app->get('/', function () { return 'foo'; })
->secure('ROLE_ADMIN')
;
$request = Request::create('/');
$response = $app->handle($request);
$this->assertEquals(401, $response->getStatusCode());
$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());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment