AssetsExtension.php 1.6 KB

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