postoffice-1.0.x-dev/extensions/postoffice_file/src/Template/TwigExtension.php
extensions/postoffice_file/src/Template/TwigExtension.php
<?php
namespace Drupal\postoffice_file\Template;
use Drupal\Core\Render\RendererInterface;
use Drupal\file\FileInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* A class providing postoffice Twig extensions.
*/
class TwigExtension extends AbstractExtension {
/**
* The renderer.
*/
protected RendererInterface $renderer;
/**
* Constructs postoffice twig extension.
*
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
*/
public function __construct(RendererInterface $renderer) {
$this->renderer = $renderer;
}
/**
* {@inheritdoc}
*/
public function getFunctions(): array {
return [
new TwigFunction(
'postoffice_file_attach_entity',
$this->attachFileEntity(...)
),
new TwigFunction(
'postoffice_file_attach_uri',
$this->attachFileUri(...)
),
];
}
/**
* {@inheritdoc}
*/
public function getName(): string {
return 'postoffice_file';
}
/**
* Attaches a file specified by its uri.
*
* Allows Twig templates to attach a file using a function.
* @code
* {% postoffice_file_attach_uri('path/to/some/file.pdf') %}
* @endcode
*/
public function attachFileUri(string $uri, ?string $name = NULL, ?string $mimeType = NULL): void {
$templateAttached['#attached']['drupalSettings']['postofficeFileAttachments'][$uri] = [
'name' => $name,
'mimeType' => $mimeType,
];
$this->renderer->render($templateAttached);
}
/**
* Attaches a managed file entity.
*
* Allows Twig templates to attach a file using a function.
* @code
* {% postoffice_file_attach_entity(fileEntity) %}
* @endcode
*/
public function attachFileEntity(FileInterface $file, ?string $name = NULL): void {
$this->attachFileUri($file->getFileUri(), $name, $file->getMimeType());
}
}
