├── .github ├── FUNDING.yml └── workflows │ ├── extdn-integration-tests-post-install.sh │ ├── extdn-integration-tests-pre-install.sh │ ├── extdn-integration-tests.yml │ ├── extdn-phpstan-pre-install.sh │ ├── extdn-phpstan.yml │ ├── extdn-static-tests.yml │ └── extdn-unit-tests.yml ├── .gitignore ├── .magento └── dev │ └── tests │ ├── integration │ ├── etc │ │ └── install-config-mysql.phps │ └── phpunit.xml │ └── unit │ └── phpunit.xml ├── .module.ini ├── CHANGELOG.md ├── Config ├── Config.php └── Frontend │ └── Funding.php ├── Controller └── Test │ ├── Images.php │ └── Mail.php ├── Convertor ├── ConvertWrapper.php └── Convertor.php ├── Exception └── InvalidConvertorException.php ├── LICENSE.txt ├── Model └── Config │ └── Source │ └── Encoding.php ├── Plugin └── AddCspInlineScripts.php ├── README.md ├── Setup └── UpgradeData.php ├── Test ├── Integration │ ├── Common.php │ ├── ImageConversionTest.php │ ├── ImageWithCustomStyleTest.php │ ├── ModuleTest.php │ ├── MultipleImagesSameTest.php │ └── MultipleImagesTest.php ├── Unit │ ├── Config │ │ └── ConfigTest.php │ └── Convertor │ │ └── ConvertorTest.php └── Utils │ ├── ConvertWrapperStub.php │ └── ImageProvider.php ├── composer.json ├── etc ├── acl.xml ├── adminhtml │ └── system.xml ├── config.xml ├── di.xml ├── frontend │ ├── di.xml │ └── routes.xml └── module.xml ├── phpstan.neon ├── registration.php └── view ├── adminhtml └── templates │ └── funding.phtml └── frontend ├── layout ├── hyva_catalog_product_view.xml ├── hyva_default.xml ├── webp_test_images_image_with_custom_style.xml ├── webp_test_images_multiple_existing_picturesets.xml ├── webp_test_images_multiple_images.xml ├── webp_test_images_multiple_images_same.xml └── webp_test_images_unknown_image.xml ├── requirejs-config.js ├── templates ├── hyva │ ├── add-webp-class-to-body.phtml │ └── gallery-additions.phtml └── test │ ├── image_with_custom_style.phtml │ ├── multiple_existing_picturesets.phtml │ ├── multiple_images.phtml │ ├── multiple_images_same.phtml │ └── unknown_image.phtml └── web ├── images └── test │ ├── flowers.jpg │ ├── flowers.webp │ ├── goku.jpg │ └── transparent-dragon.png └── js ├── add-webp-class-to-body.js ├── gallery-mixin.js ├── has-webp.js └── swatch-renderer-mixin.js /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: yireo 2 | custom: ["https://www.paypal.me/yireo"] 3 | 4 | -------------------------------------------------------------------------------- /.github/workflows/extdn-integration-tests-post-install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | bin/magento setup:config:set --cache-backend=redis --cache-backend-redis-server=redis --cache-backend-redis-db=0 -n 3 | -------------------------------------------------------------------------------- /.github/workflows/extdn-integration-tests-pre-install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | composer config minimum-stability dev 3 | composer config prefer-stable false 4 | 5 | composer require --dev yireo/magento2-integration-test-helper --no-update 6 | 7 | composer require yireo/magento2-replace-bundled:^4.0 --no-update 8 | composer require yireo/magento2-replace-pagebuilder:^4.0 --no-update 9 | -------------------------------------------------------------------------------- /.github/workflows/extdn-integration-tests.yml: -------------------------------------------------------------------------------- 1 | name: ExtDN Integration Tests 2 | on: [push] 3 | 4 | jobs: 5 | integration-tests: 6 | name: Magento 2 Integration Tests 7 | runs-on: ubuntu-latest 8 | services: 9 | mysql: 10 | image: mysql:8.0 11 | env: 12 | MYSQL_ROOT_PASSWORD: root 13 | ports: 14 | - 3306:3306 15 | options: --tmpfs /tmp:rw --tmpfs /var/lib/mysql:rw --health-cmd="mysqladmin ping" 16 | es: 17 | image: docker.io/wardenenv/elasticsearch:7.8 18 | ports: 19 | - 9200:9200 20 | env: 21 | 'discovery.type': single-node 22 | 'xpack.security.enabled': false 23 | ES_JAVA_OPTS: "-Xms64m -Xmx512m" 24 | options: --health-cmd="curl localhost:9200/_cluster/health?wait_for_status=yellow&timeout=60s" --health-interval=10s --health-timeout=5s --health-retries=3 25 | redis: 26 | image: redis 27 | ports: 28 | - 6379:6379 29 | options: --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 30 | env: 31 | MAGENTO_MARKETPLACE_USERNAME: ${{ secrets.MAGENTO_MARKETPLACE_USERNAME }} 32 | MAGENTO_MARKETPLACE_PASSWORD: ${{ secrets.MAGENTO_MARKETPLACE_PASSWORD }} 33 | REPOSITORY_URL: https://repo.magento.com/ 34 | MODULE_NAME: ${{ secrets.MODULE_NAME }} 35 | COMPOSER_NAME: ${{ secrets.COMPOSER_NAME }} 36 | MAGENTO_POST_INSTALL_SCRIPT: .github/workflows/extdn-integration-tests-post-install.sh 37 | steps: 38 | - uses: actions/checkout@v4 39 | - name: Cache Composer dependencies 40 | uses: actions/cache@v4 41 | with: 42 | path: /tmp/composer-cache 43 | key: ${{ runner.os }}-${{ hashFiles('**/composer.lock') }} 44 | 45 | - uses: extdn/github-actions-m2/magento-integration-tests/8.3@master 46 | env: 47 | MAGENTO_VERSION: '2.4.7-p3' 48 | with: 49 | magento_pre_install_script: .github/workflows/extdn-integration-tests-pre-install.sh 50 | magento_post_install_script: .github/workflows/extdn-integration-tests-post-install.sh 51 | -------------------------------------------------------------------------------- /.github/workflows/extdn-phpstan-pre-install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | composer config minimum-stability dev 3 | composer config prefer-stable false 4 | 5 | composer require yireo/magento2-integration-test-helper --no-update 6 | 7 | composer config --no-plugins allow-plugins true 8 | 9 | composer require --dev phpstan/extension-installer --no-update 10 | composer require --dev bitexpert/phpstan-magento --no-update 11 | 12 | composer require yireo/magento2-replace-bundled:^4.0 --no-update 13 | composer require yireo/magento2-replace-inventory:^4.0 --no-update 14 | composer require yireo/magento2-replace-pagebuilder:^4.0 --no-update 15 | -------------------------------------------------------------------------------- /.github/workflows/extdn-phpstan.yml: -------------------------------------------------------------------------------- 1 | name: ExtDN PHPStan 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | phpstan: 6 | name: PHPStan 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | 11 | - name: "Determine composer cache directory" 12 | id: "determine-composer-cache-directory" 13 | run: "echo \"::set-output name=directory::$(composer config cache-dir)\"" 14 | 15 | - name: Cache Composer dependencies 16 | uses: actions/cache@v4 17 | with: 18 | path: "${{ steps.determine-composer-cache-directory.outputs.directory }}" 19 | key: ${{ runner.os }}-${{ hashFiles('**/composer.lock') }} 20 | 21 | - uses: extdn/github-actions-m2/magento-phpstan/8.3@master 22 | with: 23 | composer_name: yireo/magento2-webp2 24 | composer_version: 2 25 | phpstan_level: 2 26 | magento_pre_install_script: .github/workflows/extdn-phpstan-pre-install.sh 27 | -------------------------------------------------------------------------------- /.github/workflows/extdn-static-tests.yml: -------------------------------------------------------------------------------- 1 | name: ExtDN Static Tests 2 | on: [push] 3 | 4 | jobs: 5 | static: 6 | name: Static Code Analysis 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | - uses: extdn/github-actions-m2/magento-coding-standard/8.3@master 11 | with: 12 | phpcs_severity: 8 13 | phpcs_report: full 14 | phpcs_extensions: php 15 | -------------------------------------------------------------------------------- /.github/workflows/extdn-unit-tests.yml: -------------------------------------------------------------------------------- 1 | name: ExtDN Unit Tests 2 | on: [push] 3 | 4 | jobs: 5 | unit-tests: 6 | name: Magento 2 Unit Tests 7 | runs-on: ubuntu-latest 8 | env: 9 | MAGENTO_MARKETPLACE_USERNAME: ${{ secrets.MAGENTO_MARKETPLACE_USERNAME }} 10 | MAGENTO_MARKETPLACE_PASSWORD: ${{ secrets.MAGENTO_MARKETPLACE_PASSWORD }} 11 | MODULE_NAME: ${{ secrets.MODULE_NAME }} 12 | COMPOSER_NAME: ${{ secrets.COMPOSER_NAME }} 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Cache Composer dependencies 17 | uses: actions/cache@v4 18 | with: 19 | path: /tmp/composer-cache 20 | key: ${{ runner.os }}-${{ hashFiles('**/composer.lock') }} 21 | 22 | - uses: extdn/github-actions-m2/magento-unit-tests/8.3@master 23 | env: 24 | MAGENTO_VERSION: '2.4.7-p3' 25 | COMPOSER_VERSION: 2 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yireo/Yireo_Webp2/02fc4614f5884caa73755c17f13ee816c6f14f4e/.gitignore -------------------------------------------------------------------------------- /.magento/dev/tests/integration/etc/install-config-mysql.phps: -------------------------------------------------------------------------------- 1 | '%MYSQL_HOST%', 9 | 'db-user' => 'root', 10 | 'db-password' => 'root', 11 | 'db-name' => 'magento-integration-test', 12 | 'db-prefix' => '', 13 | 'backend-frontname' => 'backend', 14 | 'admin-user' => \Magento\TestFramework\Bootstrap::ADMIN_NAME, 15 | 'admin-password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD, 16 | 'admin-email' => \Magento\TestFramework\Bootstrap::ADMIN_EMAIL, 17 | 'admin-firstname' => \Magento\TestFramework\Bootstrap::ADMIN_FIRSTNAME, 18 | 'admin-lastname' => \Magento\TestFramework\Bootstrap::ADMIN_LASTNAME, 19 | ]; 20 | -------------------------------------------------------------------------------- /.magento/dev/tests/integration/phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | ../../../vendor/yireo/*/Test/Integration 12 | 13 | 14 | 15 | 16 | ../../../vendor/yireo 17 | 18 | ../../../vendor/yireo/*/Test 19 | 20 | 21 | 22 | 23 | . 24 | testsuite 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /.magento/dev/tests/unit/phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | ../../../app/code/*/*/Test/Unit 12 | 13 | 14 | 15 | 16 | ../../../app/code 17 | 18 | ../../../app/code/*/*/Test 19 | 20 | 21 | 22 | 23 | . 24 | testsuite 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /.module.ini: -------------------------------------------------------------------------------- 1 | EXTENSION_VENDOR="Yireo" 2 | EXTENSION_NAME="Webp2" 3 | MODULE_NAME="Yireo_Webp2" 4 | COMPOSER_NAME="yireo/magento2-webp2" 5 | PHP_VERSIONS=("7.4", "8.1", "8.2") 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ## [0.14.3] - 24 October 2024 10 | ### Fixed 11 | - Add funding 12 | 13 | ## [0.14.2] - 23 August 2024 14 | ### Fixed 15 | - Guarantee return type is string #170 16 | 17 | ## [0.14.1] - 23 August 2024 18 | ### Fixed 19 | - Add CSP nonces to inline scripts 20 | 21 | ## [0.14.0] - 20 June 2024 22 | ### Fixed 23 | - Move GraphQL support in seperate [module](https://github.com/yireo/Yireo_Webp2GraphQl) 24 | 25 | ## [0.13.5] - 4 April 2024 26 | ### Fixed 27 | - Compatibility with Magento >=2.4.7-beta3 28 | 29 | ## [0.13.4] - 26 September 2023 30 | ### Fixed 31 | - Catch the correct exception when using properties of a specific exception. 32 | 33 | ## [0.13.3] - 22 September 2023 34 | ### Fixed 35 | - Properly check for MIME-typed (fix of #149) 36 | - Add "webp" / "nowebp" to body class for Hyva 37 | 38 | ## [0.13.2] - 6 September 2023 39 | ### Fixed 40 | - Make sure convertor is called for unsupported types #149 (@kernstmediarox) 41 | 42 | ## [0.13.1] - 6 September 2023 43 | ### Fixed 44 | - Remove non-existing `description` in exception handling 45 | - Move Hyva dependency to separate package `yireo/magento2-webp2-for-hyva` 46 | 47 | ## [0.13.0] - 30 August 2023 48 | ### Added 49 | - Copied GraphQL `url_webp` from Hyva compatibility module to here 50 | 51 | ### Fixed 52 | - Catch exceptions in converters by changing array to string with a foreach (@ghezelbash PR #140) 53 | 54 | ## [0.12.5] - 19 March 2023 55 | ### Fixed 56 | - Version bump because of new NextGenImages minor 57 | 58 | ## [0.12.4] - 13 September 2022 59 | ### Fixed 60 | - Implement the NextGenImages config setting `convert_images` 61 | 62 | ## [0.12.3] - 20 August 2022 63 | ### Fixed 64 | - Add missing semicolon #130 65 | 66 | ## [0.12.2] - 21 July 2022 67 | ### Fixed 68 | - Using JS native `_determineProductData` function #120 (@artbambou) 69 | - Fix uncaught exception #127 (@jakegore) 70 | 71 | ## [0.12.1] - 2 June 2022 72 | ### Fixed 73 | - Skip image replacement if target URL is still empty 74 | 75 | ## [0.12.0] - 4 May 2022 76 | ### Added 77 | - Added ACL for user permissions (@jeroenalewijns) 78 | - Always add `webp` CSS class to body via JS detection 79 | - Add various integration tests 80 | - Refactoring because of changed NextGenImages API 81 | 82 | ### Removed 83 | - Moved AJAX plugin for swatches to NextGenImages 84 | 85 | ## [0.11.4] - 23 August 2021 86 | ### Fixed 87 | - Check for double InvalidInputImageTypeException 88 | 89 | ## [0.11.3] - 23 August 2021 90 | ### Fixed 91 | - Fix wrong exception being caught 92 | 93 | ## [0.11.2] - 11 August 2021 94 | ### Fixed 95 | - Remove async from function (IE11 Support) (@barryvdh) 96 | 97 | ## [0.11.1] - 10 August 2021 98 | ### Fixed 99 | - Fix error to config.xml introduced in last version (@chrisastley) 100 | 101 | ## [0.11.0] - 9 August 2021 102 | ### Added 103 | - New option `encoding` for better performance with only `lossy` (@basvanpoppel) 104 | 105 | ## [0.10.11] - 15 July 2021 106 | ### Fixed 107 | - Prevent exception when GIF is renamed to JPG 108 | 109 | ## [0.10.10] - 7 July 2021 110 | ### Fixed 111 | - Hide all other fields if setting "Enabled" is set to 0 112 | - Add current store to all methods 113 | 114 | ## [0.10.9] - 24 June 2021 115 | ### Fixed 116 | - Fix PHP Notice when gallery is missing 117 | 118 | ## [0.10.8] - 24 June 2021 119 | ### Fixed 120 | - Allow configuring convertors (#77) 121 | 122 | ## [0.10.7] - 6 May 2021 123 | ### Fixed 124 | - Prevents error if variable $imageData[$imageType] is empty (@maksymcherevko) 125 | 126 | ## [0.10.6] - 2 April 2021 127 | ### Fixed 128 | - Webp images not being generated if cached jpg does not exist yet #70 (@gtlt) 129 | 130 | ## [0.10.5] - 9 March 2021 131 | ### Fixed 132 | - Refactor conversion errors 133 | - Move helper function to NextGenImages 134 | - Throw exception when no conversion is needed 135 | - Update convertor class to comply to updated interface 136 | 137 | ## [0.10.4] - 15 February 2021 138 | ### Fixed 139 | - Log all exceptions to NextGenImages logger 140 | 141 | ## [0.10.3] - 12 February 2021 142 | ### Fixed 143 | - Make sure configurable images don't throw exception 144 | 145 | ## [0.10.2] - 12 February 2021 146 | ### Fixed 147 | - Make sure wrong gallery images don't throw exception 148 | 149 | ## [0.10.1] - 11 February 2021 150 | ### Fixed 151 | - Fix JS error 152 | - Rewrite into synchronous way of detecting WebP 153 | 154 | 155 | ## [0.10.0] - 28 January 2021 156 | ### Added 157 | - Improved support on product detail page (configurable swatches + fotorama) 158 | 159 | ## [0.9.6] - 22 January 2021 160 | ### Fixed 161 | - When no .webp file is available, the source tag will be removed to prevent old image being shown on the frontend (@ar-vie) 162 | 163 | 164 | ## [0.9.5] - 3 December 2020 165 | ### Fixed 166 | - Remove class UrlReplacer again after refactoring NextGenImages 167 | 168 | ## [0.9.4] - 3 December 2020 169 | ### Fixed 170 | - Fix missing class UrlReplacer 171 | 172 | ## [0.9.3] - 2 December 2020 173 | ### Fixed 174 | - Fix composer deps with magento2-next-gen-images 175 | 176 | ## [0.9.2] - 30 November 2020 177 | ### Fixed 178 | - Stick to new ConvertorInterface interface of NextGenImages 179 | 180 | ## [0.9.1] - 30 November 2020 181 | ### Fixed 182 | - Wrong composer dependency with NextGenImages 183 | 184 | ## [0.9.0] - 30 November 2020 185 | ### Removed 186 | - Remove JavaScript check and Browser class 187 | - Moved code from this module to generic NextGenImages module 188 | - Remove Travis CI script 189 | 190 | ## [0.8.0] - 30 November 2020 191 | ### Fixed 192 | - Lazy loading configuration option was not working 193 | 194 | ### Added 195 | - Add new option for quality level 196 | 197 | ## [0.7.6] - 19 August 2020 198 | ### Fixed 199 | - Fixes wrong name in require-js config (@johannessmit) 200 | 201 | ## [0.7.5] - 13 August 2020 202 | ### Fixed 203 | - Add jQuery Cookie to prevent load order issues (@basvanpoppel) 204 | 205 | ## [0.7.4] - 3 August 2020 206 | ### Fixed 207 | - Image is correctly updated including the source (@johannessmit) 208 | 209 | ### Removed 210 | - Undo of `parse_url` Laminas replacement because this breaks pre-Laminas Magento releases 211 | 212 | ## [0.7.3] - 29 July 2020 213 | ### Added 214 | - Magento 2.4 support 215 | 216 | ### Fixed 217 | - Numerous PHPCS issues 218 | 219 | ### Added 220 | - URL parsing via laminas/laminas-uri package 221 | 222 | ## [0.7.2] - June 13th, 2020 223 | ### Fixed 224 | - Remove alt attribute from picture element (@gjportegies) 225 | 226 | ## [0.7.1] - April 6th, 2020 227 | ### Added 228 | - Quick fix to allow for WebP images in catalog swatches 229 | 230 | ## [0.7.0] - March 31st, 2020 231 | ### Added 232 | - Code refactoring to allow for Amasty Shopby compatibility 233 | 234 | ## [0.6.2] - March 18th, 2020 235 | ### Fixed 236 | - Skip captcha images (PR from @jasperzeinstra) 237 | 238 | ## [0.6.1] - March 18th, 2020 239 | ### Fixed 240 | - Do not throw error in debugging with non-existing images 241 | - Rename "Debug Log" to "Debugging" because that's what's happening 242 | 243 | ## [0.6.0] - March 7th, 2020 244 | ### Added 245 | - Skipping WebP image creation by configuration option 246 | 247 | ## [0.5.2] - March 5th, 2020 248 | ### Fixed 249 | - Fix next tag not being closed properly 250 | 251 | ## [0.5.1] - February 19th, 2020 252 | ### Fixed 253 | - Prevent overwriting existing `picture` tags 254 | 255 | ## [0.5.0] - February 11th, 2020 256 | ### Added 257 | - Upgraded rosell-dk/webp-convert library 258 | 259 | ## [0.4.7] - January 31st, 2020 260 | ### Added 261 | - Add class attribute in picture (PR from itsazzad) 262 | - Better support info 263 | - Raise framework requirements for proper support of ViewModels 264 | - Added logic for fetching the css class from the original image (PR from duckchip) 265 | - Added missing variable in the ReplaceTags plugin (PR from duckchip) 266 | 267 | ## [0.4.6] - November 23rd, 2019 268 | ### Fixed 269 | - Raise requirements for proper support of ViewModels 270 | 271 | ## [0.4.5] - October 16th, 2019 272 | ### Added 273 | - Add check for additional layout handle `webp_skip` 274 | 275 | ## [0.4.4] - October 15th, 2019 276 | ### Fixed 277 | - Dirty workaround for email layout 278 | 279 | ## [0.4.3] - October 4th, 2019 280 | ### Added 281 | - Add controller for email testing 282 | 283 | ### Fixed 284 | - Do not apply WebP if no handles 285 | 286 | ## [0.4.2] - July 14th, 2019 287 | ### Fixed 288 | - Make sure modified gallery images are returned as Collection, not an array 289 | - Test with Aimes_Notorama 290 | 291 | ## [0.4.1] - July 2019 292 | ### Fixed 293 | - Original tag (with custom styling) was not used in `picture` element, but new one was created instead 294 | 295 | ## [0.4.0] - July 2019 296 | ### Added 297 | - Move configuration to separate **Yireo** section 298 | - Add a `config.xml` file 299 | - Changed configuration path from `system/yireo_webp2/*` to `yireo_webp2/settings/*` 300 | - Move `quality_level` to `config.xml` 301 | 302 | ## [0.3.0] - 2019-05-02 303 | ### Fixed 304 | - Fix issue with additional images not being converted if already converted (@jove4015) 305 | - Fix issue with static versioning not being reckognized 306 | - Make sure src, width and height still remain in picture-tag 307 | 308 | ### Added 309 | - Integration test for multiple instances of same image 310 | - Add fields in backend for PHP version and module version 311 | - Integration Test to test conversion of test-files 312 | - Throw an exception of source file is not found 313 | - Add provider of dummy images 314 | - Add integration test of dummy images page 315 | - Add test page with dummy images 316 | - Only show original image in HTML source when debugging 317 | 318 | ## [0.2.0] - 2019-04-28 319 | ### Fixed 320 | - Fix issue with additional images not being converted if already converted 321 | - Make sure to enable cookie-check whenever FPC is enabled 322 | 323 | ### Added 324 | - Actual meaningful integration test for browsing product page 325 | 326 | ## [0.1.1] - 2019-04-12 327 | ### Fixed 328 | - Disable gallery fix if FPC is enabled 329 | 330 | ## [0.1.0] - 2019-04-12 331 | ### Added 332 | - Add GD checker in backend settings 333 | 334 | ## [0.0.3] - 2019-03-21 335 | ### Fixed 336 | - Fix for Fotorama gallery 337 | - Check via timestamps for new and modified files 338 | 339 | ### Added 340 | - Check for browser support via cookie and Chrome-check 341 | - Inspect ACCEPT header for image/webp support 342 | - Implement detect.js script to detect WebP support and set a cookie 343 | - Add configuration values 344 | 345 | ## [0.0.2] - 2019-03-20 346 | ### Added 347 | - Temporary release for CI purpose 348 | 349 | ## [0.0.1] - 2019-03-20 350 | ### Added 351 | - Initial commit 352 | - Support for regular img-tags to picture-tags conversion 353 | -------------------------------------------------------------------------------- /Config/Config.php: -------------------------------------------------------------------------------- 1 | scopeConfig = $scopeConfig; 43 | $this->storeManager = $storeManager; 44 | $this->nextGenImagesConfig = $nextGenImagesConfig; 45 | } 46 | 47 | /** 48 | * @return bool 49 | */ 50 | public function enabled(): bool 51 | { 52 | return (bool)$this->getValue('yireo_webp2/settings/enabled'); 53 | } 54 | 55 | /** 56 | * @return bool 57 | */ 58 | public function allowImageCreation(): bool 59 | { 60 | return $this->nextGenImagesConfig->allowImageCreation(); 61 | } 62 | 63 | /** 64 | * @return int 65 | */ 66 | public function getQualityLevel(): int 67 | { 68 | $qualityLevel = (int)$this->getValue('yireo_webp2/settings/quality_level'); 69 | if ($qualityLevel > 100) { 70 | return 100; 71 | } 72 | 73 | if ($qualityLevel < 1) { 74 | return 1; 75 | } 76 | 77 | return $qualityLevel; 78 | } 79 | 80 | /** 81 | * @return string[] 82 | * @throws InvalidConvertorException 83 | */ 84 | public function getConvertors(): array 85 | { 86 | $allConvertors = ['cwebp', 'gd', 'imagick', 'wpc', 'ewww']; 87 | $storedConvertors = $this->getValue('yireo_webp2/settings/convertors'); 88 | $storedConvertors = $this->stringToArray((string)$storedConvertors); 89 | if (empty($storedConvertors)) { 90 | return $allConvertors; 91 | } 92 | 93 | foreach ($storedConvertors as $storedConvertor) { 94 | if (!in_array($storedConvertor, $allConvertors)) { 95 | throw new InvalidConvertorException('Invalid convertor: "' . $storedConvertor . '"'); 96 | } 97 | } 98 | 99 | return $storedConvertors; 100 | } 101 | 102 | /** 103 | * @return string 104 | * @throws InvalidConvertorException 105 | */ 106 | public function getEncoding(): string 107 | { 108 | $allEncoding = ['lossy', 'lossless', 'auto']; 109 | $storedEncoding = (string)$this->getValue('yireo_webp2/settings/encoding'); 110 | if (empty($storedEncoding)) { 111 | return 'lossy'; 112 | } 113 | 114 | if (!in_array($storedEncoding, $allEncoding)) { 115 | throw new InvalidConvertorException('Invalid encoding: "' . $storedEncoding . '"'); 116 | } 117 | 118 | return $storedEncoding; 119 | } 120 | 121 | /** 122 | * @param string $path 123 | * @return mixed 124 | */ 125 | private function getValue(string $path) 126 | { 127 | try { 128 | return $this->scopeConfig->getValue( 129 | $path, 130 | ScopeInterface::SCOPE_STORE, 131 | $this->storeManager->getStore() 132 | ); 133 | } catch (NoSuchEntityException $e) { 134 | return null; 135 | } 136 | } 137 | 138 | /** 139 | * @param string $string 140 | * @return array 141 | */ 142 | private function stringToArray(string $string): array 143 | { 144 | $array = []; 145 | $strings = explode(',', $string); 146 | foreach ($strings as $string) { 147 | $string = trim($string); 148 | if ($string) { 149 | $array[] = $string; 150 | } 151 | } 152 | 153 | return $array; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /Config/Frontend/Funding.php: -------------------------------------------------------------------------------- 1 | toHtml(); 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Controller/Test/Images.php: -------------------------------------------------------------------------------- 1 | pageFactory = $pageFactory; 30 | } 31 | 32 | /** 33 | * @return Page 34 | */ 35 | public function execute() 36 | { 37 | $page = $this->pageFactory->create(); 38 | 39 | $case = strtolower((string)$this->_request->getParam('case')); 40 | $case = preg_replace('/([^a-z\_]+)/', '', $case); 41 | $handle = 'webp_test_images_' . $case; 42 | $page->addHandle($handle); 43 | 44 | return $page; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Controller/Test/Mail.php: -------------------------------------------------------------------------------- 1 | transportBuilder = $transportBuilder; 83 | $this->storeManager = $storeManager; 84 | $this->layoutFactory = $layoutFactory; 85 | $this->request = $request; 86 | $this->jsonFactory = $jsonFactory; 87 | $this->scopeConfig = $scopeConfig; 88 | $this->config = $config; 89 | } 90 | 91 | /** 92 | * @return ResultInterface 93 | * @throws LocalizedException 94 | * @throws MailException 95 | * @throws NoSuchEntityException 96 | */ 97 | public function execute(): ResultInterface 98 | { 99 | $token = (string)$this->request->getParam('token'); 100 | $cryptKey = (string)$this->config->get('crypt/key'); 101 | if ($token === $cryptKey) { 102 | return $this->sendResult(['msg' => 'Invalid token']); 103 | } 104 | 105 | $emailTemplate = (string)$this->request->getParam('email'); 106 | 107 | if (empty($emailTemplate)) { 108 | $emailTemplate = 'sales_email_invoice_template'; 109 | } 110 | 111 | $receiverInfo = [ 112 | 'name' => $this->scopeConfig->getValue('trans_email_ident/general/name'), 113 | 'email' => $this->scopeConfig->getValue('trans_email_ident/general/email'), 114 | ]; 115 | 116 | $senderInfo = [ 117 | 'name' => $this->scopeConfig->getValue('trans_email_ident/general/name'), 118 | 'email' => $this->scopeConfig->getValue('trans_email_ident/general/email'), 119 | ]; 120 | 121 | $data = [ 122 | 'template' => $emailTemplate, 123 | 'sender' => $senderInfo, 124 | 'receiver' => $receiverInfo 125 | ]; 126 | 127 | $variables = []; 128 | $this->transportBuilder->setTemplateIdentifier($emailTemplate) 129 | ->setTemplateOptions( 130 | [ 131 | 'area' => Area::AREA_FRONTEND, 132 | 'store' => $this->storeManager->getStore()->getId(), 133 | ] 134 | ) 135 | ->setTemplateVars($variables) 136 | ->setFrom($senderInfo) 137 | ->addTo($receiverInfo['email'], $receiverInfo['name']); 138 | 139 | $transport = $this->transportBuilder->getTransport(); 140 | $transport->sendMessage(); 141 | $data['msg'] = 'Email sent'; 142 | 143 | return $this->sendResult($data); 144 | } 145 | 146 | /** 147 | * @param mixed[] $data 148 | * @return ResultInterface 149 | */ 150 | private function sendResult(array $data): ResultInterface 151 | { 152 | $jsonResult = $this->jsonFactory->create(); 153 | $jsonResult->setData($data); 154 | return $jsonResult; 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /Convertor/ConvertWrapper.php: -------------------------------------------------------------------------------- 1 | config = $config; 38 | $this->logger = $logger; 39 | } 40 | 41 | /** 42 | * @param string $sourceImageFilename 43 | * @param string $destinationImageFilename 44 | * @throws ConversionFailedException 45 | * @throws InvalidConvertorException 46 | * @throws InvalidImageTypeException 47 | */ 48 | public function convert(string $sourceImageFilename, string $destinationImageFilename): void 49 | { 50 | $options = $this->getOptions(); 51 | foreach ($this->config->getConvertors() as $convertor){ 52 | $options['converter'] = $convertor; 53 | try { 54 | WebPConvert::convert($sourceImageFilename, $destinationImageFilename, $options); 55 | } catch (ConversionFailedException $e) { 56 | $this->logger->debug($e->getMessage() . ' - ' . $e->description, $e->getTrace()); 57 | continue; 58 | } catch (\Exception $e) { 59 | $this->logger->debug($e->getMessage(), $e->getTrace()); 60 | continue; 61 | } 62 | break; 63 | } 64 | } 65 | 66 | /** 67 | * @return array 68 | * @throws InvalidConvertorException 69 | */ 70 | public function getOptions(): array 71 | { 72 | return [ 73 | 'quality' => 'auto', 74 | 'max-quality' => $this->config->getQualityLevel(), 75 | 'encoding' => $this->config->getEncoding(), 76 | ]; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Convertor/Convertor.php: -------------------------------------------------------------------------------- 1 | config = $config; 55 | $this->imageFile = $imageFile; 56 | $this->convertWrapper = $convertWrapper; 57 | $this->targetImageFactory = $targetImageFactory; 58 | } 59 | 60 | /** 61 | * @param Image $image 62 | * @return Image 63 | * @throws ConvertorException 64 | * @throws FileSystemException 65 | */ 66 | public function convertImage(Image $image): Image 67 | { 68 | if (!$this->config->enabled()) { 69 | throw new ConvertorException('WebP conversion is not enabled'); 70 | } 71 | 72 | if (!in_array($image->getMimetype(), ['image/jpeg', 'image/jpg', 'image/png'])) { 73 | throw new ConvertorException('The mimetype "'.$image->getMimetype().'" is not supported'); 74 | } 75 | 76 | // @todo: https://gitlab.hyva.io/hyva-themes/hyva-compat/magento2-yireo-next-gen-images/-/blob/main/src/Plugin/ConverterPlugin.php#L50 77 | 78 | $webpImage = $this->targetImageFactory->create($image, 'webp'); 79 | $result = $this->convert($image->getPath(), $webpImage->getPath()); 80 | 81 | if (!$result && !$this->imageFile->fileExists($webpImage->getPath())) { 82 | throw new ConvertorException('WebP path "'.$webpImage->getPath().'" does not exist after conversion'); 83 | } 84 | 85 | return $webpImage; 86 | } 87 | 88 | /** 89 | * @param string $sourceImagePath 90 | * @param string $targetImagePath 91 | * @return bool 92 | * @throws ConvertorException 93 | */ 94 | private function convert(string $sourceImagePath, string $targetImagePath): bool 95 | { 96 | if (!$this->imageFile->fileExists($sourceImagePath)) { 97 | throw new ConvertorException('Source cached image does not exists: '.$sourceImagePath); 98 | } 99 | 100 | if (!$this->imageFile->needsConversion($sourceImagePath, $targetImagePath)) { 101 | return true; 102 | } 103 | 104 | if (!$this->config->enabled() || !$this->config->allowImageCreation()) { 105 | throw new ConvertorException('WebP conversion is not enabled'); 106 | } 107 | 108 | try { 109 | $this->convertWrapper->convert($sourceImagePath, $targetImagePath); 110 | } catch (InvalidImageTypeException|InvalidInputException|InvalidInputImageTypeException $e) { 111 | return false; 112 | } catch (ConversionFailedException|InvalidConvertorException $e) { 113 | throw new ConvertorException($targetImagePath.': '.$e->getMessage()); 114 | } 115 | 116 | return true; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /Exception/InvalidConvertorException.php: -------------------------------------------------------------------------------- 1 | " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. 48 | -------------------------------------------------------------------------------- /Model/Config/Source/Encoding.php: -------------------------------------------------------------------------------- 1 | 'lossy', 'label' => 'Lossy'], 13 | ['value' => 'lossless', 'label' => 'Lossless'], 14 | ['value' => 'auto', 'label' => 'Auto (both lossy and lossless)'], 15 | ]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Plugin/AddCspInlineScripts.php: -------------------------------------------------------------------------------- 1 | replaceInlineScripts = $replaceInlineScripts; 16 | } 17 | 18 | public function afterToHtml(Template $block, $html): string 19 | { 20 | if (false === strstr((string)$block->getNameInLayout(), 'yireo_webp2.')) { 21 | return (string)$html; 22 | } 23 | 24 | return $this->replaceInlineScripts->replace((string)$html); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Magento 2 module for WebP 2 | 3 | 4 | **This module adds WebP support to Magento 2.** 5 | 6 | ## About this module 7 | - When `` tags are found on the page, the corresponding JPG or PNG is converted into WebP and a corresponding `` tag. 8 | - The Fotorama gallery of the Magento core product pages is replaced with WebP images without issues as well. However, the Fotorama effect loads new JPG images again, replacing the original `` tag. This shows that the Fotorama library is not scalable and may be a bad decision to use. We recommend you replace it with the [Notorama](https://github.com/robaimes/module-notorama) module instead. 9 | 10 | > [!WARNING] 11 | > Hyvä support is built into the latest versions of this module. Please do not use the deprecated compatibility module anymore. 12 | 13 | ## Instructions for using composer 14 | Use composer to install this extension. Not using composer is **not** supported. Next, install the new module plus its dependency `Yireo_NextGenImages` into Magento itself: 15 | 16 | ```bash 17 | composer require yireo/magento2-webp2 18 | bin/magento module:enable Yireo_Webp2 Yireo_NextGenImages 19 | bin/magento setup:upgrade 20 | ``` 21 | 22 | Enable the module by toggling the setting in **Stores > Configuration > Yireo > Yireo WebP > Enabled**. 23 | 24 | ## System requirements 25 | Make sure your PHP environment supports WebP: This means that the function `imagewebp` should exist in PHP. We hope to add 26 | more checks for this in the extension itself soon. For now, just open up a PHP `phpinfo()` page and check for WebP 27 | support. Please note that installing `libwebp` on your system is not the same as having PHP support WebP. Check the 28 | `phpinfo()` file and add new PHP modules to PHP if needed. If in doubt, simple create a PHP script `test.php` and a line 29 | `` tag should be replaced with a `` tag that lists both the old image and the new WebP image. If the conversion from the old image to WebP goes well. 46 | 47 | You can expect the HTML to be changed, so inspecting the HTML source gives a good impression. You can also use the Error Console to inspect network traffic: If some `webp` images are flying be in a default Magento environment, this usually proofs that the extension is working to some extent. 48 | 49 | #### My CPU usage goes up. Is that normal? 50 | Yes, it is normal. This extension does two things: It shows a WebP on the frontend of your shop. And it 51 | generates that WebP when it is missing. Obviously, generating an image takes up system resources. And if 52 | you have a large catalog, it is going to do more time. How much time? Do make sure to calculate this 53 | yourself: Take an image, resize it using the `cwebp` binary and measure the time - multiply it by how many 54 | images there are. This should give a fair estimation on how much time is needed. 55 | 56 | Note that this extension allows for using various mechanisms (aka *convertors*). Tune the **Convertors** 57 | settings if you want to try to optimize things. Sometimes, GD is faster than `cwebp`. Sometimes, GD just 58 | breaks things. It depends, so you need to pick upon the responsibility to try this in your specific 59 | environment. 60 | 61 | Also note that this extension allows for setting an *encoding*. The default is `auto` which creates both a lossy and a lossless WebP and then picks the smallest one. Things could be twice as fast by setting this to `lossy`. 62 | 63 | If you don't like the generation of images at all, you could also use other CLI tools instead. 64 | 65 | #### Class 'WebPConvert\WebPConvert' not found 66 | We only support the installation of our Magento 2 extensions, if they are installed via `composer`. Please note that - as we see it - `composer` is the only way for managing Magento depedencies. If you want to install the extension manually in `app/code`, please study the contents of `cmoposer.json` to install all dependencies of this module manually as well. 67 | 68 | #### After installation, I'm still seeing only PNG and JPEG images 69 | This could mean that the conversion failed. New WebP images are stored in the same path as the original path (somewhere in `pub/`) which means that all folders need to be writable by the webserver. Specifically, if your deployment is based on artifacts, this could be an issue. 70 | 71 | Also make sure that your PHP environment is capable of WebP: The function `imagewebp` should exist in PHP and we recommend a `cwebp` binary to be placed in `/usr/local/bin/`. 72 | 73 | Last but not least, WebP images only work in WebP-capable browsers. The extension detects the browser support. Make sure to test this in Chrome first, which natively supports WebP. 74 | 75 | #### Warning: filesize(): stat failed for xxx.webp 76 | If you are seeing this issue in the `exception.log` and/or `system.log`, 77 | do make sure to wipe out Magento caching and do make sure that the WebP 78 | file in question is accessible: The webserver running Magento should have 79 | read access to the file. Likewise, if you want this extension to 80 | automatically convert a JPEG into WebP, do make sure that the folder 81 | containing the JPEG is writable. 82 | 83 | #### Some of the images are converted, but others are not. 84 | Not all JPEG and PNG images are fit for conversion to WebP. In the past, WebP has had issues with alpha-transparency and partial transparency. If the WebP image can't be generated by our extension, it is not generated. Simple as that. If some images are converted but some are not, try to upload those to online conversion tools to see if they work. 85 | 86 | Make sure your `cwebp` binary and PHP environment are up-to-date. 87 | 88 | #### This sucks. It only works in some browsers. 89 | Don't complain to us. Instead, ask the other browser vendors to support this as well. And don't say this 90 | is not worth implementing, because I bet more than 25% of your sites visitors will benefit from WebP. Not 91 | offering this to them, is wasting additional bandwidth. 92 | 93 | #### Some emails are also displaying WebP 94 | It could be that your transactional email templates are including XML layout handles that suddenly introduce this extensions functionality, while actually adding WebP to emails is a bad idea (because most email clients will not support anything of the like). 95 | 96 | If you encounter such an email, find out which XML layout handle is the cause of this (`{handle layout="foobar"}`). Next, create a new XML layout file with that name (`foobar.xml`) and call the `webp_skip` handle from it (``). So this instructs the WebP extension to skip loading itself. 97 | 98 | #### error while loading shared libraries: libjpeg.so.8: cannot open shared object file: No such file or directory 99 | Ask your system administrator to install this library. Or ask the system administrator to install WebP support in PHP by upgrading PHP itself to the right version and to include the right PHP modules (like imagemagick). Or skip converting WebP images by disabling the setting in our extension and then convert all WebP images by hand. 100 | 101 | #### Can I use this with Amasty Shopby? 102 | Yes, you can. Make sure to install the addition https://github.com/yireo/Yireo_Webp2ForAmastyShopby as well. 103 | 104 | #### How can I convert WebP images manually from the CLI? 105 | Even though this extension (or actually its parent extension `Yireo_NextGenImages`) support a CLI (`bin/magento next-gen-images:convert`), using this extension for 1000s of images will definitely not be performant. If you want to convert all images at once from the CLI, it is better to look at other tools. For instance, the `cwebp` binary (part of the Google WebP project itself) could be installed. Or perhaps you could use `convert` of the Imagick project. 106 | 107 | Next, a simple shell script could be used to build all WebP files: 108 | ```bash 109 | find . -type f -name \*.jpg | while read IMAGE do; convert $IMAGE ${IMAGE/.jpg/.webp}; done 110 | ``` 111 | 112 | Or another example (of @rostilos): 113 | ```bash 114 | #!/bin/bash 115 | start=`date +%s` 116 | directory="../pub/media" 117 | 118 | cd "$directory" || exit 119 | find . -type f \( -iname \*.jpg -o -iname \*.jpeg -o -iname \*.png \) -print0 | 120 | 121 | while IFS= read -r -d $'\0' file; 122 | do 123 | filename=$(basename -- "$file") 124 | new_filename="${filename%.*}.webp" 125 | new_filepath="$(dirname "$file")/$new_filename" 126 | echo "Converting: $file -> $new_filepath" 127 | cwebp -q 80 -quiet "$file" -o "$new_filepath" 128 | done 129 | end=`date +%s` 130 | runtime=$((end-start)) 131 | 132 | echo "Execution completed in $runtime seconds." 133 | ``` 134 | 135 | ## Requesting support 136 | 137 | ### First check to see if our extension is doing its job 138 | Before requesting support, please make sure that you properly check whether this extension is working or not. Do not look at your browser and definitely do not use third party SEO tools to make any conclusions. Instead, inspect the HTML source in your browser. Our extension modifies the HTML so that regular `` tags are replaced with something similar to the following: 139 | ```html 140 | 141 | 142 | 143 | 144 | 145 | ``` 146 | 147 | If similar HTML is there, but your browser is not showing the WebP image, then realize that this is not due to our extension, but due to your browser. Unfortunately, we are not browser manufacturers and we can't change this. Refer to https://caniuse.com/#search=webp instead. 148 | 149 | ### Opening an issue for this extension 150 | Feel free to open an **Issue** in the GitHub project of this extension. However, do make sure to be thorough and provide as many details as you can: 151 | 152 | - What browser did you test this with? 153 | - What is your Magento version? 154 | - What is your PHP version? 155 | - Did you make sure to use `composer` to install all dependencies? 156 | - Not using `composer` is **not** supported. 157 | - Which specific composer version of the Yireo WebP2 extension did you install? 158 | - Which specific composer version of the Yireo NextGenImages extension did you install? 159 | - Have you tested this after flushing all caches, especially the Full Page Cache? 160 | - Have you tested this after disabling all caches, especially the Full Page Cache? 161 | - The Full Page Cache will prevent you from seeing dynamic results. The Full Page Cache works with our extension, it just pointless to troubleshoot things with FPC enabled, unless you are troubleshooting FPC itself. 162 | - Are you testing this in the Developer Mode or in the Production Mode? 163 | - We recommend you to use the Developer Mode. Do not use the Default Mode anywhere. Do not use the Production Mode to make modifications to Magento. 164 | - Under **Stores > Configuration > Yireo > Yireo WebP2** and **Stores > Configuration > Yireo > Yireo NextGenImages**, what settings do you see with which values? 165 | - Preferably post a screenshot with the settings. 166 | - Could you supply a URL to a live demo? 167 | - Could you please supply a snapshot of the HTML source of a product page? 168 | 169 | Please note that we do not support Windows to be used to run Magento. Magento itself is not supporting Windows either. If you are stuck with Windows, make sure to use the WSL (Windows Subsystem for Linux) and use the Linux layer instead. 170 | 171 | If the WebP configuration section is showing in the backend, but the HTML source in the frontend is not modified, please send the output of the command `bin/magento dev:di:info "\Magento\Framework\View\LayoutInterface"`. 172 | 173 | ### Issues with specific images 174 | If some images are converted but others are not, please supply the following details: 175 | 176 | - The output of the command `bin/magento next-gen-images:test-uri $URL` where `$URL` is the URL to the original image (JPG or PNG) 177 | - The output of the command `bin/magento next-gen-images:convert $PATH` where `$PATH` is the absolute path to the original image (JPG or PNG) 178 | - Whether or not you are using a CDN for serving images. 179 | -------------------------------------------------------------------------------- /Setup/UpgradeData.php: -------------------------------------------------------------------------------- 1 | configCollectionFactory = $configCollectionFactory; 35 | $this->storageWriter = $storageWriter; 36 | } 37 | 38 | /** 39 | * @param ModuleDataSetupInterface $setup 40 | * @param ModuleContextInterface $context 41 | * @return void 42 | */ 43 | public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) 44 | { 45 | $setup->startSetup(); 46 | 47 | $oldPath = 'system/yireo_webp/'; 48 | $newPath = 'yireo_webp2/settings/'; 49 | 50 | $configCollection = $this->configCollectionFactory->create(); 51 | $configCollection->addFieldToFilter('path', ['like' => $oldPath . '%']); 52 | $items = $configCollection->getItems(); 53 | 54 | foreach ($items as $item) { 55 | $data = $item->getData(); 56 | $this->storageWriter->delete($data['path'], $data['scope'], $data['scope_id']); 57 | $newPath = str_replace($oldPath, $newPath, $data['path']); 58 | $this->storageWriter->save($newPath, $data['value'], $data['scope'], $data['scope_id']); 59 | } 60 | 61 | $setup->endSetup(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Test/Integration/Common.php: -------------------------------------------------------------------------------- 1 | _objectManager->get(ConvertWrapperStub::class); 20 | $this->_objectManager->addSharedInstance($convertWrapperStub, ConvertWrapper::class); 21 | } 22 | 23 | /** 24 | * @return string[] 25 | */ 26 | protected function fixtureImageFiles(): array 27 | { 28 | // @todo: It would be cleaner to use the sandbox directory for this 29 | /** @var DirectoryList $directoryList */ 30 | $directoryList = $this->_objectManager->get(DirectoryList::class); 31 | 32 | $root = $directoryList->getRoot(); 33 | $imagesInThemePath = $root . '/pub/static/frontend/Magento/luma/en_US/Yireo_Webp2/images/test'; 34 | 35 | if (!is_dir($imagesInThemePath)) { 36 | mkdir($imagesInThemePath, 0777, true); 37 | } 38 | 39 | if (!is_dir($imagesInThemePath)) { 40 | throw new RuntimeException('Failed to create folder: ' . $imagesInThemePath); 41 | } 42 | 43 | $currentFiles = scandir($imagesInThemePath); 44 | foreach ($currentFiles as $currentFile) { 45 | if (!in_array($currentFile, ['.', '..'])) { 46 | unlink($imagesInThemePath . '/' . $currentFile); 47 | } 48 | } 49 | 50 | /** @var ImageProvider $imageProvider */ 51 | $imageProvider = $this->_objectManager->get(ImageProvider::class); 52 | $images = $imageProvider->getImages(); 53 | 54 | /** @var ComponentRegistrar $componentRegistrar */ 55 | $componentRegistrar = $this->_objectManager->get(ComponentRegistrar::class); 56 | $modulePath = $componentRegistrar->getPath('module', 'Yireo_Webp2'); 57 | $moduleWebPath = $modulePath . '/view/frontend/web'; 58 | 59 | foreach ($images as $image) { 60 | $sourceImage = $moduleWebPath . '/' . $image; 61 | $destinationImage = $imagesInThemePath . '/' . basename($image); 62 | copy($sourceImage, $destinationImage); 63 | } 64 | 65 | return glob($root . '/pub/static/frontend/Magento/luma/en_US/Yireo_Webp2/images/test/*'); 66 | } 67 | 68 | /** 69 | * @return ImageProvider 70 | */ 71 | protected function getImageProvider(): ImageProvider 72 | { 73 | return $this->_objectManager->get(ImageProvider::class); 74 | } 75 | 76 | /** 77 | * @param string $body 78 | * @param array $images 79 | */ 80 | protected function assertImageTagsExist(string $body, array $images) 81 | { 82 | $layout = $this->_objectManager->get(LayoutInterface::class); 83 | $blocks = $layout->getChildBlocks('main'); 84 | $html = ''; 85 | foreach ($blocks as $block) { 86 | $html .= $block->toHtml(); 87 | } 88 | 89 | foreach ($images as $image) { 90 | $webPImage = preg_replace('/\.(png|jpg)$/', '.webp', $image); 91 | $debugMsg = 'Asserting that body contains "' . $webPImage . '": ' . $html; 92 | $this->assertTrue((bool)strpos($body, $webPImage), $debugMsg); 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /Test/Integration/ImageConversionTest.php: -------------------------------------------------------------------------------- 1 | fixtureImageFiles(); 19 | $imagePath = $images[0]; 20 | $image = $this->_objectManager->get(ImageFactory::class)->createFromPath($imagePath); 21 | $convertor = $this->_objectManager->get(Convertor::class); 22 | $convertedImage = $convertor->convertImage($image); 23 | $this->assertNotEmpty($convertedImage->getPath()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Test/Integration/ImageWithCustomStyleTest.php: -------------------------------------------------------------------------------- 1 | fixtureImageFiles(); 20 | 21 | $this->getRequest()->setParam('case', 'image_with_custom_style'); 22 | $this->dispatch('webp/test/images'); 23 | $this->assertSame('image_with_custom_style', $this->getRequest()->getParam('case')); 24 | $this->assertSame(200, $this->getResponse()->getHttpResponseCode()); 25 | 26 | $body = $this->getResponse()->getContent(); 27 | $this->assertImageTagsExist($body, [$this->getImageProvider()->getImage()]); 28 | $this->assertTrue((bool)strpos($body, 'type="image/webp"')); 29 | 30 | if (!getenv('TRAVIS')) { 31 | $this->assertTrue((bool)strpos($body, 'style="display:insane; opacity:666;"')); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Test/Integration/ModuleTest.php: -------------------------------------------------------------------------------- 1 | getPaths(ComponentRegistrar::MODULE); 19 | $this->assertArrayHasKey('Yireo_Webp2', $paths); 20 | } 21 | 22 | /** 23 | * Test if the module is known and enabled 24 | */ 25 | public function testIfModuleIsKnownAndEnabled() 26 | { 27 | $objectManager = Bootstrap::getObjectManager(); 28 | $moduleList = $objectManager->create(ModuleList::class); 29 | $this->assertTrue($moduleList->has('Yireo_NextGenImages')); 30 | $this->assertTrue($moduleList->has('Yireo_Webp2')); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Test/Integration/MultipleImagesSameTest.php: -------------------------------------------------------------------------------- 1 | fixtureImageFiles(); 18 | 19 | $this->getRequest()->setParam('case', 'multiple_images_same'); 20 | $this->dispatch('webp/test/images'); 21 | $this->assertSame('multiple_images_same', $this->getRequest()->getParam('case')); 22 | $this->assertSame(200, $this->getResponse()->getHttpResponseCode()); 23 | 24 | $body = $this->getResponse()->getContent(); 25 | 26 | $this->assertImageTagsExist($body, [$this->getImageProvider()->getImage()]); 27 | $this->assertTrue((bool)strpos($body, 'type="image/webp"')); 28 | 29 | if (!getenv('TRAVIS')) { 30 | $this->assertImageTagsExist($body, [$this->getImageProvider()->getImage()]); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Test/Integration/MultipleImagesTest.php: -------------------------------------------------------------------------------- 1 | fixtureImageFiles(); 16 | 17 | $this->getRequest()->setParam('case', 'multiple_images'); 18 | $this->dispatch('webp/test/images'); 19 | $this->assertSame('multiple_images', $this->getRequest()->getParam('case')); 20 | $this->assertSame(200, $this->getResponse()->getHttpResponseCode()); 21 | 22 | $body = $this->getResponse()->getBody(); 23 | $this->assertImageTagsExist($body, [$this->getImageProvider()->getImage()]); 24 | $this->assertTrue((bool)strpos($body, 'type="image/webp"')); 25 | 26 | if (!getenv('TRAVIS')) { 27 | $this->assertImageTagsExist($body, $this->getImageProvider()->getImages()); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Test/Unit/Config/ConfigTest.php: -------------------------------------------------------------------------------- 1 | createMock(ScopeConfigInterface::class); 16 | $storeManager = $this->createMock(StoreManagerInterface::class); 17 | $nextGenImagesConfig = $this->createMock(NextGenImagesConfig::class); 18 | $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); 19 | $this->assertFalse($config->enabled()); 20 | 21 | $scopeConfig->method('getValue')->willReturn(1); 22 | $this->assertTrue($config->enabled()); 23 | } 24 | 25 | public function testGetQualityLevel() 26 | { 27 | $scopeConfig = $this->createMock(ScopeConfigInterface::class); 28 | $storeManager = $this->createMock(StoreManagerInterface::class); 29 | $nextGenImagesConfig = $this->createMock(NextGenImagesConfig::class); 30 | $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); 31 | $this->assertEquals(1, $config->getQualityLevel()); 32 | 33 | $scopeConfig = $this->createMock(ScopeConfigInterface::class); 34 | $scopeConfig->method('getValue')->willReturn(42); 35 | $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); 36 | $this->assertEquals(42, $config->getQualityLevel()); 37 | 38 | $scopeConfig = $this->createMock(ScopeConfigInterface::class); 39 | $scopeConfig->method('getValue')->willReturn(142); 40 | $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); 41 | $this->assertEquals(100, $config->getQualityLevel()); 42 | 43 | $scopeConfig = $this->createMock(ScopeConfigInterface::class); 44 | $scopeConfig->method('getValue')->willReturn(0); 45 | $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); 46 | $this->assertEquals(1, $config->getQualityLevel()); 47 | } 48 | 49 | public function testGetConvertors() 50 | { 51 | $scopeConfig = $this->createMock(ScopeConfigInterface::class); 52 | $storeManager = $this->createMock(StoreManagerInterface::class); 53 | $nextGenImagesConfig = $this->createMock(NextGenImagesConfig::class); 54 | $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); 55 | $this->assertNotEmpty($config->getConvertors()); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Test/Unit/Convertor/ConvertorTest.php: -------------------------------------------------------------------------------- 1 | createMock(Config::class); 22 | $config->method('enabled')->willReturn(true); 23 | $convertor = $this->getConvertor($config); 24 | 25 | $this->expectException(ConvertorException::class); 26 | $image = new Image('/tmp/pub/test/foobar.jpg', '/test/foobar.jpg'); 27 | $this->assertEquals('/test/foobar.webp', $convertor->convertImage($image)); 28 | } 29 | 30 | /** 31 | * Test for Yireo\Webp2\Convertor\Convertor::convertImage 32 | */ 33 | public function testConvert() 34 | { 35 | $convertor = $this->getConvertor(); 36 | $this->expectException(ConvertorException::class); 37 | $image = new Image('/tmp/pub/test/foobar.jpg', '/test/foobar.jpg'); 38 | $convertor->convertImage($image); 39 | } 40 | 41 | /** 42 | * @param Config|null $config 43 | * @return Convertor 44 | */ 45 | private function getConvertor(?Config $config = null): Convertor 46 | { 47 | if (!$config) { 48 | $config = $this->createMock(Config::class); 49 | } 50 | 51 | $file = $this->createMock(File::class); 52 | $convertWrapper = $this->createMock(ConvertWrapper::class); 53 | $targetImageFactory = $this->createMock(TargetImageFactory::class); 54 | 55 | return new Convertor( 56 | $config, 57 | $file, 58 | $convertWrapper, 59 | $targetImageFactory 60 | ); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Test/Utils/ConvertWrapperStub.php: -------------------------------------------------------------------------------- 1 | getImages(); 28 | return $images[0]; 29 | } 30 | 31 | /** 32 | * @return string 33 | */ 34 | public function getNonExistingImage(): string 35 | { 36 | return 'images/test/non-existing.jpg'; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "yireo/magento2-webp2", 3 | "license": "OSL-3.0", 4 | "version": "0.14.3", 5 | "type": "magento2-module", 6 | "homepage": "https://www.yireo.com/software/magento-extensions/webp2", 7 | "description": "Magento 2 module to add WebP support to the Magento frontend", 8 | "keywords": [ 9 | "composer-installer", 10 | "magento", 11 | "Magento 2", 12 | "Exception", 13 | "Yireo" 14 | ], 15 | "authors": [ 16 | { 17 | "name": "Jisse Reitsma (Yireo)", 18 | "email": "jisse@yireo.com" 19 | } 20 | ], 21 | "require": { 22 | "yireo/magento2-next-gen-images": "~0.3", 23 | "yireo/magento2-csp-utilities": "^1.0", 24 | "magento/framework": "^101.0.1|^101.1|^102.0|^103.0", 25 | "magento/module-backend": "^100.0|^101.0|^102.0", 26 | "magento/module-config": "^101.0", 27 | "magento/module-store": "^101.0", 28 | "rosell-dk/webp-convert": "^2.0", 29 | "psr/log": "^1 || ^2 || ^3", 30 | "php": ">=7.4.0", 31 | "ext-json": "*", 32 | "ext-pcre": "*", 33 | "ext-gd": "*" 34 | }, 35 | "require-dev": { 36 | "phpunit/phpunit": "^9.0|^10.0|^11.0", 37 | "phpstan/phpstan": "^0.12.32", 38 | "bitexpert/phpstan-magento": "^0.3.0", 39 | "yireo/magento2-integration-test-helper": "^0.0.8" 40 | }, 41 | "suggest": { 42 | "yireo/magento2-webp2-for-hyva": "Additional fixes with Yireo Webp2 for Hyva", 43 | "yireo/magento2-webp2-graph-ql": "GraphQL endpoints for Yireo Webp2" 44 | }, 45 | "autoload": { 46 | "psr-4": { 47 | "Yireo\\Webp2\\": "" 48 | }, 49 | "files": [ 50 | "registration.php" 51 | ] 52 | }, 53 | "funding": [ 54 | { 55 | "type": "github", 56 | "url": "https://github.com/sponsors/jissereitsma" 57 | }, 58 | { 59 | "type": "github", 60 | "url": "https://github.com/sponsors/yireo" 61 | }, 62 | { 63 | "type": "paypal", 64 | "url": "https://www.paypal.me/yireo" 65 | }, 66 | { 67 | "type": "other", 68 | "url": "https://www.buymeacoffee.com/jissereitsma" 69 | } 70 | ] 71 | } 72 | -------------------------------------------------------------------------------- /etc/acl.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /etc/adminhtml/system.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | yireo 10 | Yireo_Webp2::config 11 | 12 | 13 | 14 | 15 | Yireo\Webp2\Config\Frontend\Funding 16 | 17 | 18 | 19 | Magento\Config\Model\Config\Source\Yesno 20 | 21 | 22 | 23 | 24 | 25 | 1 26 | 27 | 28 | 29 | 30 | Yireo\Webp2\VirtualType\Block\Adminhtml\System\Config\ModuleVersion 31 | 32 | 1 33 | 34 | 35 | 36 | 37 | 38 | 39 | 1 40 | 41 | 42 | 43 | 44 | Yireo\Webp2\Model\Config\Source\Encoding 45 | 46 | 47 | 1 48 | 49 | 50 | 51 |
52 |
53 |
54 | -------------------------------------------------------------------------------- /etc/config.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 1 16 | 80 17 | cwebp,gd,imagick,wpc,ewww 18 | lossy 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /etc/di.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | Yireo\Webp2\Convertor\Convertor 8 | 9 | 10 | 11 | 12 | 13 | 14 | Yireo_Webp2 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /etc/frontend/di.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /etc/frontend/routes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /etc/module.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | excludePaths: 3 | - */Test/*/* 4 | -------------------------------------------------------------------------------- /registration.php: -------------------------------------------------------------------------------- 1 | 3 |
4 | 10 |
11 |

Consider sponsoring this extension

12 |

13 | This extension is totally free. It takes time to develop and maintain though, all on a voluntary basis. 14 | If you are using this extension in a Magento shop that earns you money (either as an agency, as a developer 15 | or as a merchant), 16 | please consider sponsoring me and/or Yireo via GitHub. It would be appreciated and would help me to build 17 | even more cool things. 18 |

19 | 23 |
24 |
25 | 26 | 49 | -------------------------------------------------------------------------------- /view/frontend/layout/hyva_catalog_product_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /view/frontend/layout/hyva_default.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /view/frontend/layout/webp_test_images_image_with_custom_style.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Yireo\Webp2\Test\Utils\ImageProvider 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /view/frontend/layout/webp_test_images_multiple_existing_picturesets.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Yireo\Webp2\Test\Utils\ImageProvider 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /view/frontend/layout/webp_test_images_multiple_images.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Yireo\Webp2\Test\Utils\ImageProvider 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /view/frontend/layout/webp_test_images_multiple_images_same.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Yireo\Webp2\Test\Utils\ImageProvider 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /view/frontend/layout/webp_test_images_unknown_image.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Yireo\Webp2\Test\Utils\ImageProvider 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /view/frontend/requirejs-config.js: -------------------------------------------------------------------------------- 1 | var config = { 2 | config: { 3 | mixins: { 4 | 'Magento_Swatches/js/swatch-renderer': { 5 | 'Yireo_Webp2/js/swatch-renderer-mixin': true 6 | }, 7 | 'mage/gallery/gallery': { 8 | 'Yireo_Webp2/js/gallery-mixin': true 9 | } 10 | } 11 | }, 12 | deps: [ 13 | 'Yireo_Webp2/js/add-webp-class-to-body' 14 | ] 15 | }; 16 | -------------------------------------------------------------------------------- /view/frontend/templates/hyva/add-webp-class-to-body.phtml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /view/frontend/templates/hyva/gallery-additions.phtml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /view/frontend/templates/test/image_with_custom_style.phtml: -------------------------------------------------------------------------------- 1 | getImageProvider(); $image = $imageProvider->getImage(); $imageUrl = $block->escapeUrl($block->getViewFileUrl('Yireo_Webp2/' . $image)); ?>

getNameInLayout() ?>

test sample

Layout handles

getLayout()->getUpdate()->getHandles()); ?>
-------------------------------------------------------------------------------- /view/frontend/templates/test/multiple_existing_picturesets.phtml: -------------------------------------------------------------------------------- 1 | getImageProvider(); $images = $imageProvider->getImages(); $imageUrl = $block->escapeUrl($block->getViewFileUrl('Yireo_Webp2/' . $image)); ?>

getNameInLayout() ?>

Layout handles

getLayout()->getUpdate()->getHandles()); ?>
-------------------------------------------------------------------------------- /view/frontend/templates/test/multiple_images.phtml: -------------------------------------------------------------------------------- 1 | getImageProvider(); $images = $imageProvider->getImages(); ?>

getNameInLayout() ?>

escapeUrl($block->getViewFileUrl('Yireo_Webp2/' . $image)); ?>

Layout handles

getLayout()->getUpdate()->getHandles()); ?>
-------------------------------------------------------------------------------- /view/frontend/templates/test/multiple_images_same.phtml: -------------------------------------------------------------------------------- 1 | getImageProvider(); $image = $imageProvider->getImage(); ?>

getNameInLayout() ?>

Layout handles

getLayout()->getUpdate()->getHandles()); ?>
-------------------------------------------------------------------------------- /view/frontend/templates/test/unknown_image.phtml: -------------------------------------------------------------------------------- 1 |

Layout handles

getLayout()->getUpdate()->getHandles()); ?>
-------------------------------------------------------------------------------- /view/frontend/web/images/test/flowers.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yireo/Yireo_Webp2/02fc4614f5884caa73755c17f13ee816c6f14f4e/view/frontend/web/images/test/flowers.jpg -------------------------------------------------------------------------------- /view/frontend/web/images/test/flowers.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yireo/Yireo_Webp2/02fc4614f5884caa73755c17f13ee816c6f14f4e/view/frontend/web/images/test/flowers.webp -------------------------------------------------------------------------------- /view/frontend/web/images/test/goku.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yireo/Yireo_Webp2/02fc4614f5884caa73755c17f13ee816c6f14f4e/view/frontend/web/images/test/goku.jpg -------------------------------------------------------------------------------- /view/frontend/web/images/test/transparent-dragon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yireo/Yireo_Webp2/02fc4614f5884caa73755c17f13ee816c6f14f4e/view/frontend/web/images/test/transparent-dragon.png -------------------------------------------------------------------------------- /view/frontend/web/js/add-webp-class-to-body.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'jquery', 3 | './has-webp' 4 | ], function($, hasWebP) { 5 | if (hasWebP()) { 6 | $('body').addClass('webp'); 7 | } else { 8 | $('body').addClass('no-webp'); 9 | } 10 | }); 11 | -------------------------------------------------------------------------------- /view/frontend/web/js/gallery-mixin.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'jquery', 3 | './has-webp', 4 | "domReady!" 5 | ], function ($, hasWebP) { 6 | 'use strict'; 7 | 8 | var mixin = { 9 | initialize: function (config, element) { 10 | if (hasWebP()) { 11 | this._replaceImageDataWithWebp(config.data); 12 | } 13 | this._super(config, element); 14 | }, 15 | 16 | _replaceImageDataWithWebp: function (imagesData) { 17 | if (_.isEmpty(imagesData)) { 18 | return; 19 | } 20 | 21 | $.each(imagesData, function (key, imageData) { 22 | if (imageData['full_webp']) imageData['full'] = imageData['full_webp']; 23 | if (imageData['img_webp'])imageData['img'] = imageData['img_webp']; 24 | if (imageData['thumb_webp'])imageData['thumb'] = imageData['thumb_webp']; 25 | }); 26 | } 27 | }; 28 | 29 | return function (target) { 30 | return target.extend(mixin); 31 | } 32 | }); -------------------------------------------------------------------------------- /view/frontend/web/js/has-webp.js: -------------------------------------------------------------------------------- 1 | define([], function () { 2 | 'use strict'; 3 | 4 | return function hasWebP() { 5 | var elem = document.createElement('canvas'); 6 | 7 | if (!!(elem.getContext && elem.getContext('2d'))) { 8 | return elem.toDataURL('image/webp').indexOf('data:image/webp') === 0; 9 | } 10 | return false; 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /view/frontend/web/js/swatch-renderer-mixin.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'jquery', 3 | './has-webp', 4 | "domReady!" 5 | ], function ($, hasWebP) { 6 | 'use strict'; 7 | 8 | return function (widget) { 9 | $.widget('mage.SwatchRenderer', widget, { 10 | _init: function () { 11 | this._super(); 12 | if (hasWebP()) { 13 | $.each(this.options.jsonConfig.images, (function (key, imagesData) { 14 | $.each(imagesData, (function (key, imageData) { 15 | this._replaceImageData(imageData); 16 | }).bind(this)); 17 | }).bind(this)); 18 | } 19 | }, 20 | 21 | _ProductMediaCallback: function ($this, response, isInProductView) { 22 | if (hasWebP()) { 23 | this._replaceImageData(response); 24 | if (response.gallery) { 25 | $.each(response.gallery, (function (key, galleryImage) { 26 | this._replaceImageData(galleryImage); 27 | }).bind(this)); 28 | } 29 | } 30 | 31 | this._super($this, response, isInProductView); 32 | 33 | var productData = this._determineProductData(); 34 | let $pictureTag = $('.product-image-container-' + productData.productId + ' picture'); 35 | $pictureTag.find('source').remove(); 36 | }, 37 | 38 | _replaceImageData: function (imageData) { 39 | if (_.isEmpty(imageData)) { 40 | return imageData; 41 | } 42 | 43 | for (const [key, value] of Object.entries(imageData)) { 44 | if (imageData[key + '_webp']) { 45 | imageData[key] = imageData[key + '_webp']; 46 | } 47 | } 48 | 49 | return imageData; 50 | } 51 | }); 52 | 53 | return $.mage.SwatchRenderer; 54 | } 55 | }); 56 | --------------------------------------------------------------------------------