|
| 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\Api; |
| 10 | + |
| 11 | +use Magefan\LazyLoad\Model\Config; |
| 12 | + |
| 13 | +/** |
| 14 | + * Class WebPPlugin |
| 15 | + */ |
| 16 | +class HtmlParserInterfacePlugin |
| 17 | +{ |
| 18 | + |
| 19 | + /** |
| 20 | + * @var Config |
| 21 | + */ |
| 22 | + private $config; |
| 23 | + |
| 24 | + /** |
| 25 | + * WebPPlugin constructor. |
| 26 | + * @param Config $config |
| 27 | + */ |
| 28 | + public function __construct( |
| 29 | + Config $config |
| 30 | + |
| 31 | + ) { |
| 32 | + $this->config = $config; |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * @param $subject |
| 37 | + * @param callable $proceed |
| 38 | + * @param $imagePath |
| 39 | + * @param $htmlTag |
| 40 | + * @return mixed|string|string[]|null |
| 41 | + */ |
| 42 | + public function aroundGetNewHtmlTag($subject, callable $proceed, $imagePath, $image) |
| 43 | + { |
| 44 | + if (!$this->config->getEnabled()) { |
| 45 | + return $proceed($imagePath, $image); |
| 46 | + } |
| 47 | + |
| 48 | + $originImagePath = $imagePath; |
| 49 | + |
| 50 | + if (strpos($imagePath, 'Magefan_LazyLoad/images/pixel.jpg')) { |
| 51 | + |
| 52 | + $doStr = 'data-original="'; |
| 53 | + $p1 = strpos($image, $doStr); |
| 54 | + |
| 55 | + if ($p1 !== false) { |
| 56 | + $p1 += strlen($doStr); |
| 57 | + $p2 = strpos($image, '"', $p1); |
| 58 | + if ($p2 !== false) { |
| 59 | + $imagePath = substr($image, $p1, $p2 - $p1); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + $html = $proceed($imagePath, $image); |
| 65 | + |
| 66 | + if ($originImagePath != $imagePath) { |
| 67 | + |
| 68 | + if (strpos($html, '<picture') !== false) { |
| 69 | + $tmpSrc = 'TMP_SRC'; |
| 70 | + $pixelSrc = 'srcset="' . $originImagePath . '"'; |
| 71 | + |
| 72 | + $html = str_replace($pixelSrc, $tmpSrc, $html); |
| 73 | + |
| 74 | + $html = preg_replace('#<source\s+([^>]*)(?:srcset="([^"]*)")([^>]*)?>#isU', '<source ' . $pixelSrc . |
| 75 | + ' data-originalset="$2" $1 $3/>', $html); |
| 76 | + |
| 77 | + $html = str_replace($tmpSrc, $pixelSrc, $html); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + return $html; |
| 82 | + } |
| 83 | +} |
0 commit comments