|
|
@@ -0,0 +1,40 @@
|
|
|
+<?php
|
|
|
+declare(strict_types=1);
|
|
|
+
|
|
|
+namespace App\Service\Twig;
|
|
|
+
|
|
|
+use App\Service\Utils\PathUtils;
|
|
|
+use Path\Path;
|
|
|
+use Symfony\Component\Asset\Packages;
|
|
|
+use Twig\Extension\AbstractExtension;
|
|
|
+use Twig\TwigFilter;
|
|
|
+
|
|
|
+class ToBase64Extension extends AbstractExtension
|
|
|
+{
|
|
|
+ public function __construct(
|
|
|
+ private Packages $packages,
|
|
|
+ private string $projectDir
|
|
|
+ ) {}
|
|
|
+
|
|
|
+ public function getFilters(): array
|
|
|
+ {
|
|
|
+ return [
|
|
|
+ new TwigFilter('img_to_base64', [$this, 'imgToBase64']),
|
|
|
+ ];
|
|
|
+ }
|
|
|
+
|
|
|
+ public function imgToBase64(string $assetPath): string
|
|
|
+ {
|
|
|
+ $publicDir = (new Path($this->projectDir))->append('public');
|
|
|
+ $imgPath = $publicDir->append($assetPath);
|
|
|
+
|
|
|
+ if (!$imgPath->exists()) {
|
|
|
+ return '';
|
|
|
+ }
|
|
|
+
|
|
|
+ $imageData = base64_encode($imgPath->getContent());
|
|
|
+ $mimeType = mime_content_type($imgPath->path()) ?: 'image/jpeg';
|
|
|
+
|
|
|
+ return "data:$mimeType;base64,$imageData";
|
|
|
+ }
|
|
|
+}
|