mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-06-12 13:24:25 +00:00
83 lines
2.3 KiB
PHP
83 lines
2.3 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
/*
|
||
* Chill is a software for social workers
|
||
*
|
||
* For the full copyright and license information, please view
|
||
* the LICENSE file that was distributed with this source code.
|
||
*/
|
||
|
||
namespace Chill\MainBundle\Templating;
|
||
|
||
use DateTimeInterface;
|
||
use Twig\Environment;
|
||
use Twig\Extension\AbstractExtension;
|
||
use Twig\TwigFilter;
|
||
|
||
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 string $value Default to 'No value'. Fallback to default if null
|
||
* @param string $message
|
||
* @param string $template
|
||
*
|
||
* @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);
|
||
|
||
$t = match ($template) {
|
||
'default', 'blockquote' => '@ChillMain/Extensions/PrintOrMessage/'.$template.'_date.html.twig',
|
||
default => $template,
|
||
};
|
||
} else {
|
||
$t = match ($template) {
|
||
'default', 'blockquote' => '@ChillMain/Extensions/PrintOrMessage/'.$template.'.html.twig',
|
||
default => $template,
|
||
};
|
||
}
|
||
|
||
return $twig->render($t, \array_merge([
|
||
'value' => $value,
|
||
'message' => $message,
|
||
], $options));
|
||
}
|
||
}
|