chill-bundles/Templating/ChillTwigHelper.php

102 lines
3.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2014-2019, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Templating;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\Environment;
/**
*
*/
class ChillTwigHelper extends AbstractExtension
{
public function getFilters()
{
return [
new TwigFilter('chill_print_or_message', [$this, 'printOrMessage'], [
'needs_environment' => true,
'is_safe' => ['html', 'html_attrs']
]),
];
}
/**
* Print `value` inside a template, or, if $value is empty,
* print $message.
*
* The template can be customized. The template is a full path to another
* template, or one of the key belows:
*
* - 'default' ;
* - 'blockquote' ;
*
* `DateTimeInterface are also rendered. The date and time format may be set
* using those key in `$options´ parameter:
*
* - `date_format` (default to `'medium'`)
* - `time_format` (default to `'none'`)
*
* @param Environment $twig
* @param string $value Default to 'No value'. Fallback to default if null
* @param string $message
* @param string $template
* @param array $options
* @return string
*/
public function printOrMessage(
Environment $twig,
$value,
$message = 'No value',
$template = 'default',
array $options = []
) {
if ($value instanceof \DateTimeInterface) {
$options = \array_merge([
'date_format' => 'medium',
'time_format' => 'none'
], $options);
switch ($template) {
case 'default':
case 'blockquote':
$t = '@ChillMain/Extensions/PrintOrMessage/'.$template.'_date.html.twig';
break;
default:
$t = $template;
}
} else {
switch ($template) {
case 'default':
case 'blockquote':
$t = '@ChillMain/Extensions/PrintOrMessage/'.$template.'.html.twig';
break;
default:
$t = $template;
}
}
return $twig->render($t, \array_merge([
'value' => $value,
'message' => $message ?? 'No value'
], $options));
}
}