GetSrcByIdViewHelper.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Opentalent\OtTemplating\ViewHelpers\Image;
  3. use Opentalent\OtCore\Exception\ApiRequestException;
  4. use Opentalent\OtCore\Service\OpentalentImageService;
  5. use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
  6. /**
  7. * Returns the url of the requested image
  8. *
  9. * {namespace ot=Opentalent\OtTemplating\ViewHelpers}
  10. *
  11. * {ot:getImageUrl(fileId: 123, size: 'md')}
  12. *
  13. * @see ot_core/Classes/Service/OpentalentImageService.php
  14. * @package Opentalent\OtTemplating\ViewHelpers
  15. */
  16. class GetSrcByIdViewHelper extends OtAbstractViewHelper
  17. {
  18. public OpentalentImageService $opentalentImageService;
  19. /**
  20. * @param OpentalentImageService $opentalentImageService
  21. * @return void
  22. */
  23. public function injectOpentalentImageService(OpentalentImageService $opentalentImageService)
  24. {
  25. $this->opentalentImageService = $opentalentImageService;
  26. }
  27. /**
  28. * -- This method is expected by Fluid --
  29. * Declares the viewhelper's parameters
  30. */
  31. public function initializeArguments()
  32. {
  33. $this->registerArgument(
  34. 'fileId',
  35. 'int',
  36. 'The id of the File object',
  37. true
  38. );
  39. $this->registerArgument(
  40. 'size',
  41. 'string',
  42. 'The expected size (sm, md, or lg)',
  43. false,
  44. 'md'
  45. );
  46. $this->registerArgument(
  47. 'default',
  48. 'string',
  49. 'The src of the image if the file is not found',
  50. false,
  51. ''
  52. );
  53. }
  54. /**
  55. * -- This method is expected by Fluid --
  56. * Renders the content as html
  57. *
  58. * @return string Rendered tag
  59. */
  60. public function render() {
  61. $fileId = $this->arguments['fileId'];
  62. $size = $this->arguments['size'];
  63. $default = $this->arguments['default'];
  64. try {
  65. return $this->opentalentImageService->getImageUrl($fileId, $size);
  66. } catch (ApiRequestException $e) {
  67. if ($e->getCode() === 404) {
  68. return $default;
  69. }
  70. }
  71. }
  72. }