Template refactoring to use twig

This commit is contained in:
Igor Scheller 2018-09-02 02:09:56 +02:00
parent ac48332166
commit 9e217d87c0
20 changed files with 496 additions and 227 deletions

View File

@ -40,69 +40,6 @@ function header_render_hints()
return $hints_renderer->render();
}
/**
* Renders the header toolbar containing search, login/logout, user and settings links.
*
* @return string
*/
function header_toolbar()
{
global $page, $privileges, $user;
$toolbar_items = [];
if (isset($user)) {
$toolbar_items[] = toolbar_item_link(
page_link_to('shifts', ['action' => 'next']),
'time',
User_shift_state_render($user)
);
}
if (!isset($user) && in_array('register', $privileges) && config('registration_enabled')) {
$toolbar_items[] = toolbar_item_link(
page_link_to('register'),
'plus',
register_title(),
$page == 'register'
);
}
if (in_array('login', $privileges)) {
$toolbar_items[] = toolbar_item_link(
page_link_to('login'),
'log-in',
login_title(),
$page == 'login'
);
}
if (isset($user) && in_array('user_messages', $privileges)) {
$toolbar_items[] = toolbar_item_link(
page_link_to('user_messages'),
'envelope',
user_unread_messages()
);
}
$toolbar_items[] = header_render_hints();
if (in_array('user_myshifts', $privileges)) {
$toolbar_items[] = toolbar_item_link(
page_link_to('users', ['action' => 'view']),
' icon-icon_angel',
$user['Nick'],
$page == 'users'
);
}
$user_submenu = make_user_submenu();
if (count($user_submenu) > 0) {
$toolbar_items[] = toolbar_dropdown('', '', $user_submenu);
}
return toolbar($toolbar_items, true);
}
/**
* @return array
*/
@ -120,7 +57,7 @@ function make_user_submenu()
$user_submenu[] = toolbar_item_link(
page_link_to('user_settings'),
'list-alt',
settings_title(),
__('Settings'),
$page == 'user_settings'
);
}
@ -129,7 +66,7 @@ function make_user_submenu()
$user_submenu[] = toolbar_item_link(
page_link_to('logout'),
'log-out',
logout_title(),
__('Logout'),
$page == 'logout'
);
}
@ -146,11 +83,11 @@ function make_navigation()
$menu = [];
$pages = [
'news' => news_title(),
'user_meetings' => meetings_title(),
'user_shifts' => shifts_title(),
'angeltypes' => angeltypes_title(),
'user_questions' => questions_title()
'news' => __('News'),
'user_meetings' => __('Meetings'),
'user_shifts' => __('Shifts'),
'angeltypes' => __('Angeltypes'),
'user_questions' => __('Ask the Heaven'),
];
foreach ($pages as $menu_page => $title) {
@ -163,18 +100,18 @@ function make_navigation()
$admin_menu = [];
$admin_pages = [
'admin_arrive' => admin_arrive_title(),
'admin_active' => admin_active_title(),
'admin_user' => admin_user_title(),
'admin_free' => admin_free_title(),
'admin_questions' => admin_questions_title(),
'shifttypes' => shifttypes_title(),
'admin_shifts' => admin_shifts_title(),
'admin_rooms' => admin_rooms_title(),
'admin_groups' => admin_groups_title(),
'admin_import' => admin_import_title(),
'admin_log' => admin_log_title(),
'admin_event_config' => event_config_title()
'admin_arrive' => __('Arrived angels'),
'admin_active' => __('Active angels'),
'admin_user' => __('All Angels'),
'admin_free' => __('Free angels'),
'admin_questions' => __('Answer questions'),
'shifttypes' => __('Shifttypes'),
'admin_shifts' => __('Create shifts'),
'admin_rooms' => __('Rooms'),
'admin_groups' => __('Grouprights'),
'admin_import' => __('Frab import'),
'admin_log' => __('Log'),
'admin_event_config' => __('Event config'),
];
foreach ($admin_pages as $menu_page => $title) {
@ -192,7 +129,7 @@ function make_navigation()
$menu[] = toolbar_dropdown('', __('Admin'), $admin_menu);
}
return toolbar($menu);
return '<ul class="nav navbar-nav">' . join("\n", $menu) . '</ul>';
}
/**
@ -250,11 +187,3 @@ function make_language_select()
}
return $items;
}
/**
* @return string
*/
function make_menu()
{
return make_navigation();
}

