1<?php 2 3namespace ComboStrap; 4 5use ComboStrap\Meta\Field\FeaturedRasterImage; 6use ComboStrap\Meta\Field\FeaturedSvgImage; 7use Exception; 8 9class ImageSystem 10{ 11 12 /** 13 * @throws ExceptionNotFound - if the image was not found 14 */ 15 public static function selectAndGetBestMetadataPageImageFetcherForRatio(MarkupPath $page, TagAttributes $tagAttributes): IFetcherLocalImage 16 { 17 /** 18 * Take the image and the page images 19 * of the first page with an image 20 */ 21 $selectedPageImage = self::createImageFetchFromPageImageMetadata($page); 22 $stringRatio = $tagAttributes->getValue(Dimension::RATIO_ATTRIBUTE); 23 if ($stringRatio === null) { 24 return $selectedPageImage; 25 } 26 27 /** 28 * We select the best image for the ratio 29 * Best ratio 30 */ 31 $bestRatioDistance = 9999; 32 try { 33 $targetRatio = Dimension::convertTextualRatioToNumber($stringRatio); 34 } catch (ExceptionBadSyntax $e) { 35 LogUtility::error("The ratio ($stringRatio) is not a valid ratio. Error: {$e->getMessage()}", PageImageTag::CANONICAL); 36 return $selectedPageImage; 37 } 38 39 $pageImages = $page->getPageMetadataImages(); 40 foreach ($pageImages as $pageImage) { 41 $path = $pageImage->getImagePath(); 42 try { 43 $fetcherImage = IFetcherLocalImage::createImageFetchFromPath($path); 44 } catch (Exception $e) { 45 LogUtility::msg("An image object could not be build from ($path). Is it an image file ?. Error: {$e->getMessage()}"); 46 continue; 47 } 48 $ratioDistance = $targetRatio - $fetcherImage->getIntrinsicAspectRatio(); 49 if ($ratioDistance < $bestRatioDistance) { 50 $bestRatioDistance = $ratioDistance; 51 $selectedPageImage = $fetcherImage; 52 } 53 } 54 return $selectedPageImage; 55 } 56 57 /** 58 * @throws ExceptionNotFound 59 * @deprecated 60 */ 61 public static function createImageFetchFromPageImageMetadata(MarkupPath $page): IFetcherLocalImage 62 { 63 $selectedPageImage = null; 64 foreach ($page->getPageMetadataImages() as $pageMetadataImage) { 65 try { 66 $pageMetadataImagePath = $pageMetadataImage->getImagePath(); 67 $selectedPageImage = IFetcherLocalImage::createImageFetchFromPath($pageMetadataImagePath); 68 } catch (\Exception $e) { 69 LogUtility::internalError("The file ($pageMetadataImagePath) is not a valid image for the page ($page). Error: {$e->getMessage()}"); 70 continue; 71 } 72 } 73 if ($selectedPageImage !== null) { 74 return $selectedPageImage; 75 } 76 throw new ExceptionNotFound("No page image metadata image could be found for the page ($page)"); 77 } 78 79 80} 81