Przeglądaj źródła

add a default value to ImageGetSrcById viewhelper

Olivier Massot 1 rok temu
rodzic
commit
00aff3d32f

+ 7 - 0
ot_core/Classes/Service/OpentalentImageService.php

@@ -2,6 +2,7 @@
 
 namespace Opentalent\OtCore\Service;
 
+use Opentalent\OtCore\Exception\ApiRequestException;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
 
 class OpentalentImageService
@@ -19,6 +20,12 @@ class OpentalentImageService
         $this->apiService = $apiService ?? GeneralUtility::makeInstance(OpentalentApiService::class);
     }
 
+    /**
+     * @param int $fileId
+     * @param string $size
+     * @return string
+     * @throws ApiRequestException
+     */
     public function getImageUrl(int $fileId, string $size = self::IMAGE_MD): string {
         if (!in_array($size, [self::IMAGE_SM, self::IMAGE_MD, self::IMAGE_LG])) {
             throw new \RuntimeException('Invalid $size : ' . $size);

+ 17 - 1
ot_templating/Classes/ViewHelpers/Image/GetSrcByIdViewHelper.php

@@ -3,6 +3,7 @@
 namespace Opentalent\OtTemplating\ViewHelpers\Image;
 
 
+use Opentalent\OtCore\Exception\ApiRequestException;
 use Opentalent\OtCore\Service\OpentalentImageService;
 use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
 
@@ -48,6 +49,13 @@ class GetSrcByIdViewHelper extends OtAbstractViewHelper
             false,
             'md'
         );
+        $this->registerArgument(
+            'default',
+            'string',
+            'The src of the image if the file is not found',
+            false,
+            ''
+        );
     }
 
     /**
@@ -59,7 +67,15 @@ class GetSrcByIdViewHelper extends OtAbstractViewHelper
     public function render() {
         $fileId = $this->arguments['fileId'];
         $size = $this->arguments['size'];
-        return $this->opentalentImageService->getImageUrl($fileId, $size);
+        $default = $this->arguments['default'];
+
+        try {
+            return $this->opentalentImageService->getImageUrl($fileId, $size);
+        } catch (ApiRequestException $e) {
+            if ($e->getCode() === 404) {
+                return $default;
+            }
+        }
     }
 
 }