|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magefan ([email protected]). All rights reserved. |
| 4 | + * Please visit Magefan.com for license details (https://magefan.com/end-user-license-agreement). |
| 5 | + * |
| 6 | + * Glory to Ukraine! Glory to the heroes! |
| 7 | + */ |
| 8 | + |
| 9 | +namespace Magefan\LazyLoad\Plugin\Magefan\WebP\Model; |
| 10 | + |
| 11 | +use Magefan\WebP\Model\WebP; |
| 12 | + |
| 13 | +/** |
| 14 | + * Class WebPPlugin |
| 15 | + */ |
| 16 | +class WebPPlugin |
| 17 | +{ |
| 18 | + const LAZY_TAG = '<!-- MAGEFAN_LAZY_LOAD -->'; |
| 19 | + |
| 20 | + /** |
| 21 | + * @var Convertor |
| 22 | + */ |
| 23 | + private $webp; |
| 24 | + |
| 25 | + public function __construct( |
| 26 | + WebP $webp |
| 27 | + |
| 28 | + ) { |
| 29 | + $this->webp = $webp; |
| 30 | + } |
| 31 | + |
| 32 | + public function aroundGetPictureTagHtml($subject, callable $proceed, $webpUrl, $imagePath, $htmlTag) |
| 33 | + { |
| 34 | + $result = false; |
| 35 | + |
| 36 | + $originImagePath = $imagePath; |
| 37 | + |
| 38 | + if (strpos($imagePath, 'Magefan_LazyLoad/images/pixel.jpg')) { |
| 39 | + |
| 40 | + $doStr = 'data-original="'; |
| 41 | + $p1 = strpos($htmlTag, $doStr); |
| 42 | + |
| 43 | + if ($p1 !== false) { |
| 44 | + $p1 += strlen($doStr); |
| 45 | + $p2 = strpos($htmlTag, '"', $p1); |
| 46 | + if ($p2 !== false) { |
| 47 | + $imagePath = substr($htmlTag, $p1, $p2 - $p1); |
| 48 | + $webpUrl = $this->webp->getWebpUrl($imagePath); |
| 49 | + |
| 50 | + $result = $this->webp->convert($imagePath, $webpUrl); |
| 51 | + |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + if (!$result) { |
| 57 | + return $htmlTag; |
| 58 | + } |
| 59 | + |
| 60 | + $html = $proceed($webpUrl, $imagePath, $htmlTag); |
| 61 | + |
| 62 | + if ($originImagePath != $imagePath) { |
| 63 | + if (strpos($html, '<picture') !== false) { |
| 64 | + $tmpSrc = 'TMP_SRC'; |
| 65 | + $pixelSrc = 'srcset="' . $originImagePath . '"'; |
| 66 | + $html = str_replace($pixelSrc, $tmpSrc, $html); |
| 67 | + $html = preg_replace('#<source\s+([^>]*)(?:srcset="([^"]*)")([^>]*)?>#isU', '<source ' . $pixelSrc . |
| 68 | + ' data-originalset="$2" $1 $3/>', $html); |
| 69 | + $html = str_replace($tmpSrc, $pixelSrc, $html); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return $html; |
| 74 | + } |
| 75 | +} |
0 commit comments