View File

@ -147,18 +147,6 @@ function heading($content, $number = 1)
return '<h' . $number . '>' . $content . '</h' . $number . '>';
}
/**
* Render a toolbar.
*
* @param array $items
* @param bool $right
* @return string
*/
function toolbar($items = [], $right = false)
{
return '<ul class="nav navbar-nav' . ($right ? ' navbar-right' : '') . '">' . join("\n", $items) . '</ul>';
}
/**
* @param string[] $items
* @return string

View File

@ -60,57 +60,6 @@ function EventConfig_countdown_page($event_config)
return join('', $elements);
}
/**
* Converts event name and start+end date into a line of text.
*
* @param array $event_config
* @return string
*/
function EventConfig_info($event_config)
{
if (empty($event_config)) {
return '';
}
// Event name, start+end date are set
if (
!is_null($event_config['event_name'])
&& !is_null($event_config['event_start_date'])
&& !is_null($event_config['event_end_date'])
) {
return sprintf(
__('%s, from %s to %s'),
$event_config['event_name'],
date(__('Y-m-d'), $event_config['event_start_date']),
date(__('Y-m-d'), $event_config['event_end_date'])
);
}
// Event name, start date are set
if (!is_null($event_config['event_name']) && !is_null($event_config['event_start_date'])) {
return sprintf(
__('%s, starting %s'), $event_config['event_name'],
date(__('Y-m-d'), $event_config['event_start_date'])
);
}
// Event start+end date are set
if (!is_null($event_config['event_start_date']) && !is_null($event_config['event_end_date'])) {
return sprintf(
__('Event from %s to %s'),
date(__('Y-m-d'), $event_config['event_start_date']),
date(__('Y-m-d'), $event_config['event_end_date'])
);
}
// Only event name is set
if (!is_null($event_config['event_name'])) {
return sprintf($event_config['event_name']);
}
return '';
}
/**
* Render edit page for event config.
*

View File

@ -3,12 +3,15 @@
namespace Engelsystem\Http;
use Engelsystem\Container\ServiceProvider;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
class RequestServiceProvider extends ServiceProvider
{
public function register()
{
$request = $this->app->call([Request::class, 'createFromGlobals']);
$this->app->instance(Request::class, $request);
$this->app->instance(SymfonyRequest::class, $request);
$this->app->instance('request', $request);
}
}

View File

@ -3,12 +3,15 @@
namespace Engelsystem\Http;
use Engelsystem\Container\ServiceProvider;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class ResponseServiceProvider extends ServiceProvider
{
public function register()
{
$response = $this->app->make(Response::class);
$this->app->instance(Response::class, $response);
$this->app->instance(SymfonyResponse::class, $response);
$this->app->instance('response', $response);
}
}

View File

@ -60,6 +60,7 @@ class LegacyMiddleware implements MiddlewareInterface
): ResponseInterface {
global $user;
global $privileges;
global $page;
/** @var Request $appRequest */
$appRequest = $this->container->get('request');
@ -271,27 +272,13 @@ class LegacyMiddleware implements MiddlewareInterface
*/
protected function renderPage($page, $title, $content)
{
global $user;
$event_config = EventConfig();
$parameters = [
'key' => (isset($user) ? $user['api_key'] : ''),
];
if ($page == 'user_meetings') {
$parameters['meetings'] = 1;
}
if (!empty($page) && is_int($page)) {
return response($content, (int)$page);
}
return response(view('layouts/app', [
'title' => $title,
'atom_feed' => ($page == 'news' || $page == 'user_meetings') ? $parameters : [],
'menu' => make_menu(),
'content' => msg() . $content,
'header_toolbar' => header_toolbar(),
'event_info' => EventConfig_info($event_config) . ' <br />'
'title' => $title,
'content' => msg() . $content,
]), 200);
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace Engelsystem\Renderer\Twig\Extensions;
use Twig_Extension as TwigExtension;
use Twig_Function as TwigFunction;
class Authentication extends TwigExtension
{
/**
* @return TwigFunction[]
*/
public function getFunctions()
{
return [
new TwigFunction('is_user', [$this, 'isAuthenticated']),
new TwigFunction('is_guest', [$this, 'isGuest']),
new TwigFunction('has_permission_to', [$this, 'checkAuth']),
];
}
public function isAuthenticated()
{
global $user;
return !empty($user);
}
public function isGuest()
{
return !$this->isAuthenticated();
}
public function checkAuth($privilege)
{
global $privileges;
return in_array($privilege, $privileges);
}
}

View File

@ -2,6 +2,7 @@
namespace Engelsystem\Renderer\Twig\Extensions;
use Carbon\Carbon;
use Twig_Extension as TwigExtension;
use Twig_Extension_GlobalsInterface as GlobalsInterface;
@ -16,8 +17,45 @@ class Globals extends TwigExtension implements GlobalsInterface
{
global $user;
$eventConfig = $this->getEventConfig();
if (empty($eventConfig)) {
$eventConfig = [];
}
return [
'user' => isset($user) ? $user : [],
'user' => isset($user) ? $user : [],
'event_config' => $this->filterEventConfig($eventConfig),
];
}
/**
* @return array
* @codeCoverageIgnore
*/
protected function getEventConfig()
{
return EventConfig();
}
/**
* @param $eventConfig
* @return mixed
*/
protected function filterEventConfig($eventConfig)
{
array_walk($eventConfig, function (&$value, $key) {
if (is_null($value) || !in_array($key, [
'buildup_start_date',
'event_start_date',
'event_end_date',
'teardown_end_date',
])) {
return;
}
$value = Carbon::createFromTimestamp($value);
});
return $eventConfig;
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace Engelsystem\Renderer\Twig\Extensions;
use Engelsystem\Http\Request;
use Twig_Extension as TwigExtension;
use Twig_Function as TwigFunction;
class Legacy extends TwigExtension
{
/** @var Request */
protected $request;
/**
* @param Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* @return TwigFunction[]
*/
public function getFunctions()
{
$isSafeHtml = ['is_safe' => ['html']];
return [
new TwigFunction('menu', 'make_navigation', $isSafeHtml),
new TwigFunction('menuUserShiftState', 'User_shift_state_render', $isSafeHtml),
new TwigFunction('menuUserMessages', 'user_unread_messages', $isSafeHtml),
new TwigFunction('menuUserHints', 'header_render_hints', $isSafeHtml),
new TwigFunction('menuUserSubmenu', 'make_user_submenu', $isSafeHtml),
new TwigFunction('page', [$this, 'getPage']),
];
}
/**
* @return string
*/
public function getPage()
{
if ($this->request->has('p')) {
return $this->request->get('p');
}
return $this->request->path();
}
}

View File

@ -2,24 +2,30 @@
namespace Engelsystem\Renderer;
use Engelsystem\Config\Config as EngelsystemConfig;
use Engelsystem\Container\ServiceProvider;
use Engelsystem\Renderer\Twig\Extensions\Authentication;
use Engelsystem\Renderer\Twig\Extensions\Config;
use Engelsystem\Renderer\Twig\Extensions\Globals;
use Engelsystem\Renderer\Twig\Extensions\Legacy;
use Engelsystem\Renderer\Twig\Extensions\Session;
use Engelsystem\Renderer\Twig\Extensions\Translation;
use Engelsystem\Renderer\Twig\Extensions\Url;
use Twig_Environment as Twig;
use Twig_Extension_Core as TwigCore;
use Twig_LoaderInterface as TwigLoaderInterface;
class TwigServiceProvider extends ServiceProvider
{
/** @var array */
protected $extensions = [
'config' => Config::class,
'globals' => Globals::class,
'session' => Session::class,
'url' => Url::class,
'translation' => Translation::class,
'authentication' => Authentication::class,
'config' => Config::class,
'globals' => Globals::class,
'session' => Session::class,
'legacy' => Legacy::class,
'translation' => Translation::class,
'url' => Url::class,
];
public function register()
@ -44,6 +50,8 @@ class TwigServiceProvider extends ServiceProvider
protected function registerTwigEngine()
{
$viewsPath = $this->app->get('path.views');
/** @var EngelsystemConfig $config */
$config = $this->app->get('config');
$twigLoader = $this->app->make(TwigLoader::class, ['paths' => $viewsPath]);
$this->app->instance(TwigLoader::class, $twigLoader);
@ -54,6 +62,10 @@ class TwigServiceProvider extends ServiceProvider
$this->app->instance(Twig::class, $twig);
$this->app->instance('twig.environment', $twig);
/** @var TwigCore $twigCore */
$twigCore = $twig->getExtension(TwigCore::class);
$twigCore->setTimezone($config->get('timezone'));
$twigEngine = $this->app->make(TwigEngine::class);
$this->app->instance('renderer.twigEngine', $twigEngine);
$this->app->tag('renderer.twigEngine', ['renderer.engine']);

View File

@ -11,59 +11,29 @@
<link rel="stylesheet" type="text/css" href="vendor/bootstrap-datepicker-1.7.1/css/bootstrap-datepicker3.min.css"/>
<script type="text/javascript" src="vendor/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="vendor/jquery-ui.min.js"></script>
{% if atom_feed -%}
<link href="{{ url('atom', atom_feed) }}" type="application/atom+xml" rel="alternate" title="Atom Feed">
{% if page() in ['news', 'user-meetings', '/'] and is_user() -%}
{% set parameters = {'key': user.api_key} -%}
{% if page() == 'user-meetings' -%}
{% set parameters = parameters|merge({'meetings': 1}) -%}
{% endif %}
<link href="{{ url('atom', parameters) }}" type="application/atom+xml" rel="alternate" title="Atom Feed">
{% endif %}
{% endblock %}
</head>
<body>
{% block body %}
<div class="navbar navbar-default navbar-fixed-top">
{% block header %}
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{{ url('/') }}">
<span class="icon-icon_angel"></span> <strong class="visible-lg-inline">ENGELSYSTEM</strong>
</a>
</div>
{% block navbar %}
<div class="collapse navbar-collapse" id="navbar-collapse-1">
{{ menu|raw }}
{{ header_toolbar|raw }}
</div>
{% endblock %}
</div>
{% endblock %}
</div>
{% block header %}
{% include "layouts/parts/navbar.twig" %}
{% endblock %}
<div class="container-fluid">
<div class="row">{% block content %}{{ content|raw }}{% endblock %}</div>
<div class="row">
{% block content %}{{ content|raw }}{% endblock %}
</div>
<div class="row" id="footer">
{% block footer %}
<div class="col-md-12">
<hr/>
<div class="text-center footer" style="margin-bottom: 10px;">
{% block eventinfo %}
{{ event_info|raw }}
{% endblock %}
<a href="{{ config('faq_url') }}">FAQ</a>
· <a href="{{ config('contact_email') }}">
<span class="glyphicon glyphicon-envelope"></span>Contact
</a>
· <a href="https://github.com/engelsystem/engelsystem/issues">Bugs / Features</a>
· <a href="https://github.com/engelsystem/engelsystem/">Development Platform</a>
· <a href="{{ url('credits') }}">Credits</a>
</div>
</div>
{% include "layouts/parts/footer.twig" %}
{% endblock %}
</div>
</div>

View File

@ -0,0 +1,36 @@
<div class="col-md-12">
<hr/>
<div class="text-center footer" style="margin-bottom: 10px;">
{% block eventinfo %}
{% if event_config.event_name %}
{% if event_config.event_start_date and event_config.event_end_date %}
{{ __('%s, from %s to %s', [
event_config.event_name,
date(event_config.event_start_date).format(__('Y-m-d')),
date(event_config.event_end_date).format(__('Y-m-d'))
]) }}
{% elseif event_config.event_start_date %}
{{ __('%s, starting %s', [
event_config.event_name,
date(event_config.event_start_date).format(__('Y-m-d'))
]) }}
{% else %}
{{ event_config.event_name }}
{% endif %} <br>
{% elseif event_config.event_start_date and event_config.event_end_date %}
{{ __('Event from %s to %s', [
date(event_config.event_start_date).format(__('Y-m-d')),
date(event_config.event_end_date).format(__('Y-m-d'))
]) }} <br>
{% endif %}
{% endblock %}
<a href="{{ config('faq_url') }}">{{ __('FAQ') }}</a>
· <a href="{{ config('contact_email') }}">
<span class="glyphicon glyphicon-envelope"></span> {{ __('Contact') }}
</a>
· <a href="https://github.com/engelsystem/engelsystem/issues">{{ __('Bugs / Features') }}</a>
· <a href="https://github.com/engelsystem/engelsystem/">{{ __('Development Platform') }}</a>
· <a href="{{ url('credits') }}">{{ __('Credits') }}</a>
</div>
</div>

View File

@ -0,0 +1,74 @@
{% import _self as elements %}
{% macro toolbar_item(label, link, active_page, icon) %}
<li{% if page() == active_page %} class="active"{% endif %}>
<a href="{{ link }}">
{% if icon %}<span class="glyphicon {{ icon }}"></span>{% endif %}
{{ label|raw }}
</a>
</li>
{% endmacro %}
<div class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
{% block navbar %}
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{{ url('/') }}">
<span class="icon-icon_angel"></span> <strong class="visible-lg-inline">ENGELSYSTEM</strong>
</a>
</div>
{% block menu %}
<div class="collapse navbar-collapse" id="navbar-collapse-1">
{% block menu_items %}
{{ menu() }}
{% endblock %}
{% block menu_toolbar %}
<ul class="nav navbar-nav navbar-right">
{% if is_user() %}
{{ elements.toolbar_item(menuUserShiftState(user), url('shifts', {'action': 'next'}), '', 'glyphicon-time') }}
{% elseif has_permission_to('register') and config('registration_enabled') %}
{{ elements.toolbar_item(__('Register'), url('register'), 'register', 'glyphicon-plus') }}
{% endif %}
{% if has_permission_to('login') %}
{{ elements.toolbar_item(__('Login'), url('login'), 'login', 'glyphicon-log-in') }}
{% endif %}
{% if is_user() and has_permission_to('user_messages') %}
{{ elements.toolbar_item(menuUserMessages(), url('user-messages'), 'user-messages', 'glyphicon-envelope') }}
{% endif %}
{{ menuUserHints() }}
{% if has_permission_to('user_myshifts') %}
{{ elements.toolbar_item(user.Nick, url('users', {'action': 'view'}), 'users', 'icon-icon_angel') }}
{% endif %}
{% if has_permission_to('user_settings') or has_permission_to('logout') %}
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
{{ menuUserSubmenu()|join(" ")|raw }}
</ul>
</li>
{% endif %}
</ul>
{% endblock %}
</div>
{% endblock %}
{% endblock %}
</div>
</div>

View File

@ -6,6 +6,7 @@ use Engelsystem\Http\Request;
use Engelsystem\Http\RequestServiceProvider;
use Engelsystem\Test\Unit\ServiceProviderTest;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
class RequestServiceProviderTest extends ServiceProviderTest
{
@ -21,7 +22,13 @@ class RequestServiceProviderTest extends ServiceProviderTest
$app = $this->getApp(['call', 'instance']);
$this->setExpects($app, 'call', [[Request::class, 'createFromGlobals']], $request);
$this->setExpects($app, 'instance', ['request', $request]);
$app->expects($this->exactly(3))
->method('instance')
->withConsecutive(
[Request::class, $request],
[SymfonyRequest::class, $request],
['request', $request]
);
$serviceProvider = new RequestServiceProvider($app);
$serviceProvider->register();

View File

@ -6,6 +6,7 @@ use Engelsystem\Http\Response;
use Engelsystem\Http\ResponseServiceProvider;
use Engelsystem\Test\Unit\ServiceProviderTest;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class ResponseServiceProviderTest extends ServiceProviderTest
{
@ -21,7 +22,13 @@ class ResponseServiceProviderTest extends ServiceProviderTest
$app = $this->getApp();
$this->setExpects($app, 'make', [Response::class], $response);
$this->setExpects($app, 'instance', ['response', $response]);
$app->expects($this->exactly(3))
->method('instance')
->withConsecutive(
[Response::class, $response],
[SymfonyResponse::class, $response],
['response', $response]
);
$serviceProvider = new ResponseServiceProvider($app);
$serviceProvider->register();

View File

@ -0,0 +1,56 @@
<?php
namespace Engelsystem\Test\Unit\Renderer\Twig\Extensions;
use Engelsystem\Renderer\Twig\Extensions\Authentication;
class AuthenticationTest extends ExtensionTest
{
/**
* @covers \Engelsystem\Renderer\Twig\Extensions\Authentication::getFunctions
*/
public function testGetFunctions()
{
$extension = new Authentication();
$functions = $extension->getFunctions();
$this->assertExtensionExists('is_user', [$extension, 'isAuthenticated'], $functions);
$this->assertExtensionExists('is_guest', [$extension, 'isGuest'], $functions);
$this->assertExtensionExists('has_permission_to', [$extension, 'checkAuth'], $functions);
}
/**
* @covers \Engelsystem\Renderer\Twig\Extensions\Authentication::isAuthenticated
* @covers \Engelsystem\Renderer\Twig\Extensions\Authentication::isGuest
*/
public function testIsAuthenticated()
{
global $user;
$user = [];
$extension = new Authentication();
$this->assertFalse($extension->isAuthenticated());
$this->assertTrue($extension->isGuest());
$user = ['lorem' => 'ipsum'];
$this->assertTrue($extension->isAuthenticated());
$this->assertFalse($extension->isGuest());
}
/**
* @covers \Engelsystem\Renderer\Twig\Extensions\Authentication::checkAuth
*/
public function testCheckAuth()
{
global $privileges;
$privileges = [];
$extension = new Authentication();
$this->assertFalse($extension->checkAuth('foo.bar'));
$privileges = ['foo.bar'];
$this->assertTrue($extension->checkAuth('foo.bar'));
}
}

View File

@ -2,8 +2,10 @@
namespace Engelsystem\Test\Unit\Renderer\Twig\Extensions;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Twig_Function as TwigFunction;
use Twig_Node as TwigNode;
abstract class ExtensionTest extends TestCase
{
@ -35,7 +37,7 @@ abstract class ExtensionTest extends TestCase
* @param callable $callback
* @param TwigFunction[] $functions
*/
protected function assertExtensionExists($name, $callback, $functions)
protected function assertExtensionExists($name, $callback, $functions, $options = [])
{
foreach ($functions as $function) {
if ($function->getName() != $name) {
@ -43,6 +45,14 @@ abstract class ExtensionTest extends TestCase
}
$this->assertEquals($callback, $function->getCallable());
if (isset($options['is_save'])) {
/** @var TwigNode|MockObject $twigNode */
$twigNode = $this->createMock(TwigNode::class);
$this->assertArraySubset($options['is_save'], $function->getSafe($twigNode));
}
return;
}

View File

@ -2,24 +2,54 @@
namespace Engelsystem\Test\Unit\Renderer\Twig\Extensions;
use Carbon\Carbon;
use Engelsystem\Renderer\Twig\Extensions\Globals;
use PHPUnit\Framework\MockObject\MockObject;
class GlobalsTest extends ExtensionTest
{
/**
* @covers \Engelsystem\Renderer\Twig\Extensions\Globals::getGlobals
* @covers \Engelsystem\Renderer\Twig\Extensions\Globals::filterEventConfig
*/
public function testGetGlobals()
{
$extension = new Globals();
global $user;
$user = [];
/** @var Globals|MockObject $extension */
$extension = $this->getMockBuilder(Globals::class)
->setMethods(['getEventConfig'])
->getMock();
$extension->expects($this->exactly(2))
->method('getEventConfig')
->willReturnOnConsecutiveCalls(
null,
[
'lorem' => 'ipsum',
'event_end_date' => 1234567890,
]
);
$globals = $extension->getGlobals();
$this->assertGlobalsExists('user', [], $globals);
$this->assertGlobalsExists('event_config', [], $globals);
global $user;
$user['foo'] = 'bar';
$globals = $extension->getGlobals();
$this->assertGlobalsExists('user', ['foo' => 'bar'], $globals);
$this->assertGlobalsExists('event_config', ['lorem' => 'ipsum'], $globals);
$config = $globals['event_config'];
$this->assertArrayHasKey('event_end_date', $config);
/** @var Carbon $eventEndDate */
$eventEndDate = $config['event_end_date'];
$this->assertInstanceOf(Carbon::class, $eventEndDate);
$eventEndDate->setTimezone('UTC');
$this->assertEquals('2009-02-13 23:31:30', $eventEndDate->format('Y-m-d H:i:s'));
}
}

View File

@ -0,0 +1,59 @@
<?php
namespace Engelsystem\Test\Unit\Renderer\Twig\Extensions;
use Engelsystem\Http\Request;
use Engelsystem\Renderer\Twig\Extensions\Legacy;
use PHPUnit\Framework\MockObject\MockObject;
class LegacyTest extends ExtensionTest
{
/**
* @covers \Engelsystem\Renderer\Twig\Extensions\Legacy::getFunctions
*/
public function testGetFunctions()
{
$isSafeHtml = ['is_safe' => ['html']];
/** @var Request|MockObject $request */
$request = $this->createMock(Request::class);
$extension = new Legacy($request);
$functions = $extension->getFunctions();
$this->assertExtensionExists('menu', 'make_navigation', $functions, $isSafeHtml);
$this->assertExtensionExists('menuUserShiftState', 'User_shift_state_render', $functions, $isSafeHtml);
$this->assertExtensionExists('menuUserMessages', 'user_unread_messages', $functions, $isSafeHtml);
$this->assertExtensionExists('menuUserHints', 'header_render_hints', $functions, $isSafeHtml);
$this->assertExtensionExists('menuUserSubmenu', 'make_user_submenu', $functions, $isSafeHtml);
$this->assertExtensionExists('page', [$extension, 'getPage'], $functions);
}
/**
* @covers \Engelsystem\Renderer\Twig\Extensions\Legacy::getPage
* @covers \Engelsystem\Renderer\Twig\Extensions\Legacy::__construct
*/
public function testIsAuthenticated()
{
/** @var Request|MockObject $request */
$request = $this->createMock(Request::class);
$extension = new Legacy($request);
$request->expects($this->exactly(2))
->method('has')
->with('p')
->willReturnOnConsecutiveCalls(true, false);
$request->expects($this->once())
->method('get')
->with('p')
->willReturn('foo-bar');
$request->expects($this->once())
->method('path')
->willReturn('batz');
$this->assertEquals('foo-bar', $extension->getPage());
$this->assertEquals('batz', $extension->getPage());
}
}

View File

@ -2,6 +2,7 @@
namespace Engelsystem\Test\Unit\Renderer;
use Engelsystem\Config\Config;
use Engelsystem\Renderer\TwigEngine;
use Engelsystem\Renderer\TwigLoader;
use Engelsystem\Renderer\TwigServiceProvider;
@ -10,6 +11,7 @@ use PHPUnit\Framework\MockObject\MockObject;
use ReflectionClass as Reflection;
use stdClass;
use Twig_Environment as Twig;
use Twig_Extension_Core as TwigCore;
use Twig_ExtensionInterface as ExtensionInterface;
use Twig_LoaderInterface as TwigLoaderInterface;
@ -97,6 +99,12 @@ class TwigServiceProviderTest extends ServiceProviderTest
$twigLoader = $this->createMock(TwigLoader::class);
/** @var Twig|MockObject $twig */
$twig = $this->createMock(Twig::class);
/** @var Config|MockObject $config */
$config = $this->createMock(Config::class);
/** @var TwigCore|MockObject $twigCore */
$twigCore = $this->getMockBuilder(stdClass::class)
->setMethods(['setTimezone'])
->getMock();
$app = $this->getApp(['make', 'instance', 'tag', 'get']);
@ -125,13 +133,27 @@ class TwigServiceProviderTest extends ServiceProviderTest
['renderer.twigEngine', $twigEngine]
);
$app->expects($this->once())
$app->expects($this->exactly(2))
->method('get')
->with('path.views')
->willReturn($viewsPath);
->withConsecutive(['path.views'], ['config'])
->willReturnOnConsecutiveCalls($viewsPath, $config);
$this->setExpects($app, 'tag', ['renderer.twigEngine', ['renderer.engine']]);
$config->expects($this->once())
->method('get')
->with('timezone')
->willReturn('The/World');
$twig->expects($this->once())
->method('getExtension')
->with(TwigCore::class)
->willReturn($twigCore);
$twigCore->expects($this->once())
->method('setTimezone')
->with('The/World');
$serviceProvider = new TwigServiceProvider($app);
$this->setExtensionsTo($serviceProvider, []);