Files
chill-bundles/src/Bundle/ChillCustomFieldsBundle/Templating/Twig/CustomFieldRenderingTwig.php

89 lines
3.1 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\CustomFieldsBundle\Templating\Twig;
use Chill\CustomFieldsBundle\Entity\CustomField;
use Chill\CustomFieldsBundle\Service\CustomFieldsHelper;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Add the following Twig Extension :
* * chill_custom_field_widget : to render the value of the custom field,
* * chill_custom_field_label : to render the label of the custom field,.
*/
class CustomFieldRenderingTwig
{
/**
* @var array<string, string> The default parameters
*/
private array $defaultParams = [
'label_layout' => '@ChillCustomFields/CustomField/render_label.html.twig',
];
public function __construct(private readonly CustomFieldsHelper $customFieldsHelper) {}
/** (non-PHPdoc).
* @see Twig_ExtensionInterface::getName()
*/
public function getName()
{
return 'chill_custom_fields_rendering';
}
#[\Twig\Attribute\AsTwigFunction('chill_custom_field_is_empty')]
public function isEmptyValue($fields, CustomField $customField)
{
return $this->customFieldsHelper
->isEmptyValue($fields, $customField);
}
/**
* Twig Extension that is used to render the label of a custom field.
*
* @param CustomField $customField Either a customField OR a customizable_entity OR the FQDN of the entity
* @param array $params The parameters for rendering. Currently, 'label_layout' allow to choose a different label. Default is '@ChillCustomFields/CustomField/render_label.html.twig'
*
* @return string HTML representation of the custom field label
*/
#[\Twig\Attribute\AsTwigFunction('chill_custom_field_label', isSafe: [
'html',
], needsEnvironment: true)]
public function renderLabel(Environment $env, CustomField $customField, array $params = []): string
{
$resolvedParams = array_merge($this->defaultParams, $params);
return $env->render($resolvedParams['label_layout'], ['customField' => $customField]);
}
/**
* Twig extension that is used to render the value of a custom field.
*
* The presentation of the value is influenced by the document type.
*
* @param array $fields The array raw, as stored in the db
* @param CustomField $customField Either a customField OR a customizable_entity OR the FQDN of the entity
* @param string $documentType The type of the document (csv, html)
*
* @return string HTML representation of the custom field value, as described in the CustomFieldInterface. Is HTML safe
*/
#[\Twig\Attribute\AsTwigFunction('chill_custom_field_widget', isSafe: [
'html',
])]
public function renderWidget(array $fields, CustomField $customField, $documentType = 'html')
{
return $this->customFieldsHelper
->renderCustomField($fields, $customField, $documentType);
}
}