AssetsExtension.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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\FileManager;
  7. use App\Service\Utils\PathUtils;
  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. class AssetsExtension extends AbstractExtension
  17. {
  18. public function __construct(
  19. readonly private FileManager $fileManager,
  20. ) {
  21. }
  22. public function getFunctions(): array
  23. {
  24. return [
  25. new TwigFunction('absPath', [$this, 'absPath']),
  26. new TwigFunction('fileImagePath', [$this, 'fileImagePath']),
  27. ];
  28. }
  29. /**
  30. * Return the absolute path of the given file in the public directory.
  31. *
  32. * Usage :
  33. *
  34. * <img src="{{ absPath('images/logo.png') }}"/>
  35. */
  36. public function absPath(string $partialPath): string
  37. {
  38. return PathUtils::join(PathUtils::getProjectDir(), 'public', $partialPath);
  39. }
  40. /**
  41. * Retourne l'URL d'accès à une image contenu dans une File.
  42. *
  43. * Usage :
  44. *
  45. * <img src="{{ fileImagePath((licence.logo, 'sm') }}"/>
  46. *
  47. * @param string $size @see src/Enum/Core/FileSizeEnum.php
  48. *
  49. * @throws FileNotFoundException
  50. */
  51. public function fileImagePath(File $file, string $size): string
  52. {
  53. return ltrim($this->fileManager->getImageUrl($file, $size, true), '/');
  54. }
  55. }