Repository: yireo/Yireo_Webp2 Branch: master Commit: e5bc07ccc0c8 Files: 68 Total size: 109.1 KB Directory structure: gitextract_sf71blct/ ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ ├── compile.yml │ ├── integration-tests/ │ │ ├── etc/ │ │ │ ├── install-config-mysql.php │ │ │ └── mysql-client-config.php │ │ ├── phpunit10.xml │ │ └── phpunit9.xml │ ├── integration-tests.yml │ ├── static-tests.yml │ └── 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_category_view.xml │ ├── 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/ └── js/ ├── add-webp-class-to-body.js ├── gallery-mixin.js ├── has-webp.js └── swatch-renderer-mixin.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ github: yireo custom: ["https://www.paypal.me/yireo"] ================================================ FILE: .github/workflows/compile.yml ================================================ name: Magento 2 DI compilation on: ['push', 'pull_request'] jobs: compile: name: Magento 2 DI compilation #runs-on: self-hosted runs-on: ubuntu-latest strategy: matrix: magento_version: ['2.4.5-p14', '2.4.7-p4', '2.4.7-p7', '2.4.8', '2.4.8-p1', '2.4.8-p2', '2.4.8-p3'] container: image: yireo/magento2installed:${{ matrix.magento_version }} steps: - name: Checkout sources uses: actions/checkout@v4 - name: Configure Yireo GitLab run: | test -n "${{ secrets.GITLAB_TOKEN }}" || exit 0 cd /tmp/magento composer config gitlab-domains gitlab.yireo.com composer config --global --auth http-basic.gitlab.yireo.com yireo "${{ secrets.GITLAB_TOKEN }}" composer config repositories.loki-third-party composer https://gitlab.yireo.com/api/v4/group/loki-third-party/-/packages/composer/packages.json composer config repositories.loki-checkout composer https://gitlab.yireo.com/api/v4/group/loki-checkout/-/packages/composer/packages.json - name: Add module source run: | COMPOSER_NAME=$(grep '^COMPOSER_NAME=' .module.ini | cut -d= -f2- | tr -d '"') cp -R ${GITHUB_WORKSPACE} /tmp/magento/package-source cd /tmp/magento composer config repositories.local-source path package-source/ composer require --prefer-source ${COMPOSER_NAME}:@dev - name: Run Magento 2 compilation run: | cd /tmp/magento bin/magento module:enable --all php -dmemory_limit=-1 bin/magento setup:di:compile ================================================ FILE: .github/workflows/integration-tests/etc/install-config-mysql.php ================================================ disableAll() ->enableMagento() ->disableByPattern('SampleData') ->disableByPattern('Magento_TestModule') ->disableMagentoInventory() ->disableGraphQl() ->enableByMagentoModuleEnv(); return (new InstallConfig()) ->setDisableModules($disableModules) ->addDb('mysql', 'magento2', 'magento2', 'magento2') ->addRedis('redis') ->addElasticSearch('opensearch', 'opensearch', 9200) ->get(); ================================================ FILE: .github/workflows/integration-tests/etc/mysql-client-config.php ================================================ [ 'disable-ssl', ], ]; ================================================ FILE: .github/workflows/integration-tests/phpunit10.xml ================================================ ../../../app/code/Yireo/LokiCheckout*/Test/Integration ../../../vendor/yireo/magento2-loki-checkout*/Test/Integration . testsuite ================================================ FILE: .github/workflows/integration-tests/phpunit9.xml ================================================ ../../../app/code/Yireo/LokiCheckout*/Test/Integration ../../../vendor/yireo/magento2-loki-checkout*/Test/Integration . testsuite ================================================ FILE: .github/workflows/integration-tests.yml ================================================ name: Magento 2 Integration Tests on: ['push', 'pull_request'] jobs: integration-tests: name: Magento 2 Integration Tests #runs-on: self-hosted runs-on: ubuntu-latest container: image: yireo/magento2installed:2.4.8-p3 services: mysql: image: yireo/mariadb:10 env: MYSQL_ROOT_PASSWORD: root MYSQL_USER: magento2 MYSQL_PASSWORD: magento2 MYSQL_DATABASE: magento2 options: --tmpfs /tmp:rw --tmpfs /var/lib/mysql:rw --health-cmd="mysqladmin ping" opensearch: image: yireo/opensearch:latest env: 'discovery.type': single-node ES_JAVA_OPTS: "-Xms256m -Xmx256m" options: --health-cmd="curl localhost:9200/_cluster/health?wait_for_status=yellow&timeout=60s" --health-interval=10s --health-timeout=5s --health-retries=3 redis: image: redis options: --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 steps: - name: Checkout sources uses: actions/checkout@v4 - name: Apply patch for reporting memory under Alpine run: cd /tmp/magento && curl -fsSL https://patch-diff.githubusercontent.com/raw/magento/magento2/pull/39216.diff | git apply - name: Apply patch for changing MySQL client configuration run: cd /tmp/magento && curl -fsSL https://patch-diff.githubusercontent.com/raw/magento/magento2/pull/40410.diff | git apply - name: Configure GitLab run: | test -n "${{ secrets.GITLAB_TOKEN }}" || exit 0 cd /tmp/magento composer config --auth gitlab-token.gitlab.yireo.com ${{ secrets.GITLAB_TOKEN }} composer config repositories.loki-checkout composer https://gitlab.yireo.com/api/v4/group/loki-checkout/-/packages/composer/packages.json - name: Add module source run: | export COMPOSER_NAME=`cat .module.ini | grep COMPOSER_NAME | cut -f2 -d= | tr -d '"'` cp -R ${GITHUB_WORKSPACE} /tmp/magento/package-source cd /tmp/magento composer config repositories.local-source path package-source/ composer require --prefer-source -- ${COMPOSER_NAME}:@dev yireo/magento2-integration-test-helper - name: Run Magento 2 Integration Tests run: | test -d $GITHUB_WORKSPACE/Test/Integration || exit 0 export EXTENSION_VENDOR=`cat .module.ini | grep EXTENSION_VENDOR | cut -f2 -d= | tr -d '"'` export EXTENSION_NAME=`cat .module.ini | grep EXTENSION_NAME | cut -f2 -d= | tr -d '"'` export COMPOSER_NAME=`cat .module.ini | grep COMPOSER_NAME | cut -f2 -d= | tr -d '"'` export MAGENTO_MODULE=${EXTENSION_VENDOR}_${EXTENSION_NAME} cd /tmp/magento/dev/tests/integration/ cp -R ${GITHUB_WORKSPACE}/.github/workflows/integration-tests/* . php ../../../vendor/bin/phpunit --atleast-version 9 && cp phpunit9.xml phpunit.xml php ../../../vendor/bin/phpunit --atleast-version 10 && cp phpunit10.xml phpunit.xml php -d memory_limit=4G ../../../vendor/bin/phpunit -c phpunit.xml ../../../vendor/$COMPOSER_NAME/Test/Integration ================================================ FILE: .github/workflows/static-tests.yml ================================================ name: Magento 2 Static Tests on: ['push', 'pull_request'] jobs: phpcs: name: Magento PHPCS runs-on: ubuntu-latest container: image: yireo/magento2installed:2.4.8-p3 steps: - name: Checkout sources uses: actions/checkout@v4 - name: Run Magento 2 PHPCS Tests run: | PHPCS_LEVEL=${{ env.PHPCS_LEVEL }} test -z "$PHPCS_LEVEL" && PHPCS_LEVEL=$(jq -r '.phpcs_severity // 10' MODULE.json) test -z "$PHPCS_LEVEL" && PHPCS_LEVEL=10 echo "Testing for PHPCS severity $PHPCS_LEVEL" cd /tmp/magento php vendor/bin/phpcs --standard=Magento2 --ignore=Test/,node_modules/ --colors --extensions=php,phtml --severity=$PHPCS_LEVEL ${GITHUB_WORKSPACE} phpstan: name: Magento PHPStan runs-on: ubuntu-latest container: image: yireo/magento2installed:2.4.8-p3 steps: - name: Checkout sources uses: actions/checkout@v4 - name: Configure GitLab run: | test -n "${{ secrets.GITLAB_TOKEN }}" || exit 0 cd /tmp/magento composer config gitlab-domains gitlab.yireo.com composer config --auth gitlab-token.gitlab.yireo.com ${{ secrets.GITLAB_TOKEN }} composer config repositories.loki-checkout composer https://gitlab.yireo.com/api/v4/group/loki-checkout/-/packages/composer/packages.json - name: Add module source run: | export COMPOSER_NAME=`cat .module.ini | grep COMPOSER_NAME | cut -f2 -d= | tr -d '"'` export COMPOSER_DEV_REQUIREMENTS=`jq -r '.["require-dev"] // {} | to_entries | map("\(.key):\(.value)") | join(" ")' composer.json` cp -R ${GITHUB_WORKSPACE} /tmp/magento/package-source cd /tmp/magento composer config repositories.local-source path package-source/ composer config --no-plugins allow-plugins true composer remove --dev magento/magento-coding-standard test -z "$COMPOSER_DEV_REQUIREMENTS" || composer require --dev $COMPOSER_DEV_REQUIREMENTS composer require --dev --prefer-source -- phpstan/phpstan:^2.0 bitexpert/phpstan-magento:^0.42 phpstan/extension-installer composer require --prefer-source -- ${COMPOSER_NAME}:@dev yireo/magento2-integration-test-helper - name: Run Magento 2 PHPStan Tests run: | export COMPOSER_NAME=`cat .module.ini | grep COMPOSER_NAME | cut -f2 -d= | tr -d '"'` export PHPSTAN_LEVEL=$(jq -r '.phpstan_level // 1' MODULE.json) test -z "$PHPSTAN_LEVEL" && PHPSTAN_LEVEL=1 test -f /tmp/magento/phpstan.neon || echo 'parameters:' > /tmp/magento/phpstan.neon echo "Testing for PHPStan level $PHPSTAN_LEVEL" cd /tmp/magento export MODULE_PATH=$(realpath vendor/${COMPOSER_NAME}) php -d memory_limit=4G vendor/bin/phpstan analyse --level $PHPSTAN_LEVEL $MODULE_PATH ================================================ FILE: .github/workflows/unit-tests.yml ================================================ name: Magento 2 Unit Tests on: ['push', 'pull_request'] jobs: unit-tests: name: Magento 2 Unit Tests #runs-on: self-hosted runs-on: ubuntu-latest container: image: yireo/magento2installed:2.4.8-p3 steps: - name: Checkout sources uses: actions/checkout@v4 - name: Configure GitLab run: | test -n "${{ secrets.GITLAB_TOKEN }}" || exit 0 cd /tmp/magento composer config --auth gitlab-token.gitlab.yireo.com ${{ secrets.GITLAB_TOKEN }} composer config repositories.loki-checkout composer https://gitlab.yireo.com/api/v4/group/loki-checkout/-/packages/composer/packages.json - name: Add module source run: | export COMPOSER_NAME=`cat .module.ini | grep COMPOSER_NAME | cut -f2 -d= | tr -d '"'` test -z "$COMPOSER_NAME}" && (echo "No composer name found" && exit 1) cp -R $GITHUB_WORKSPACE /tmp/magento/package-source cd /tmp/magento composer config repositories.local-source path package-source/ composer require --prefer-source -W -- $COMPOSER_NAME:@dev - name: Run Magento 2 Unit Tests run: | test -d $GITHUB_WORKSPACE/Test/Unit || exit 0 export COMPOSER_NAME=`cat .module.ini | grep COMPOSER_NAME | cut -f2 -d= | tr -d '"'` cd /tmp/magento/dev/tests/unit/ php -d memory_limit=4G ../../../vendor/bin/phpunit -c phpunit.xml.dist ../../../vendor/$COMPOSER_NAME/Test/Unit ================================================ FILE: .gitignore ================================================ ================================================ FILE: .magento/dev/tests/integration/etc/install-config-mysql.phps ================================================ '%MYSQL_HOST%', 'db-user' => 'root', 'db-password' => 'root', 'db-name' => 'magento-integration-test', 'db-prefix' => '', 'backend-frontname' => 'backend', 'admin-user' => \Magento\TestFramework\Bootstrap::ADMIN_NAME, 'admin-password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD, 'admin-email' => \Magento\TestFramework\Bootstrap::ADMIN_EMAIL, 'admin-firstname' => \Magento\TestFramework\Bootstrap::ADMIN_FIRSTNAME, 'admin-lastname' => \Magento\TestFramework\Bootstrap::ADMIN_LASTNAME, ]; ================================================ FILE: .magento/dev/tests/integration/phpunit.xml ================================================ ../../../vendor/yireo/*/Test/Integration ../../../vendor/yireo ../../../vendor/yireo/*/Test . testsuite ================================================ FILE: .magento/dev/tests/unit/phpunit.xml ================================================ ../../../app/code/*/*/Test/Unit ../../../app/code ../../../app/code/*/*/Test . testsuite ================================================ FILE: .module.ini ================================================ EXTENSION_VENDOR="Yireo" EXTENSION_NAME="Webp2" MODULE_NAME="Yireo_Webp2" COMPOSER_NAME="yireo/magento2-webp2" PHP_VERSIONS=("7.4", "8.1", "8.2") ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.14.3] - 24 October 2024 ### Fixed - Add funding ## [0.14.2] - 23 August 2024 ### Fixed - Guarantee return type is string #170 ## [0.14.1] - 23 August 2024 ### Fixed - Add CSP nonces to inline scripts ## [0.14.0] - 20 June 2024 ### Fixed - Move GraphQL support in seperate [module](https://github.com/yireo/Yireo_Webp2GraphQl) ## [0.13.5] - 4 April 2024 ### Fixed - Compatibility with Magento >=2.4.7-beta3 ## [0.13.4] - 26 September 2023 ### Fixed - Catch the correct exception when using properties of a specific exception. ## [0.13.3] - 22 September 2023 ### Fixed - Properly check for MIME-typed (fix of #149) - Add "webp" / "nowebp" to body class for Hyva ## [0.13.2] - 6 September 2023 ### Fixed - Make sure convertor is called for unsupported types #149 (@kernstmediarox) ## [0.13.1] - 6 September 2023 ### Fixed - Remove non-existing `description` in exception handling - Move Hyva dependency to separate package `yireo/magento2-webp2-for-hyva` ## [0.13.0] - 30 August 2023 ### Added - Copied GraphQL `url_webp` from Hyva compatibility module to here ### Fixed - Catch exceptions in converters by changing array to string with a foreach (@ghezelbash PR #140) ## [0.12.5] - 19 March 2023 ### Fixed - Version bump because of new NextGenImages minor ## [0.12.4] - 13 September 2022 ### Fixed - Implement the NextGenImages config setting `convert_images` ## [0.12.3] - 20 August 2022 ### Fixed - Add missing semicolon #130 ## [0.12.2] - 21 July 2022 ### Fixed - Using JS native `_determineProductData` function #120 (@artbambou) - Fix uncaught exception #127 (@jakegore) ## [0.12.1] - 2 June 2022 ### Fixed - Skip image replacement if target URL is still empty ## [0.12.0] - 4 May 2022 ### Added - Added ACL for user permissions (@jeroenalewijns) - Always add `webp` CSS class to body via JS detection - Add various integration tests - Refactoring because of changed NextGenImages API ### Removed - Moved AJAX plugin for swatches to NextGenImages ## [0.11.4] - 23 August 2021 ### Fixed - Check for double InvalidInputImageTypeException ## [0.11.3] - 23 August 2021 ### Fixed - Fix wrong exception being caught ## [0.11.2] - 11 August 2021 ### Fixed - Remove async from function (IE11 Support) (@barryvdh) ## [0.11.1] - 10 August 2021 ### Fixed - Fix error to config.xml introduced in last version (@chrisastley) ## [0.11.0] - 9 August 2021 ### Added - New option `encoding` for better performance with only `lossy` (@basvanpoppel) ## [0.10.11] - 15 July 2021 ### Fixed - Prevent exception when GIF is renamed to JPG ## [0.10.10] - 7 July 2021 ### Fixed - Hide all other fields if setting "Enabled" is set to 0 - Add current store to all methods ## [0.10.9] - 24 June 2021 ### Fixed - Fix PHP Notice when gallery is missing ## [0.10.8] - 24 June 2021 ### Fixed - Allow configuring convertors (#77) ## [0.10.7] - 6 May 2021 ### Fixed - Prevents error if variable $imageData[$imageType] is empty (@maksymcherevko) ## [0.10.6] - 2 April 2021 ### Fixed - Webp images not being generated if cached jpg does not exist yet #70 (@gtlt) ## [0.10.5] - 9 March 2021 ### Fixed - Refactor conversion errors - Move helper function to NextGenImages - Throw exception when no conversion is needed - Update convertor class to comply to updated interface ## [0.10.4] - 15 February 2021 ### Fixed - Log all exceptions to NextGenImages logger ## [0.10.3] - 12 February 2021 ### Fixed - Make sure configurable images don't throw exception ## [0.10.2] - 12 February 2021 ### Fixed - Make sure wrong gallery images don't throw exception ## [0.10.1] - 11 February 2021 ### Fixed - Fix JS error - Rewrite into synchronous way of detecting WebP ## [0.10.0] - 28 January 2021 ### Added - Improved support on product detail page (configurable swatches + fotorama) ## [0.9.6] - 22 January 2021 ### Fixed - When no .webp file is available, the source tag will be removed to prevent old image being shown on the frontend (@ar-vie) ## [0.9.5] - 3 December 2020 ### Fixed - Remove class UrlReplacer again after refactoring NextGenImages ## [0.9.4] - 3 December 2020 ### Fixed - Fix missing class UrlReplacer ## [0.9.3] - 2 December 2020 ### Fixed - Fix composer deps with magento2-next-gen-images ## [0.9.2] - 30 November 2020 ### Fixed - Stick to new ConvertorInterface interface of NextGenImages ## [0.9.1] - 30 November 2020 ### Fixed - Wrong composer dependency with NextGenImages ## [0.9.0] - 30 November 2020 ### Removed - Remove JavaScript check and Browser class - Moved code from this module to generic NextGenImages module - Remove Travis CI script ## [0.8.0] - 30 November 2020 ### Fixed - Lazy loading configuration option was not working ### Added - Add new option for quality level ## [0.7.6] - 19 August 2020 ### Fixed - Fixes wrong name in require-js config (@johannessmit) ## [0.7.5] - 13 August 2020 ### Fixed - Add jQuery Cookie to prevent load order issues (@basvanpoppel) ## [0.7.4] - 3 August 2020 ### Fixed - Image is correctly updated including the source (@johannessmit) ### Removed - Undo of `parse_url` Laminas replacement because this breaks pre-Laminas Magento releases ## [0.7.3] - 29 July 2020 ### Added - Magento 2.4 support ### Fixed - Numerous PHPCS issues ### Added - URL parsing via laminas/laminas-uri package ## [0.7.2] - June 13th, 2020 ### Fixed - Remove alt attribute from picture element (@gjportegies) ## [0.7.1] - April 6th, 2020 ### Added - Quick fix to allow for WebP images in catalog swatches ## [0.7.0] - March 31st, 2020 ### Added - Code refactoring to allow for Amasty Shopby compatibility ## [0.6.2] - March 18th, 2020 ### Fixed - Skip captcha images (PR from @jasperzeinstra) ## [0.6.1] - March 18th, 2020 ### Fixed - Do not throw error in debugging with non-existing images - Rename "Debug Log" to "Debugging" because that's what's happening ## [0.6.0] - March 7th, 2020 ### Added - Skipping WebP image creation by configuration option ## [0.5.2] - March 5th, 2020 ### Fixed - Fix next tag not being closed properly ## [0.5.1] - February 19th, 2020 ### Fixed - Prevent overwriting existing `picture` tags ## [0.5.0] - February 11th, 2020 ### Added - Upgraded rosell-dk/webp-convert library ## [0.4.7] - January 31st, 2020 ### Added - Add class attribute in picture (PR from itsazzad) - Better support info - Raise framework requirements for proper support of ViewModels - Added logic for fetching the css class from the original image (PR from duckchip) - Added missing variable in the ReplaceTags plugin (PR from duckchip) ## [0.4.6] - November 23rd, 2019 ### Fixed - Raise requirements for proper support of ViewModels ## [0.4.5] - October 16th, 2019 ### Added - Add check for additional layout handle `webp_skip` ## [0.4.4] - October 15th, 2019 ### Fixed - Dirty workaround for email layout ## [0.4.3] - October 4th, 2019 ### Added - Add controller for email testing ### Fixed - Do not apply WebP if no handles ## [0.4.2] - July 14th, 2019 ### Fixed - Make sure modified gallery images are returned as Collection, not an array - Test with Aimes_Notorama ## [0.4.1] - July 2019 ### Fixed - Original tag (with custom styling) was not used in `picture` element, but new one was created instead ## [0.4.0] - July 2019 ### Added - Move configuration to separate **Yireo** section - Add a `config.xml` file - Changed configuration path from `system/yireo_webp2/*` to `yireo_webp2/settings/*` - Move `quality_level` to `config.xml` ## [0.3.0] - 2019-05-02 ### Fixed - Fix issue with additional images not being converted if already converted (@jove4015) - Fix issue with static versioning not being reckognized - Make sure src, width and height still remain in picture-tag ### Added - Integration test for multiple instances of same image - Add fields in backend for PHP version and module version - Integration Test to test conversion of test-files - Throw an exception of source file is not found - Add provider of dummy images - Add integration test of dummy images page - Add test page with dummy images - Only show original image in HTML source when debugging ## [0.2.0] - 2019-04-28 ### Fixed - Fix issue with additional images not being converted if already converted - Make sure to enable cookie-check whenever FPC is enabled ### Added - Actual meaningful integration test for browsing product page ## [0.1.1] - 2019-04-12 ### Fixed - Disable gallery fix if FPC is enabled ## [0.1.0] - 2019-04-12 ### Added - Add GD checker in backend settings ## [0.0.3] - 2019-03-21 ### Fixed - Fix for Fotorama gallery - Check via timestamps for new and modified files ### Added - Check for browser support via cookie and Chrome-check - Inspect ACCEPT header for image/webp support - Implement detect.js script to detect WebP support and set a cookie - Add configuration values ## [0.0.2] - 2019-03-20 ### Added - Temporary release for CI purpose ## [0.0.1] - 2019-03-20 ### Added - Initial commit - Support for regular img-tags to picture-tags conversion ================================================ FILE: Config/Config.php ================================================ scopeConfig = $scopeConfig; $this->storeManager = $storeManager; $this->nextGenImagesConfig = $nextGenImagesConfig; } /** * @return bool */ public function enabled(): bool { return (bool)$this->getValue('yireo_webp2/settings/enabled'); } /** * @return bool */ public function allowImageCreation(): bool { return $this->nextGenImagesConfig->allowImageCreation(); } /** * @return int */ public function getQualityLevel(): int { $qualityLevel = (int)$this->getValue('yireo_webp2/settings/quality_level'); if ($qualityLevel > 100) { return 100; } if ($qualityLevel < 1) { return 1; } return $qualityLevel; } /** * @return string[] * @throws InvalidConvertorException */ public function getConvertors(): array { $allConvertors = ['cwebp', 'gd', 'imagick', 'wpc', 'ewww']; $storedConvertors = $this->getValue('yireo_webp2/settings/convertors'); $storedConvertors = $this->stringToArray((string)$storedConvertors); if (empty($storedConvertors)) { return $allConvertors; } foreach ($storedConvertors as $storedConvertor) { if (!in_array($storedConvertor, $allConvertors)) { throw new InvalidConvertorException('Invalid convertor: "' . $storedConvertor . '"'); } } return $storedConvertors; } /** * @return string * @throws InvalidConvertorException */ public function getEncoding(): string { $allEncoding = ['lossy', 'lossless', 'auto']; $storedEncoding = (string)$this->getValue('yireo_webp2/settings/encoding'); if (empty($storedEncoding)) { return 'lossy'; } if (!in_array($storedEncoding, $allEncoding)) { throw new InvalidConvertorException('Invalid encoding: "' . $storedEncoding . '"'); } return $storedEncoding; } /** * @param string $path * @return mixed */ private function getValue(string $path) { try { return $this->scopeConfig->getValue( $path, ScopeInterface::SCOPE_STORE, $this->storeManager->getStore() ); } catch (NoSuchEntityException $e) { return null; } } /** * @param string $string * @return array */ private function stringToArray(string $string): array { $array = []; $strings = explode(',', $string); foreach ($strings as $string) { $string = trim($string); if ($string) { $array[] = $string; } } return $array; } } ================================================ FILE: Config/Frontend/Funding.php ================================================ toHtml(); } } ================================================ FILE: Controller/Test/Images.php ================================================ pageFactory = $pageFactory; } /** * @return Page */ public function execute() { $page = $this->pageFactory->create(); $case = strtolower((string)$this->_request->getParam('case')); $case = preg_replace('/([^a-z\_]+)/', '', $case); $handle = 'webp_test_images_' . $case; $page->addHandle($handle); return $page; } } ================================================ FILE: Controller/Test/Mail.php ================================================ transportBuilder = $transportBuilder; $this->storeManager = $storeManager; $this->layoutFactory = $layoutFactory; $this->request = $request; $this->jsonFactory = $jsonFactory; $this->scopeConfig = $scopeConfig; $this->config = $config; } /** * @return ResultInterface * @throws LocalizedException * @throws MailException * @throws NoSuchEntityException */ public function execute(): ResultInterface { $token = (string)$this->request->getParam('token'); $cryptKey = (string)$this->config->get('crypt/key'); if ($token === $cryptKey) { return $this->sendResult(['msg' => 'Invalid token']); } $emailTemplate = (string)$this->request->getParam('email'); if (empty($emailTemplate)) { $emailTemplate = 'sales_email_invoice_template'; } $receiverInfo = [ 'name' => $this->scopeConfig->getValue('trans_email_ident/general/name'), 'email' => $this->scopeConfig->getValue('trans_email_ident/general/email'), ]; $senderInfo = [ 'name' => $this->scopeConfig->getValue('trans_email_ident/general/name'), 'email' => $this->scopeConfig->getValue('trans_email_ident/general/email'), ]; $data = [ 'template' => $emailTemplate, 'sender' => $senderInfo, 'receiver' => $receiverInfo ]; $variables = []; $this->transportBuilder->setTemplateIdentifier($emailTemplate) ->setTemplateOptions( [ 'area' => Area::AREA_FRONTEND, 'store' => $this->storeManager->getStore()->getId(), ] ) ->setTemplateVars($variables) ->setFrom($senderInfo) ->addTo($receiverInfo['email'], $receiverInfo['name']); $transport = $this->transportBuilder->getTransport(); $transport->sendMessage(); $data['msg'] = 'Email sent'; return $this->sendResult($data); } /** * @param mixed[] $data * @return ResultInterface */ private function sendResult(array $data): ResultInterface { $jsonResult = $this->jsonFactory->create(); $jsonResult->setData($data); return $jsonResult; } } ================================================ FILE: Convertor/ConvertWrapper.php ================================================ config = $config; $this->logger = $logger; } /** * @param string $sourceImageFilename * @param string $destinationImageFilename * @throws ConversionFailedException * @throws InvalidConvertorException * @throws InvalidImageTypeException */ public function convert(string $sourceImageFilename, string $destinationImageFilename): void { $options = $this->getOptions(); foreach ($this->config->getConvertors() as $convertor){ $options['converter'] = $convertor; try { WebPConvert::convert($sourceImageFilename, $destinationImageFilename, $options); } catch (ConversionFailedException $e) { $this->logger->debug($e->getMessage() . ' - ' . $e->description, $e->getTrace()); continue; } catch (\Exception $e) { $this->logger->debug($e->getMessage(), $e->getTrace()); continue; } break; } } /** * @return array * @throws InvalidConvertorException */ public function getOptions(): array { return [ 'quality' => 'auto', 'max-quality' => $this->config->getQualityLevel(), 'encoding' => $this->config->getEncoding(), ]; } } ================================================ FILE: Convertor/Convertor.php ================================================ config = $config; $this->imageFile = $imageFile; $this->convertWrapper = $convertWrapper; $this->targetImageFactory = $targetImageFactory; $this->imageFactory = $imageFactory; } /** * @param Image $image * @return Image * @throws ConvertorException * @throws FileSystemException */ public function convertImage(Image $image): Image { if (!$this->config->enabled()) { throw new ConvertorException('WebP conversion is not enabled'); } if (!in_array($image->getMimetype(), ['image/jpeg', 'image/jpg', 'image/png'])) { throw new ConvertorException('The mimetype "'.$image->getMimetype().'" is not supported'); } // @todo: https://gitlab.hyva.io/hyva-themes/hyva-compat/magento2-yireo-next-gen-images/-/blob/main/src/Plugin/ConverterPlugin.php#L50 $webpImage = $this->targetImageFactory->create($image, 'webp'); $result = $this->convert($image->getPath(), $webpImage->getPath()); if (!$result && !$this->imageFile->fileExists($webpImage->getPath())) { throw new ConvertorException('WebP path "'.$webpImage->getPath().'" does not exist after conversion'); } $webpImage->setSrcSet($this->convertSrcSet($image)); return $webpImage; } /** * @param string $sourceImagePath * @param string $targetImagePath * @return bool * @throws ConvertorException */ private function convert(string $sourceImagePath, string $targetImagePath): bool { if (!$this->imageFile->fileExists($sourceImagePath)) { throw new ConvertorException('Source cached image does not exists: '.$sourceImagePath); } if (!$this->imageFile->needsConversion($sourceImagePath, $targetImagePath)) { return true; } if (!$this->config->enabled() || !$this->config->allowImageCreation()) { throw new ConvertorException('WebP conversion is not enabled'); } try { $this->convertWrapper->convert($sourceImagePath, $targetImagePath); } catch (InvalidImageTypeException|InvalidInputException|InvalidInputImageTypeException $e) { return false; } catch (ConversionFailedException|InvalidConvertorException $e) { throw new ConvertorException($targetImagePath.': '.$e->getMessage()); } return true; } private function convertSrcSet(Image $image): string { $srcSetImages = explode(',', $image->getSrcSet()); $webpImageSrcSet = ''; foreach ($srcSetImages as $srcSetImage) { $pieces = explode(' ', trim($srcSetImage)); $imageUrl = $pieces[0]; $descriptor = $pieces[1] ?? 0; $srcSetImage = $this->imageFactory->createFromUrl($imageUrl); $srcSetWebpImage = $this->targetImageFactory->create($srcSetImage, 'webp'); $result = $this->convert($srcSetImage->getPath(), $srcSetWebpImage->getPath()); if (!$result && !$this->imageFile->fileExists($srcSetWebpImage->getPath())) { throw new ConvertorException('WebP path "'.$srcSetWebpImage->getPath().'" does not exist after conversion'); } $webpImageSrcSet .= ($webpImageSrcSet ? ', ' : '') . $srcSetWebpImage->getUrl() . ' ' . ($descriptor ?: ''); } return $webpImageSrcSet; } } ================================================ FILE: Exception/InvalidConvertorException.php ================================================ " 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. ================================================ FILE: Model/Config/Source/Encoding.php ================================================ 'lossy', 'label' => 'Lossy'], ['value' => 'lossless', 'label' => 'Lossless'], ['value' => 'auto', 'label' => 'Auto (both lossy and lossless)'], ]; } } ================================================ FILE: Plugin/AddCspInlineScripts.php ================================================ replaceInlineScripts = $replaceInlineScripts; } public function afterToHtml(Template $block, $html): string { if (false === strstr((string)$block->getNameInLayout(), 'yireo_webp2.')) { return (string)$html; } return $this->replaceInlineScripts->replace((string)$html); } } ================================================ FILE: README.md ================================================ # Magento 2 module for WebP **This module adds WebP support to Magento 2.** ## About this module - When `` tags are found on the page, the corresponding JPG or PNG is converted into WebP and a corresponding `` tag. - 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. > [!WARNING] > Hyvä support is built into the latest versions of this module. Please do not use the deprecated compatibility module anymore. ## Instructions for using composer 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: ```bash composer require yireo/magento2-webp2 bin/magento module:enable Yireo_Webp2 Yireo_NextGenImages bin/magento setup:upgrade ``` Enable the module by toggling the setting in **Stores > Configuration > Yireo > Yireo WebP > Enabled**. ## System requirements Make sure your PHP environment supports WebP: This means that the function `imagewebp` should exist in PHP. We hope to add more checks for this in the extension itself soon. For now, just open up a PHP `phpinfo()` page and check for WebP support. Please note that installing `libwebp` on your system is not the same as having PHP support WebP. Check the `phpinfo()` file and add new PHP modules to PHP if needed. If in doubt, simple create a PHP script `test.php` and a line `` 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. 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. #### My CPU usage goes up. Is that normal? Yes, it is normal. This extension does two things: It shows a WebP on the frontend of your shop. And it generates that WebP when it is missing. Obviously, generating an image takes up system resources. And if you have a large catalog, it is going to do more time. How much time? Do make sure to calculate this yourself: Take an image, resize it using the `cwebp` binary and measure the time - multiply it by how many images there are. This should give a fair estimation on how much time is needed. Note that this extension allows for using various mechanisms (aka *convertors*). Tune the **Convertors** settings if you want to try to optimize things. Sometimes, GD is faster than `cwebp`. Sometimes, GD just breaks things. It depends, so you need to pick upon the responsibility to try this in your specific environment. 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`. If you don't like the generation of images at all, you could also use other CLI tools instead. #### Class 'WebPConvert\WebPConvert' not found 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. #### After installation, I'm still seeing only PNG and JPEG images 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. 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/`. 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. #### Warning: filesize(): stat failed for xxx.webp If you are seeing this issue in the `exception.log` and/or `system.log`, do make sure to wipe out Magento caching and do make sure that the WebP file in question is accessible: The webserver running Magento should have read access to the file. Likewise, if you want this extension to automatically convert a JPEG into WebP, do make sure that the folder containing the JPEG is writable. #### Some of the images are converted, but others are not. 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. Make sure your `cwebp` binary and PHP environment are up-to-date. #### This sucks. It only works in some browsers. Don't complain to us. Instead, ask the other browser vendors to support this as well. And don't say this is not worth implementing, because I bet more than 25% of your sites visitors will benefit from WebP. Not offering this to them, is wasting additional bandwidth. #### Some emails are also displaying WebP 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). 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. #### error while loading shared libraries: libjpeg.so.8: cannot open shared object file: No such file or directory 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. #### Can I use this with Amasty Shopby? Yes, you can. Make sure to install the addition https://github.com/yireo/Yireo_Webp2ForAmastyShopby as well. #### How can I convert WebP images manually from the CLI? 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. Next, a simple shell script could be used to build all WebP files: ```bash find . -type f -name \*.jpg | while read IMAGE do; convert $IMAGE ${IMAGE/.jpg/.webp}; done ``` Or another example (of @rostilos): ```bash #!/bin/bash start=`date +%s` directory="../pub/media" cd "$directory" || exit find . -type f \( -iname \*.jpg -o -iname \*.jpeg -o -iname \*.png \) -print0 | while IFS= read -r -d $'\0' file; do filename=$(basename -- "$file") new_filename="${filename%.*}.webp" new_filepath="$(dirname "$file")/$new_filename" echo "Converting: $file -> $new_filepath" cwebp -q 80 -quiet "$file" -o "$new_filepath" done end=`date +%s` runtime=$((end-start)) echo "Execution completed in $runtime seconds." ``` ## Requesting support ### First check to see if our extension is doing its job 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: ```html ``` 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. ### Opening an issue for this extension 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: - What browser did you test this with? - What is your Magento version? - What is your PHP version? - Did you make sure to use `composer` to install all dependencies? - Not using `composer` is **not** supported. - Which specific composer version of the Yireo WebP2 extension did you install? - Which specific composer version of the Yireo NextGenImages extension did you install? - Have you tested this after flushing all caches, especially the Full Page Cache? - Have you tested this after disabling all caches, especially the Full Page Cache? - 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. - Are you testing this in the Developer Mode or in the Production Mode? - 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. - Under **Stores > Configuration > Yireo > Yireo WebP2** and **Stores > Configuration > Yireo > Yireo NextGenImages**, what settings do you see with which values? - Preferably post a screenshot with the settings. - Could you supply a URL to a live demo? - Could you please supply a snapshot of the HTML source of a product page? 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. 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"`. ### Issues with specific images If some images are converted but others are not, please supply the following details: - 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) - 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) - Whether or not you are using a CDN for serving images. ================================================ FILE: Setup/UpgradeData.php ================================================ configCollectionFactory = $configCollectionFactory; $this->storageWriter = $storageWriter; } /** * @param ModuleDataSetupInterface $setup * @param ModuleContextInterface $context * @return void */ public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); $oldPath = 'system/yireo_webp/'; $newPath = 'yireo_webp2/settings/'; $configCollection = $this->configCollectionFactory->create(); $configCollection->addFieldToFilter('path', ['like' => $oldPath . '%']); $items = $configCollection->getItems(); foreach ($items as $item) { $data = $item->getData(); $this->storageWriter->delete($data['path'], $data['scope'], $data['scope_id']); $newPath = str_replace($oldPath, $newPath, $data['path']); $this->storageWriter->save($newPath, $data['value'], $data['scope'], $data['scope_id']); } $setup->endSetup(); } } ================================================ FILE: Test/Integration/Common.php ================================================ _objectManager->get(ConvertWrapperStub::class); $this->_objectManager->addSharedInstance($convertWrapperStub, ConvertWrapper::class); } /** * @return string[] */ protected function fixtureImageFiles(): array { // @todo: It would be cleaner to use the sandbox directory for this /** @var DirectoryList $directoryList */ $directoryList = $this->_objectManager->get(DirectoryList::class); $root = $directoryList->getRoot(); $imagesInThemePath = $root . '/pub/static/frontend/Magento/luma/en_US/Yireo_Webp2/images/test'; if (!is_dir($imagesInThemePath)) { mkdir($imagesInThemePath, 0777, true); } if (!is_dir($imagesInThemePath)) { throw new RuntimeException('Failed to create folder: ' . $imagesInThemePath); } $currentFiles = scandir($imagesInThemePath); foreach ($currentFiles as $currentFile) { if (!in_array($currentFile, ['.', '..'])) { unlink($imagesInThemePath . '/' . $currentFile); } } /** @var ImageProvider $imageProvider */ $imageProvider = $this->_objectManager->get(ImageProvider::class); $images = $imageProvider->getImages(); /** @var ComponentRegistrar $componentRegistrar */ $componentRegistrar = $this->_objectManager->get(ComponentRegistrar::class); $modulePath = $componentRegistrar->getPath('module', 'Yireo_Webp2'); $moduleWebPath = $modulePath . '/view/frontend/web'; foreach ($images as $image) { $sourceImage = $moduleWebPath . '/' . $image; $destinationImage = $imagesInThemePath . '/' . basename($image); copy($sourceImage, $destinationImage); } return glob($root . '/pub/static/frontend/Magento/luma/en_US/Yireo_Webp2/images/test/*'); } /** * @return ImageProvider */ protected function getImageProvider(): ImageProvider { return $this->_objectManager->get(ImageProvider::class); } /** * @param string $body * @param array $images */ protected function assertImageTagsExist(string $body, array $images) { $layout = $this->_objectManager->get(LayoutInterface::class); $blocks = $layout->getChildBlocks('main'); $html = ''; foreach ($blocks as $block) { $html .= $block->toHtml(); } foreach ($images as $image) { $webPImage = preg_replace('/\.(png|jpg)$/', '.webp', $image); $debugMsg = 'Asserting that body contains "' . $webPImage . '": ' . $html; $this->assertTrue((bool)strpos($body, $webPImage), $debugMsg); } } } ================================================ FILE: Test/Integration/ImageConversionTest.php ================================================ fixtureImageFiles(); $imagePath = $images[0]; $image = $this->_objectManager->get(ImageFactory::class)->createFromPath($imagePath); $convertor = $this->_objectManager->get(Convertor::class); $convertedImage = $convertor->convertImage($image); $this->assertNotEmpty($convertedImage->getPath()); } } ================================================ FILE: Test/Integration/ImageWithCustomStyleTest.php ================================================ fixtureImageFiles(); $this->getRequest()->setParam('case', 'image_with_custom_style'); $this->dispatch('webp/test/images'); $this->assertSame('image_with_custom_style', $this->getRequest()->getParam('case')); $this->assertSame(200, $this->getResponse()->getHttpResponseCode()); $body = $this->getResponse()->getContent(); $this->assertImageTagsExist($body, [$this->getImageProvider()->getImage()]); $this->assertTrue((bool)strpos($body, 'type="image/webp"')); if (!getenv('TRAVIS')) { $this->assertTrue((bool)strpos($body, 'style="display:insane; opacity:666;"')); } } } ================================================ FILE: Test/Integration/ModuleTest.php ================================================ getPaths(ComponentRegistrar::MODULE); $this->assertArrayHasKey('Yireo_Webp2', $paths); } /** * Test if the module is known and enabled */ public function testIfModuleIsKnownAndEnabled() { $objectManager = Bootstrap::getObjectManager(); $moduleList = $objectManager->create(ModuleList::class); $this->assertTrue($moduleList->has('Yireo_NextGenImages')); $this->assertTrue($moduleList->has('Yireo_Webp2')); } } ================================================ FILE: Test/Integration/MultipleImagesSameTest.php ================================================ fixtureImageFiles(); $this->getRequest()->setParam('case', 'multiple_images_same'); $this->dispatch('webp/test/images'); $this->assertSame('multiple_images_same', $this->getRequest()->getParam('case')); $this->assertSame(200, $this->getResponse()->getHttpResponseCode()); $body = $this->getResponse()->getContent(); $this->assertImageTagsExist($body, [$this->getImageProvider()->getImage()]); $this->assertTrue((bool)strpos($body, 'type="image/webp"')); if (!getenv('TRAVIS')) { $this->assertImageTagsExist($body, [$this->getImageProvider()->getImage()]); } } } ================================================ FILE: Test/Integration/MultipleImagesTest.php ================================================ fixtureImageFiles(); $this->getRequest()->setParam('case', 'multiple_images'); $this->dispatch('webp/test/images'); $this->assertSame('multiple_images', $this->getRequest()->getParam('case')); $this->assertSame(200, $this->getResponse()->getHttpResponseCode()); $body = $this->getResponse()->getBody(); $this->assertImageTagsExist($body, [$this->getImageProvider()->getImage()]); $this->assertTrue((bool)strpos($body, 'type="image/webp"')); if (!getenv('TRAVIS')) { $this->assertImageTagsExist($body, $this->getImageProvider()->getImages()); } } } ================================================ FILE: Test/Unit/Config/ConfigTest.php ================================================ createMock(ScopeConfigInterface::class); $storeManager = $this->createMock(StoreManagerInterface::class); $nextGenImagesConfig = $this->createMock(NextGenImagesConfig::class); $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); $this->assertFalse($config->enabled()); $scopeConfig->method('getValue')->willReturn(1); $this->assertTrue($config->enabled()); } public function testGetQualityLevel() { $scopeConfig = $this->createMock(ScopeConfigInterface::class); $storeManager = $this->createMock(StoreManagerInterface::class); $nextGenImagesConfig = $this->createMock(NextGenImagesConfig::class); $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); $this->assertEquals(1, $config->getQualityLevel()); $scopeConfig = $this->createMock(ScopeConfigInterface::class); $scopeConfig->method('getValue')->willReturn(42); $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); $this->assertEquals(42, $config->getQualityLevel()); $scopeConfig = $this->createMock(ScopeConfigInterface::class); $scopeConfig->method('getValue')->willReturn(142); $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); $this->assertEquals(100, $config->getQualityLevel()); $scopeConfig = $this->createMock(ScopeConfigInterface::class); $scopeConfig->method('getValue')->willReturn(0); $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); $this->assertEquals(1, $config->getQualityLevel()); } public function testGetConvertors() { $scopeConfig = $this->createMock(ScopeConfigInterface::class); $storeManager = $this->createMock(StoreManagerInterface::class); $nextGenImagesConfig = $this->createMock(NextGenImagesConfig::class); $config = new Config($scopeConfig, $storeManager, $nextGenImagesConfig); $this->assertNotEmpty($config->getConvertors()); } } ================================================ FILE: Test/Unit/Convertor/ConvertorTest.php ================================================ createMock(Config::class); $config->method('enabled')->willReturn(true); $convertor = $this->getConvertor($config); $this->expectException(ConvertorException::class); $image = new Image('/tmp/pub/test/foobar.jpg', '/test/foobar.jpg'); $this->assertEquals('/test/foobar.webp', $convertor->convertImage($image)); } /** * Test for Yireo\Webp2\Convertor\Convertor::convertImage */ public function testConvert() { $convertor = $this->getConvertor(); $this->expectException(ConvertorException::class); $image = new Image('/tmp/pub/test/foobar.jpg', '/test/foobar.jpg'); $convertor->convertImage($image); } /** * Test for Yireo\Webp2\Convertor\Convertor::convertImage */ public function testItWillConvertSrcSetIfFound() { $givenSrcSet = '/test/foobar-small.jpg 500w, /test/foobar-medium.jpg 800w, /test/foobar-default.jpg'; $expectedSrcSet = '/test/foobar-small.webp 500w, /test/foobar-medium.webp 800w, /test/foobar-default.webp '; $config = $this->createMock(Config::class); $config->method('enabled')->willReturn(true); $config->method('allowImageCreation')->willReturn(true); $imageFile = $this->createMock(File::class); $imageFile->method('fileExists')->willReturn(true); $imageFile->method('needsConversion')->willReturn(true); $webpImageFile = $this->createMock(Image::class); $webpImageFile->method('getUrl')->willReturnOnConsecutiveCalls( '/test/foobar-small.webp', '/test/foobar-medium.webp', '/test/foobar-default.webp', ); $webpImageFile->expects($this->once()) ->method('setSrcSet') ->with($expectedSrcSet) ->willReturnSelf(); $convertWrapper = $this->createMock(ConvertWrapper::class); $targetImageFactory = $this->createMock(TargetImageFactory::class); $targetImageFactory->method('create')->willReturn($webpImageFile); $imageFactory = $this->createMock(ImageFactory::class); $convertor = new Convertor( $config, $imageFile, $convertWrapper, $targetImageFactory, $imageFactory ); $image = new Image('/tmp/pub/test/foobar.jpg', '/test/foobar.jpg', $givenSrcSet); $convertedImage = $convertor->convertImage($image); } /** * @param Config|null $config * @return Convertor */ private function getConvertor(?Config $config = null): Convertor { if (!$config) { $config = $this->createMock(Config::class); } $file = $this->createMock(File::class); $convertWrapper = $this->createMock(ConvertWrapper::class); $targetImageFactory = $this->createMock(TargetImageFactory::class); $imageFactory = $this->createMock(ImageFactory::class); return new Convertor( $config, $file, $convertWrapper, $targetImageFactory, $imageFactory ); } } ================================================ FILE: Test/Utils/ConvertWrapperStub.php ================================================ getImages(); return $images[0]; } /** * @return string */ public function getNonExistingImage(): string { return 'images/test/non-existing.jpg'; } } ================================================ FILE: composer.json ================================================ { "name": "yireo/magento2-webp2", "license": "OSL-3.0", "version": "0.14.3", "type": "magento2-module", "homepage": "https://www.yireo.com/software/magento-extensions/webp2", "description": "Magento 2 module to add WebP support to the Magento frontend", "keywords": [ "composer-installer", "magento", "Magento 2", "Exception", "Yireo" ], "authors": [ { "name": "Jisse Reitsma (Yireo)", "email": "jisse@yireo.com" } ], "require": { "yireo/magento2-next-gen-images": "~0.3", "yireo/magento2-csp-utilities": "^1.0", "magento/framework": "^101.0.1|^101.1|^102.0|^103.0", "magento/module-backend": "^100.0|^101.0|^102.0", "magento/module-config": "^101.0", "magento/module-store": "^101.0", "rosell-dk/webp-convert": "^2.0", "psr/log": "^1 || ^2 || ^3", "php": ">=7.4.0", "ext-json": "*", "ext-pcre": "*", "ext-gd": "*" }, "require-dev": { "phpunit/phpunit": "^9.0|^10.0|^11.0", "phpstan/phpstan": "^0.12.32", "bitexpert/phpstan-magento": "^0.3.0", "yireo/magento2-integration-test-helper": "^0.0.8" }, "suggest": { "yireo/magento2-webp2-for-hyva": "Additional fixes with Yireo Webp2 for Hyva", "yireo/magento2-webp2-graph-ql": "GraphQL endpoints for Yireo Webp2" }, "autoload": { "psr-4": { "Yireo\\Webp2\\": "" }, "files": [ "registration.php" ] }, "funding": [ { "type": "github", "url": "https://github.com/sponsors/jissereitsma" }, { "type": "github", "url": "https://github.com/sponsors/yireo" }, { "type": "paypal", "url": "https://www.paypal.me/yireo" }, { "type": "other", "url": "https://www.buymeacoffee.com/jissereitsma" } ] } ================================================ FILE: etc/acl.xml ================================================ ================================================ FILE: etc/adminhtml/system.xml ================================================
yireo Yireo_Webp2::config Yireo\Webp2\Config\Frontend\Funding Magento\Config\Model\Config\Source\Yesno 1 Yireo\Webp2\VirtualType\Block\Adminhtml\System\Config\ModuleVersion 1 1 Yireo\Webp2\Model\Config\Source\Encoding 1
================================================ FILE: etc/config.xml ================================================ 1 80 cwebp,gd,imagick,wpc,ewww lossy ================================================ FILE: etc/di.xml ================================================ Yireo\Webp2\Convertor\Convertor Yireo_Webp2 ================================================ FILE: etc/frontend/di.xml ================================================ ================================================ FILE: etc/frontend/routes.xml ================================================ ================================================ FILE: etc/module.xml ================================================ ================================================ FILE: phpstan.neon ================================================ parameters: excludePaths: - */Test/*/* ================================================ FILE: registration.php ================================================

Consider sponsoring this extension

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

================================================ FILE: view/frontend/layout/hyva_catalog_category_view.xml ================================================ ================================================ FILE: view/frontend/layout/hyva_catalog_product_view.xml ================================================ ================================================ FILE: view/frontend/layout/hyva_default.xml ================================================ ================================================ FILE: view/frontend/layout/webp_test_images_image_with_custom_style.xml ================================================ Yireo\Webp2\Test\Utils\ImageProvider ================================================ FILE: view/frontend/layout/webp_test_images_multiple_existing_picturesets.xml ================================================ Yireo\Webp2\Test\Utils\ImageProvider ================================================ FILE: view/frontend/layout/webp_test_images_multiple_images.xml ================================================ Yireo\Webp2\Test\Utils\ImageProvider ================================================ FILE: view/frontend/layout/webp_test_images_multiple_images_same.xml ================================================ Yireo\Webp2\Test\Utils\ImageProvider ================================================ FILE: view/frontend/layout/webp_test_images_unknown_image.xml ================================================ Yireo\Webp2\Test\Utils\ImageProvider ================================================ FILE: view/frontend/requirejs-config.js ================================================ var config = { config: { mixins: { 'Magento_Swatches/js/swatch-renderer': { 'Yireo_Webp2/js/swatch-renderer-mixin': true }, 'mage/gallery/gallery': { 'Yireo_Webp2/js/gallery-mixin': true } } }, deps: [ 'Yireo_Webp2/js/add-webp-class-to-body' ] }; ================================================ FILE: view/frontend/templates/hyva/add-webp-class-to-body.phtml ================================================ ================================================ FILE: view/frontend/templates/hyva/gallery-additions.phtml ================================================ ================================================ FILE: view/frontend/templates/test/image_with_custom_style.phtml ================================================ getImageProvider(); $image = $imageProvider->getImage(); $imageUrl = $block->escapeUrl($block->getViewFileUrl('Yireo_Webp2/' . $image)); ?>

getNameInLayout() ?>

test sample

Layout handles

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

getNameInLayout() ?>

Layout handles

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

getNameInLayout() ?>

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

Layout handles

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

getNameInLayout() ?>

Layout handles

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

Layout handles

getLayout()->getUpdate()->getHandles()); ?>
================================================ FILE: view/frontend/web/js/add-webp-class-to-body.js ================================================ define([ 'jquery', './has-webp' ], function($, hasWebP) { if (hasWebP()) { $('body').addClass('webp'); } else { $('body').addClass('no-webp'); } }); ================================================ FILE: view/frontend/web/js/gallery-mixin.js ================================================ define([ 'jquery', './has-webp', "domReady!" ], function ($, hasWebP) { 'use strict'; var mixin = { initialize: function (config, element) { if (hasWebP()) { this._replaceImageDataWithWebp(config.data); } this._super(config, element); }, _replaceImageDataWithWebp: function (imagesData) { if (_.isEmpty(imagesData)) { return; } $.each(imagesData, function (key, imageData) { if (imageData['full_webp']) imageData['full'] = imageData['full_webp']; if (imageData['img_webp'])imageData['img'] = imageData['img_webp']; if (imageData['thumb_webp'])imageData['thumb'] = imageData['thumb_webp']; }); } }; return function (target) { return target.extend(mixin); } }); ================================================ FILE: view/frontend/web/js/has-webp.js ================================================ define([], function () { 'use strict'; return function hasWebP() { var elem = document.createElement('canvas'); if (!!(elem.getContext && elem.getContext('2d'))) { return elem.toDataURL('image/webp').indexOf('data:image/webp') === 0; } return false; } }); ================================================ FILE: view/frontend/web/js/swatch-renderer-mixin.js ================================================ define([ 'jquery', './has-webp', "domReady!" ], function ($, hasWebP) { 'use strict'; return function (widget) { $.widget('mage.SwatchRenderer', widget, { _init: function () { this._super(); if (hasWebP()) { $.each(this.options.jsonConfig.images, (function (key, imagesData) { $.each(imagesData, (function (key, imageData) { this._replaceImageData(imageData); }).bind(this)); }).bind(this)); } }, _ProductMediaCallback: function ($this, response, isInProductView) { if (hasWebP()) { this._replaceImageData(response); if (response.gallery) { $.each(response.gallery, (function (key, galleryImage) { this._replaceImageData(galleryImage); }).bind(this)); } } this._super($this, response, isInProductView); var productData = this._determineProductData(); let $pictureTag = $('.product-image-container-' + productData.productId + ' picture'); $pictureTag.find('source').remove(); }, _replaceImageData: function (imageData) { if (_.isEmpty(imageData)) { return imageData; } for (const [key, value] of Object.entries(imageData)) { if (imageData[key + '_webp']) { imageData[key] = imageData[key + '_webp']; } } return imageData; } }); return $.mage.SwatchRenderer; } });