Skip to content

Commit cb0de46

Browse files
author
Bohdan Berezhniy
committed
added compatibility with magefan webp
1 parent 2e78904 commit cb0de46

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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+
}

etc/frontend/di.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,9 @@
2121
<plugin name="magefan_lazyLoad_plugin_amasty_pagespeedoptimizer_model_output_lazyloadprocessor_plugin"
2222
type="Magefan\LazyLoad\Plugin\Amasty\PageSpeedOptimizer\Model\Output\LazyLoadProcessorPlugin" sortOrder="1000"/>
2323
</type>
24+
<!-- Integration with Magefan_WebP -->
25+
<type name="Magefan\WebP\Model\WebP">
26+
<plugin name="magefan_lazyLoad_plugin_for_webp"
27+
type="Magefan\LazyLoad\Plugin\Magefan\WebP\Model\WebPPlugin" sortOrder="10000"/>
28+
</type>
2429
</config>

0 commit comments

Comments
 (0)