AssetsExtension.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Twig;
  4. use App\Entity\Core\File;
  5. use App\Service\File\Exception\FileNotFoundException;
  6. use App\Service\File\Manager\ImageManager;
  7. use App\Service\Utils\Path;
  8. use Twig\Extension\AbstractExtension;
  9. use Twig\TwigFunction;
  10. /**
  11. * Add new Twig methods and filters to manipulate assets
  12. *
  13. * This is particularly useful for exports, since wkhtmltoX can't resolve partial paths for assets, or download
  14. * files from the Opentalent API (the non-public ones at least)
  15. *
  16. * // TODO: à voir si c'est bien à sa place parmi les services
  17. */
  18. class AssetsExtension extends AbstractExtension
  19. {
  20. public function __construct(
  21. readonly private ImageManager $imageManager
  22. )
  23. {}
  24. public function getFunctions(): array
  25. {
  26. return [
  27. new TwigFunction('absPath', [$this, 'absPath']),
  28. new TwigFunction('toBase64Src', [$this, 'toBase64Src']),
  29. ];
  30. }
  31. /**
  32. * Return the absolute path of the given file in the public directory
  33. *
  34. * Usage :
  35. *
  36. * <img src="{{ absPath('images/logo.png') }}"/>
  37. *
  38. * @param string $partialPath
  39. * @return string
  40. */
  41. public function absPath(string $partialPath): string
  42. {
  43. return Path::join(Path::getProjectDir(), 'public', $partialPath);
  44. }
  45. /**
  46. * Return the src of an image as a base64 content
  47. *
  48. * Usage :
  49. *
  50. * <img src="{{ toBase64Src((licence.logo) }}"/>
  51. *
  52. * @param File $file
  53. * @return string
  54. * @throws FileNotFoundException
  55. */
  56. public function toBase64Src(File $file): string
  57. {
  58. return 'data:' . $file->getMimeType() . ';base64,' . base64_encode($this->imageManager->read($file));
  59. }
  60. }