Full Code of yireo/Yireo_Webp2 for AI

master e5bc07ccc0c8 cached
68 files
109.1 KB
30.4k tokens
67 symbols
1 requests
Download .txt
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
================================================
<?php // phpcs:ignoreFile

use Yireo\IntegrationTestHelper\Utilities\DisableModules;
use Yireo\IntegrationTestHelper\Utilities\InstallConfig;

$disableModules = (new DisableModules(__DIR__.'/../../../../'))
    ->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
================================================
<?php // phpcs:ignoreFile

return [
    'client-mariadb' => [
        'disable-ssl',
    ],
];



================================================
FILE: .github/workflows/integration-tests/phpunit10.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd"
         colors="true"
         columns="max"
         beStrictAboutTestsThatDoNotTestAnything="false"
         bootstrap="./framework/bootstrap.php"
         stderr="true">
    <testsuites>
        <testsuite name="LokiCheckout">
            <directory>../../../app/code/Yireo/LokiCheckout*/Test/Integration</directory>
            <directory>../../../vendor/yireo/magento2-loki-checkout*/Test/Integration</directory>
        </testsuite>
    </testsuites>
    <php>
        <includePath>.</includePath>
        <includePath>testsuite</includePath>
        <ini name="date.timezone" value="America/Los_Angeles"/>
        <ini name="xdebug.max_nesting_level" value="200"/>
        <const name="TESTS_INSTALL_CONFIG_FILE" value="etc/install-config-mysql.php"/>
        <const name="TESTS_GLOBAL_CONFIG_FILE" value="etc/config-global.php"/>
        <const name="TESTS_GLOBAL_CONFIG_DIR" value="../../../app/etc"/>
        <const name="TESTS_POST_INSTALL_SETUP_COMMAND_CONFIG_FILE" value="etc/post-install-setup-command-config.php"/>
        <const name="TESTS_CLEANUP" value="enabled"/>
        <const name="TESTS_MEM_USAGE_LIMIT" value="8192M"/>
        <const name="TESTS_MEM_LEAK_LIMIT" value=""/>
        <const name="TESTS_EXTRA_VERBOSE_LOG" value="1"/>
        <const name="TESTS_MAGENTO_MODE" value="developer"/>
        <const name="TESTS_ERROR_LOG_LISTENER_LEVEL" value="-1"/>
        <const name="USE_OVERRIDE_CONFIG" value="enabled"/>
    </php>
    <extensions>
        <bootstrap class="Magento\TestFramework\Event\Subscribers"/>
    </extensions>
</phpunit>


================================================
FILE: .github/workflows/integration-tests/phpunit9.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/9.6/phpunit.xsd"
         colors="true"
         beStrictAboutTestsThatDoNotTestAnything="false"
         bootstrap="./framework/bootstrap.php"
         stderr="true"
>
    <testsuites>
        <testsuite name="LokiCheckout">
            <directory>../../../app/code/Yireo/LokiCheckout*/Test/Integration</directory>
            <directory>../../../vendor/yireo/magento2-loki-checkout*/Test/Integration</directory>
        </testsuite>
    </testsuites>
    <php>
        <includePath>.</includePath>
        <includePath>testsuite</includePath>
        <ini name="date.timezone" value="America/Los_Angeles"/>
        <ini name="xdebug.max_nesting_level" value="200"/>
        <const name="TESTS_INSTALL_CONFIG_FILE" value="etc/install-config-mysql.php"/>
        <const name="TESTS_GLOBAL_CONFIG_FILE" value="etc/config-global.php"/>
        <const name="TESTS_GLOBAL_CONFIG_DIR" value="../../../app/etc"/>
        <const name="TESTS_POST_INSTALL_SETUP_COMMAND_CONFIG_FILE" value="etc/post-install-setup-command-config.php"/>
        <const name="TESTS_CLEANUP" value="enabled"/>
        <const name="TESTS_MEM_USAGE_LIMIT" value="8192M"/>
        <const name="TESTS_MEM_LEAK_LIMIT" value=""/>
        <const name="TESTS_EXTRA_VERBOSE_LOG" value="1"/>
        <const name="TESTS_MAGENTO_MODE" value="developer"/>
        <const name="TESTS_ERROR_LOG_LISTENER_LEVEL" value="-1"/>
    </php>
     <listeners>
         <listener class="Magento\TestFramework\Event\PhpUnit"/>
         <listener class="Magento\TestFramework\ErrorLog\Listener"/>
     </listeners>
</phpunit>


================================================
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
================================================
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

return [
    'db-host' => '%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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.1/phpunit.xsd"
         colors="true"
         beStrictAboutTestsThatDoNotTestAnything="false"
         bootstrap="./framework/bootstrap.php"
         stderr="true"
>
    <testsuites>
        <testsuite name="App">
            <directory suffix="Test.php">../../../vendor/yireo/*/Test/Integration</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">../../../vendor/yireo</directory>
            <exclude>
                <directory>../../../vendor/yireo/*/Test</directory>
            </exclude>
        </whitelist>
    </filter>
    <php>
        <includePath>.</includePath>
        <includePath>testsuite</includePath>
        <ini name="date.timezone" value="America/Los_Angeles"/>
        <ini name="xdebug.max_nesting_level" value="200"/>
        <const name="TESTS_INSTALL_CONFIG_FILE" value="etc/install-config-mysql.php"/>
        <const name="TESTS_GLOBAL_CONFIG_FILE" value="etc/config-global.php"/>
        <const name="TESTS_GLOBAL_CONFIG_DIR" value="../../../app/etc"/>
        <const name="TESTS_CLEANUP" value="enabled"/>
        <const name="TESTS_MEM_USAGE_LIMIT" value="1024M"/>
        <const name="TESTS_MEM_LEAK_LIMIT" value=""/>
        <const name="TESTS_EXTRA_VERBOSE_LOG" value="0"/>
        <const name="TESTS_MAGENTO_MODE" value="developer"/>
        <const name="TESTS_ERROR_LOG_LISTENER_LEVEL" value="-1"/>
    </php>
</phpunit>


================================================
FILE: .magento/dev/tests/unit/phpunit.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/6.2/phpunit.xsd"
         colors="true"
         beStrictAboutTestsThatDoNotTestAnything="false"
         bootstrap="../../../vendor/autoload.php"
         stderr="true"
>
    <testsuites>
        <testsuite name="App">
            <directory suffix="Test.php">../../../app/code/*/*/Test/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">../../../app/code</directory>
            <exclude>
                <directory>../../../app/code/*/*/Test</directory>
            </exclude>
        </whitelist>
    </filter>
    <php>
        <includePath>.</includePath>
        <includePath>testsuite</includePath>
        <ini name="date.timezone" value="America/Los_Angeles"/>
        <ini name="xdebug.max_nesting_level" value="200"/>
    </php>
</phpunit>


================================================
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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Config;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Yireo\NextGenImages\Config\Config as NextGenImagesConfig;
use Yireo\Webp2\Exception\InvalidConvertorException;

class Config implements ArgumentInterface
{
    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var NextGenImagesConfig
     */
    private $nextGenImagesConfig;

    /**
     * Config constructor.
     *
     * @param ScopeConfigInterface $scopeConfig
     * @param StoreManagerInterface $storeManager
     * @param NextGenImagesConfig $nextGenImagesConfig
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        StoreManagerInterface $storeManager,
        NextGenImagesConfig $nextGenImagesConfig
    ) {
        $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Config\Frontend;

use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;

class Funding extends Field
{
    protected $_template = 'Yireo_Webp2::funding.phtml';

    public function render(AbstractElement $element)
    {
        return $this->toHtml();
    }
}



================================================
FILE: Controller/Test/Images.php
================================================
<?php
declare(strict_types=1);

namespace Yireo\Webp2\Controller\Test;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;

class Images extends Action
{
    /**
     * @var PageFactory
     */
    protected $pageFactory;

    /**
     * Index constructor.
     *
     * @param Context     $context
     * @param PageFactory $pageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $pageFactory
    ) {
        parent::__construct($context);
        $this->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
================================================
<?php
declare(strict_types=1);

namespace Yireo\Webp2\Controller\Test;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Area;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\MailException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\View\Result\LayoutFactory;
use Magento\Framework\View\Result\Page;
use Magento\Store\Model\StoreManagerInterface;

class Mail extends Action
{
    /**
     * @var TransportBuilder
     */
    private $transportBuilder;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var LayoutFactory
     */
    private $layoutFactory;

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * @var JsonFactory
     */
    private $jsonFactory;

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var DeploymentConfig
     */
    private $config;

    /**
     * Mail constructor.
     * @param TransportBuilder $transportBuilder
     * @param StoreManagerInterface $storeManager
     * @param LayoutFactory $layoutFactory
     * @param RequestInterface $request
     * @param JsonFactory $jsonFactory
     * @param ScopeConfigInterface $scopeConfig
     * @param DeploymentConfig $config
     * @param Context $context
     */
    public function __construct(
        TransportBuilder $transportBuilder,
        StoreManagerInterface $storeManager,
        LayoutFactory $layoutFactory,
        RequestInterface $request,
        JsonFactory $jsonFactory,
        ScopeConfigInterface $scopeConfig,
        DeploymentConfig $config,
        Context $context
    ) {
        parent::__construct($context);
        $this->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
================================================
<?php
declare(strict_types=1);

namespace Yireo\Webp2\Convertor;

use Exception;
use Psr\Log\LoggerInterface;
use WebPConvert\Convert\Exceptions\ConversionFailed\InvalidInput\InvalidImageTypeException;
use WebPConvert\Convert\Exceptions\ConversionFailedException;
use WebPConvert\WebPConvert;
use Yireo\Webp2\Config\Config;
use Yireo\Webp2\Exception\InvalidConvertorException;

/**
 * Class ConvertWrapper to wrap third party wrapper for purpose of preference overrides and testing
 */
class ConvertWrapper
{
    /**
     * @var Config
     */
    private $config;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * ConvertWrapper constructor.
     * @param Config $config
     */
    public function __construct(
        Config $config,
        LoggerInterface $logger
    ) {
        $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Convertor;

use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\NoSuchEntityException;
use WebPConvert\Convert\Exceptions\ConversionFailed\InvalidInput\InvalidImageTypeException;
use WebPConvert\Convert\Exceptions\ConversionFailedException;
use Yireo\NextGenImages\Convertor\ConvertorInterface;
use Yireo\NextGenImages\Exception\ConvertorException;
use Yireo\NextGenImages\Image\Image;
use Yireo\NextGenImages\Image\ImageFactory;
use Yireo\NextGenImages\Image\TargetImageFactory;
use Yireo\NextGenImages\Util\File;
use Yireo\Webp2\Config\Config;
use Yireo\Webp2\Exception\InvalidConvertorException;
use WebPConvert\Exceptions\InvalidInput\InvalidImageTypeException as InvalidInputImageTypeException;
use WebPConvert\Exceptions\InvalidInputException;

class Convertor implements ConvertorInterface
{
    /**
     * @var Config
     */
    private $config;

    /**
     * @var File
     */
    private $imageFile;

    /**
     * @var ConvertWrapper
     */
    private $convertWrapper;

    /**
     * @var TargetImageFactory
     */
    private $targetImageFactory;

    /**
     * @var ImageFactory
     */
    private $imageFactory;

    /**
     * Convertor constructor.
     * @param Config $config
     * @param File $imageFile
     * @param ConvertWrapper $convertWrapper
     * @param TargetImageFactory $targetImageFactory
     * @param ImageFactory $imageFactory
     */
    public function __construct(
        Config $config,
        File $imageFile,
        ConvertWrapper $convertWrapper,
        TargetImageFactory $targetImageFactory,
        ImageFactory $imageFactory
    ) {
        $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Exception;

use Exception;

class InvalidConvertorException extends Exception
{
}


================================================
FILE: LICENSE.txt
================================================
Open Software License ("OSL") v. 3.0

This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work:

Licensed under the Open Software License version 3.0

1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following:

1.1. to reproduce the Original Work in copies, either alone or as part of a collective work;

1.2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work;

1.3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License;

1.4. to perform the Original Work publicly; and

1.5. to display the Original Work publicly. 

2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works.

3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work.

4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license.

5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c).

6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work.

7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer.

8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation.

9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c).

10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware.

11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License.

12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License.

13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable.

14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You.

16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under <insert your license name here>" 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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Model\Config\Source;

use Magento\Framework\Data\OptionSourceInterface;

class Encoding implements OptionSourceInterface
{
    public function toOptionArray()
    {
        return [
            ['value' => 'lossy', 'label' => 'Lossy'],
            ['value' => 'lossless', 'label' => 'Lossless'],
            ['value' => 'auto', 'label' => 'Auto (both lossy and lossless)'],
        ];
    }
}


================================================
FILE: Plugin/AddCspInlineScripts.php
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Plugin;

use Magento\Framework\View\Element\Template;
use Yireo\CspUtilities\Util\ReplaceInlineScripts;

class AddCspInlineScripts
{
    private ReplaceInlineScripts $replaceInlineScripts;

    public function __construct(
        ReplaceInlineScripts $replaceInlineScripts
    ) {
        $this->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
<img src="https://img.shields.io/packagist/dt/yireo/magento2-webp2"/> <img src="https://img.shields.io/packagist/v/yireo/magento2-webp2"/> <img src="https://img.shields.io/github/languages/top/yireo/Yireo_Webp2"/> <img src="https://img.shields.io/github/last-commit/yireo/Yireo_Webp2" /> <img src="https://img.shields.io/github/sponsors/yireo"/> <img src="https://img.shields.io/badge/Hyva_Themes-Supported-3df0af.svg?longCache=true" /> <img src="https://img.shields.io/twitter/follow/yireo?style=social" />

**This module adds WebP support to Magento 2.**

## About this module
- When `<img>` tags are found on the page, the corresponding JPG or PNG is converted into WebP and a corresponding `<picture` tag is used to replace the original `<img>` 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 `<picture>` 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
`<?php echo (int)function_exists('imagewebp');` to it: A `1` indicates that the function is available, a `0` indicates
that it is not. Alternatively you can check for WebP using the command `php -r 'var_dump(gd_info());'`. Make sure your CLI
binary is the same as the one being called by the webserver though.

An alternative is that the `cwebp` binary from the WebP project is uploaded to your server and placed in a generic folder like `/usr/local/bin`. Make sure to grab a copy from this binary from the [rosell-dk/webp-convert](https://github.com/rosell-dk/webp-convert/tree/master/src/Convert/Converters/Binaries) project. This method is preferred because it is the fastest. But it assumes also that the binary is placed in a folder by the server administrator.

We recommend you to work on making all options work, not just one.

Please note that both tasks should be simple for developers and system administrator, but might be magical for non-technical people. If this extension is not working out of the box for you, most likely a technical person needs to take a look at your hosting environment.

## FAQ

#### Does this module support GraphQL?
Yes, but only via the additional [Yireo Webp2GraphQl](https://github.com/yireo/Yireo_Webp2GraphQl) module

#### How do I know WebP is used?
Make sure to test things with the obvious caches disabled (Full Page Cache, Block HTML Cache). Once this extension is working, catalog images (like on a category page) should be replaced with: Their `<img>` tag should be replaced with a `<picture>` 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 (`<update handle="webp_skip" />`). 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 `<img>` tags are replaced with something similar to the following:
```html
<picture>
  <source type="image/webp" srcset="example.webp">
  <source type="image/png" srcset="example.png">
  <img src="example.png" />
</picture>
```

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
================================================
<?php declare(strict_types=1);
// phpcs:ignoreFile

namespace Yireo\Webp2\Setup;

use Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory;
use Magento\Framework\App\Config\Storage\WriterInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;

class UpgradeData implements UpgradeDataInterface
{
    /**
     * @var CollectionFactory
     */
    private $configCollectionFactory;

    /**
     * @var WriterInterface
     */
    private $storageWriter;

    /**
     * UpgradeData constructor.
     * @param CollectionFactory $configCollectionFactory
     * @param WriterInterface $storageWriter
     */
    public function __construct(
        CollectionFactory $configCollectionFactory,
        WriterInterface $storageWriter
    ) {

        $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Test\Integration;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\TestCase\AbstractController;
use RuntimeException;
use Yireo\Webp2\Convertor\ConvertWrapper;
use Yireo\Webp2\Test\Utils\ImageProvider;
use Yireo\Webp2\Test\Utils\ConvertWrapperStub;

class Common extends AbstractController
{
    protected function setUp(): void
    {
        parent::setUp();
        $convertWrapperStub = $this->_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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Test\Integration;

use Yireo\NextGenImages\Image\ImageFactory;
use Yireo\Webp2\Convertor\Convertor;

class ImageConversionTest extends Common
{
    /**
     * @@magentoConfigFixture current_store yireo_nextgenimages/settings/enabled 1
     * @@magentoConfigFixture current_store yireo_nextgenimages/settings/convert_images 1
     * @@magentoConfigFixture current_store yireo_webp2/settings/enabled 1
     * @@magentoConfigFixture current_store yireo_webp2/settings/debug 1
     */
    public function testIfHtmlContainsImageWithCustomStyle()
    {
        $images = $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Test\Integration;

class ImageWithCustomStyleTest extends Common
{
    /**
     * @magentoAppArea frontend
     * @magentoDbIsolation enabled
     * @magentoAppIsolation enabled
     * @magentoCache all disabled
     * @@magentoConfigFixture current_store yireo_nextgenimages/settings/enabled 1
     * @@magentoConfigFixture current_store yireo_nextgenimages/settings/convert_images 1
     * @@magentoConfigFixture current_store yireo_webp2/settings/enabled 1
     * @@magentoConfigFixture current_store dev/static/sign 0
     */
    public function testIfHtmlContainsImageWithCustomStyle()
    {
        $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Test\Integration;

use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\Module\ModuleList;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;

class ModuleTest extends TestCase
{
    /**
     * Test if the module is registered
     */
    public function testIfModuleIsRegistered()
    {
        $registrar = new ComponentRegistrar();
        $paths = $registrar->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Test\Integration;

use Magento\Framework\View\LayoutInterface;

class MultipleImagesSameTest extends Common
{
    /**
     * @magentoAdminConfigFixture yireo_nextgenimages/settings/enabled 1
     * @magentoAdminConfigFixture yireo_nextgenimages/settings/convert_images 1
     * @magentoAdminConfigFixture yireo_webp2/settings/enabled 1
     * @magentoAdminConfigFixture yireo_webp2/settings/debug 1
     */
    public function testIfHtmlContainsSingleWebpImage()
    {
        $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Test\Integration;

class MultipleImagesTest extends Common
{
    /**
     * @magentoAdminConfigFixture yireo_nextgenimages/settings/enabled 1
     * @magentoAdminConfigFixture yireo_nextgenimages/settings/convert_images 1
     * @magentoAdminConfigFixture yireo_webp2/settings/enabled 1
     * @magentoAdminConfigFixture yireo_webp2/settings/debug 1
     */
    public function testIfHtmlContainsWebpImages(): void
    {
        $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Test\Unit\Config;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\StoreManagerInterface;
use PHPUnit\Framework\TestCase;
use Yireo\NextGenImages\Config\Config as NextGenImagesConfig;
use Yireo\Webp2\Config\Config;

class ConfigTest extends TestCase
{
    public function testEnabled()
    {
        $scopeConfig = $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Test\Unit\Convertor;

use PHPUnit\Framework\TestCase;
use Yireo\NextGenImages\Exception\ConvertorException;
use Yireo\NextGenImages\Image\TargetImageFactory;
use Yireo\NextGenImages\Util\File;
use Yireo\NextGenImages\Image\Image;
use Yireo\NextGenImages\Image\ImageFactory;
use Yireo\Webp2\Config\Config;
use Yireo\Webp2\Convertor\Convertor;
use Yireo\Webp2\Convertor\ConvertWrapper;

class ConvertorTest extends TestCase
{
    /**
     * Test for Yireo\Webp2\Convertor\Convertor::getImage
     */
    public function testGetImage()
    {
        $config = $this->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
================================================
<?php declare(strict_types=1);

namespace Yireo\Webp2\Test\Utils;

use Yireo\Webp2\Convertor\ConvertWrapper;

/**
 * Class ConvertWrapper to wrap third party wrapper for purpose of preference overrides and testing
 */
class ConvertWrapperStub extends ConvertWrapper
{
    /**
     * @param string $sourceImageFilename
     * @param string $destinationImageFilename
     */
    public function convert(string $sourceImageFilename, string $destinationImageFilename): void
    {
        copy($sourceImageFilename, $destinationImageFilename);
    }
}


================================================
FILE: Test/Utils/ImageProvider.php
================================================
<?php
declare(strict_types=1);

namespace Yireo\Webp2\Test\Utils;

use Magento\Framework\View\Element\Block\ArgumentInterface;

class ImageProvider implements ArgumentInterface
{
    /**
     * @return string[]
     */
    public function getImages(): array
    {
        return [
            'images/test/flowers.jpg',
            'images/test/goku.jpg',
            'images/test/transparent-dragon.png',
        ];
    }

    /**
     * @return string
     */
    public function getImage(): string
    {
        $images = $this->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
================================================
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Yireo_Webp2::config" title="Yireo_Webp2" sortOrder="100"/>
            </resource>
        </resources>
    </acl>
</config>


================================================
FILE: etc/adminhtml/system.xml
================================================
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="yireo" sortOrder="999" translate="label">
            <label>Yireo</label>
        </tab>
        <section id="yireo_webp2" translate="label" sortOrder="342" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Yireo WebP2</label>
            <tab>yireo</tab>
            <resource>Yireo_Webp2::config</resource>
            <group id="settings" translate="label" type="text" sortOrder="34" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Settings</label>
                <field id="funding" type="note" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Funding</label>
                    <frontend_model>Yireo\Webp2\Config\Frontend\Funding</frontend_model>
                </field>
                <field id="enabled" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Enabled</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="quality_level" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Quality level</label>
                    <comment><![CDATA[Between 0 and 100]]></comment>
                    <depends>
                        <field id="*/*/enabled">1</field>
                    </depends>
                </field>
                <field id="module_version" translate="label" type="select" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Module version</label>
                    <frontend_model>Yireo\Webp2\VirtualType\Block\Adminhtml\System\Config\ModuleVersion</frontend_model>
                    <depends>
                        <field id="*/*/enabled">1</field>
                    </depends>
                </field>
                <field id="convertors" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Convertors</label>
                    <comment><![CDATA[Allowed values: cwebp,gd,imagick,wpc,ewww]]></comment>
                    <depends>
                        <field id="*/*/enabled">1</field>
                    </depends>
                </field>
                <field id="encoding" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Encoding</label>
                    <source_model>Yireo\Webp2\Model\Config\Source\Encoding</source_model>
                    <comment><![CDATA[Allowed values: lossy,lossless,auto]]></comment>
                    <depends>
                        <field id="*/*/enabled">1</field>
                    </depends>
                </field>
            </group>
        </section>
    </system>
</config>


================================================
FILE: etc/config.xml
================================================
<?xml version="1.0"?>
<!--
/**
 * Yireo Webp2 for Magento
 *
 * @author      Yireo (https://www.yireo.com/)
 * @copyright   Copyright 2019 Yireo (https://www.yireo.com/)
 * @license     Open Source License (OSL v3)
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <yireo_webp2>
            <settings>
                <enabled>1</enabled>
                <quality_level>80</quality_level>
                <convertors>cwebp,gd,imagick,wpc,ewww</convertors>
                <encoding>lossy</encoding>
            </settings>
        </yireo_webp2>
    </default>
</config>


================================================
FILE: etc/di.xml
================================================
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Yireo\NextGenImages\Convertor\ConvertorListing">
        <arguments>
            <argument name="convertors" xsi:type="array">
                <item name="webp2" xsi:type="object">Yireo\Webp2\Convertor\Convertor</item>
            </argument>
        </arguments>
    </type>

    <virtualType name="Yireo\Webp2\VirtualType\Block\Adminhtml\System\Config\ModuleVersion" type="Yireo\NextGenImages\Block\Adminhtml\System\Config\ModuleVersion">
        <arguments>
            <argument name="moduleName" xsi:type="string">Yireo_Webp2</argument>
        </arguments>
    </virtualType>
</config>


================================================
FILE: etc/frontend/di.xml
================================================
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\View\Element\Template">
        <plugin name="Yireo_Webp2::addCspInlineScripts" type="Yireo\Webp2\Plugin\AddCspInlineScripts"/>
    </type>
</config>


================================================
FILE: etc/frontend/routes.xml
================================================
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="webp" id="webp">
            <module name="Yireo_Webp2"/>
        </route>
    </router>
</config>

================================================
FILE: etc/module.xml
================================================
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Yireo_Webp2" setup_version="0.4.0">
        <sequence>
            <module name="Yireo_NextGenImages" />
            <module name="Yireo_CspUtilities" />
            <module name="Magento_Backend" />
            <module name="Magento_Config" />
            <module name="Magento_Store" />
        </sequence>
    </module>
</config>


================================================
FILE: phpstan.neon
================================================
parameters:
    excludePaths:
        - */Test/*/*


================================================
FILE: registration.php
================================================
<?php
/**
 * Webp2 module for Magento
 *
 * @author      Yireo (https://www.yireo.com/)
 * @copyright   Copyright 2019 Yireo (https://www.yireo.com/)
 * @license     Open Source License
 */

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Yireo_Webp2',
    __DIR__
);


================================================
FILE: view/adminhtml/templates/funding.phtml
================================================
<?php
?>
<div class="yireo-funding">
    <div class="github-logo">
        <svg xmlns="http://www.w3.org/2000/svg" height="800" width="1200" viewBox="-74.4 -120.90175 644.8 725.4105">
            <path
                d="M165.9 389.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2 .6-2-1.3-4.3-4.3-5.2-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 0C106.1 0 0 105.3 0 244c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5 21.3 0 42.8 2.9 62.8 8.5 0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 449.8 496 354.9 496 244 496 105.3 383.5 0 244.8 0zM97.2 344.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/>
        </svg>
    </div>
    <div class="details">
        <h3>Consider sponsoring this extension</h3>
        <p>
            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.
        </p>
        <ul>
            <li><a href="https://github.com/sponsors/jissereitsma">https://github.com/sponsors/jissereitsma</a></li>
            <li><a href="https://github.com/sponsors/yireo">https://github.com/sponsors/yireo</a></li>
        </ul>
    </div>
</div>

<style>
    .yireo-funding {
        display: flex;
        background: #f8f8f8;
        border: 1px solid #e3e3e3;
        padding: 30px;
    }

    .yireo-funding .github-logo {
        width: 150px;
        min-width: 150px;
        margin-right: 10px;
    }

    .yireo-funding .github-logo svg {
        width: 100%;
        height: auto;
    }

    .yireo-funding .details ul {
        margin-left: 20px;
    }
</style>


================================================
FILE: view/frontend/layout/hyva_catalog_category_view.xml
================================================
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:View/Layout:etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block name="yireo_webp2.gallery-additions" template="Yireo_Webp2::hyva/gallery-additions.phtml"/>
        </referenceContainer>
    </body>
</page>


================================================
FILE: view/frontend/layout/hyva_catalog_product_view.xml
================================================
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:View/Layout:etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block name="yireo_webp2.gallery-additions" template="Yireo_Webp2::hyva/gallery-additions.phtml"/>
        </referenceContainer>
    </body>
</page>


================================================
FILE: view/frontend/layout/hyva_default.xml
================================================
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:View/Layout:etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block name="yireo_webp2.add-webp-class-to-body" template="Yireo_Webp2::hyva/add-webp-class-to-body.phtml"/>
        </referenceContainer>
    </body>
</page>


================================================
FILE: view/frontend/layout/webp_test_images_image_with_custom_style.xml
================================================
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="empty">
    <body>
        <referenceContainer name="main">
            <block name="webp-multiple-image-with-custom-style" template="Yireo_Webp2::test/image_with_custom_style.phtml" before="-">
                <arguments>
                    <argument name="image_provider" xsi:type="object">Yireo\Webp2\Test\Utils\ImageProvider</argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>


================================================
FILE: view/frontend/layout/webp_test_images_multiple_existing_picturesets.xml
================================================
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="empty">
    <body>
        <referenceContainer name="main">
            <block name="webp-multiple-existing-imagesets" template="Yireo_Webp2::test/multiple_existing_picturesets.phtml" before="-">
                <arguments>
                    <argument name="image_provider" xsi:type="object">Yireo\Webp2\Test\Utils\ImageProvider</argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>


================================================
FILE: view/frontend/layout/webp_test_images_multiple_images.xml
================================================
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="empty">
    <body>
        <referenceContainer name="main">
            <block name="webp-multiple-images" template="Yireo_Webp2::test/multiple_images.phtml" before="-">
                <arguments>
                    <argument name="image_provider" xsi:type="object">Yireo\Webp2\Test\Utils\ImageProvider</argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>


================================================
FILE: view/frontend/layout/webp_test_images_multiple_images_same.xml
================================================
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="empty">
    <body>
        <referenceContainer name="main">
            <block name="webp-multiple-images-same" template="Yireo_Webp2::test/multiple_images_same.phtml" before="-">
                <arguments>
                    <argument name="image_provider" xsi:type="object">Yireo\Webp2\Test\Utils\ImageProvider</argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>


================================================
FILE: view/frontend/layout/webp_test_images_unknown_image.xml
================================================
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="empty">
    <body>
        <referenceContainer name="main">
            <block name="webp-multiple-images" template="Yireo_Webp2::test/unknown_image.phtml" before="-">
                <arguments>
                    <argument name="image_provider" xsi:type="object">Yireo\Webp2\Test\Utils\ImageProvider</argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>


================================================
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
================================================
<?php declare(strict_types=1); ?> <script>
    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;
    }

    if (hasWebP()) {
        document.body.classList.add("webp");
    } else {
        document.body.classList.add("no-webp");
    }</script>

================================================
FILE: view/frontend/templates/hyva/gallery-additions.phtml
================================================
<script>
    const yireoWebp2ReplaceImage = function (image) {
        if (image.full && image.full_webp) {
            image.full = image.full_webp;
            delete image.full_webp;
        }

        if (image.img && image.img_webp) {
            image.img = image.img_webp;
            delete image.img_webp;
        }

        if (image.thumb && image.thumb_webp) {
            image.thumb = image.thumb_webp;
            delete image.thumb_webp;
        }

        return image;
    }

    document.addEventListener('after-product-item-image-update', ({detail: element}) => {
        if (typeof hasWebP != 'function') {
            console.error('[Yireo_WebP2] JavaScript function "hasWebP" does not exist');
            return;
        }

        const imageUrl = element.src;
        const webpUrl = imageUrl.replace(/.jpg$/, '.webp');
        const picture = element.closest('picture');
        const webpSource = picture.querySelector('source[type="image/webp"]');
        webpSource.srcset = webpUrl;
    });

    document.addEventListener('configurable-options-init', ({detail: optionConfig}) => {
        if (typeof hasWebP != 'function') {
            console.error('[Yireo_WebP2] JavaScript function "hasWebP" does not exist');
            return;
        }

        if (optionConfig.images) {
            Object.entries(optionConfig.images).forEach(([key, imageArray]) => {
                Object.entries(imageArray).forEach(([index, image]) => {
                    imageArray[index] = yireoWebp2ReplaceImage(image);
                });
                optionConfig.images[key] = imageArray;
            });
        }
    });

    document.addEventListener('gallery-init', ({detail: galleryData}) => {
        if (typeof hasWebP != 'function') {
            console.error('[Yireo_WebP2] JavaScript function "hasWebP" does not exist');
            return;
        }

        if (galleryData.images) {
            galleryData.images.forEach(function (image) {
                yireoWebp2ReplaceImage(image);
            });
        }

        if (galleryData.initialImages) {
            galleryData.initialImages.forEach(function (image) {
                yireoWebp2ReplaceImage(image);
            });
        }

    });</script>


================================================
FILE: view/frontend/templates/test/image_with_custom_style.phtml
================================================
<?php declare(strict_types=1); /** @var $block \Magento\Framework\View\Element\Template */ /** @var $imageProvider \Yireo\Webp2\Test\Utils\ImageProvider */ $imageProvider = $block->getImageProvider(); $image = $imageProvider->getImage(); $imageUrl = $block->escapeUrl($block->getViewFileUrl('Yireo_Webp2/' . $image)); ?> <h1><?= /* @noEscape */ $block->getNameInLayout() ?></h1><img class="alt-img" src="<?= /* @noEscape */ $imageUrl ?>" alt="test sample" style="display:insane; opacity:666;"><h2>Layout handles</h2><pre><?= implode(', ', /* @noEscape */ $block->getLayout()->getUpdate()->getHandles()); ?></pre>

================================================
FILE: view/frontend/templates/test/multiple_existing_picturesets.phtml
================================================
<?php declare(strict_types=1); /** @var $block \Magento\Framework\View\Element\Template */ /** @var $imageProvider \Yireo\Webp2\Test\Utils\ImageProvider */ $imageProvider = $block->getImageProvider(); $images = $imageProvider->getImages(); $imageUrl = $block->escapeUrl($block->getViewFileUrl('Yireo_Webp2/' . $image)); ?> <h1><?= /* @noEscape */ $block->getNameInLayout() ?></h1><?php foreach ($images as $image): ?> <div><picture><img src="<?= /* @noEscape */ $imageUrl ?>" width="100" height="100"/></picture></div><?php endforeach; ?> <h2>Layout handles</h2><pre><?= implode(', ', /* @noEscape */ $block->getLayout()->getUpdate()->getHandles()); ?></pre>

================================================
FILE: view/frontend/templates/test/multiple_images.phtml
================================================
<?php declare(strict_types=1); /** @var $block \Magento\Framework\View\Element\Template */ /** @var $imageProvider \Yireo\Webp2\Test\Utils\ImageProvider */ $imageProvider = $block->getImageProvider(); $images = $imageProvider->getImages(); ?> <h1><?= /* @noEscape */ $block->getNameInLayout() ?></h1><?php foreach ($images as $image): ?> <?php $imageUrl = $block->escapeUrl($block->getViewFileUrl('Yireo_Webp2/' . $image)); ?> <div><img src="<?= /* @noEscape */ $imageUrl ?>" width="100" height="100"/></div><?php endforeach; ?> <h2>Layout handles</h2><pre><?= implode(', ', /* @noEscape */ $block->getLayout()->getUpdate()->getHandles()); ?></pre>

================================================
FILE: view/frontend/templates/test/multiple_images_same.phtml
================================================
<?php declare(strict_types=1); /** @var $block \Magento\Framework\View\Element\Template */ /** @var $imageProvider \Yireo\Webp2\Test\Utils\ImageProvider */ $imageProvider = $block->getImageProvider(); $image = $imageProvider->getImage(); ?> <h1><?= /* @noEscape */$block->getNameInLayout() ?></h1><?php for ($i = 0; $i < 3; $i++): ?> <div><img src="<?= $block->escapeUrl($block->getViewFileUrl('Yireo_Webp2/' . $image)) ?>" width="100" height="100"/></div><?php endfor; ?> <h2>Layout handles</h2><pre><?= implode(', ', /* @noEscape */ $block->getLayout()->getUpdate()->getHandles()); ?></pre>

================================================
FILE: view/frontend/templates/test/unknown_image.phtml
================================================
<?php declare(strict_types=1); /** @var $block \Magento\Framework\View\Element\Template */ ?> <img src="https://example.com/some/non/existing/image.png" alt="" width="10px"><h2>Layout handles</h2><pre><?= implode(', ', /* @noEscape */ $block->getLayout()->getUpdate()->getHandles()); ?></pre>

================================================
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;
    }
});
Download .txt
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
Download .txt
SYMBOL INDEX (67 symbols across 20 files)

FILE: Config/Config.php
  class Config (line 13) | class Config implements ArgumentInterface
    method __construct (line 37) | public function __construct(
    method enabled (line 50) | public function enabled(): bool
    method allowImageCreation (line 58) | public function allowImageCreation(): bool
    method getQualityLevel (line 66) | public function getQualityLevel(): int
    method getConvertors (line 84) | public function getConvertors(): array
    method getEncoding (line 106) | public function getEncoding(): string
    method getValue (line 125) | private function getValue(string $path)
    method stringToArray (line 142) | private function stringToArray(string $string): array

FILE: Config/Frontend/Funding.php
  class Funding (line 8) | class Funding extends Field
    method render (line 12) | public function render(AbstractElement $element)

FILE: Controller/Test/Images.php
  class Images (line 11) | class Images extends Action
    method __construct (line 24) | public function __construct(
    method execute (line 35) | public function execute()

FILE: Controller/Test/Mail.php
  class Mail (line 23) | class Mail extends Action
    method __construct (line 71) | public function __construct(
    method execute (line 97) | public function execute(): ResultInterface
    method sendResult (line 150) | private function sendResult(array $data): ResultInterface

FILE: Convertor/ConvertWrapper.php
  class ConvertWrapper (line 17) | class ConvertWrapper
    method __construct (line 33) | public function __construct(
    method convert (line 48) | public function convert(string $sourceImageFilename, string $destinati...
    method getOptions (line 70) | public function getOptions(): array

FILE: Convertor/Convertor.php
  class Convertor (line 20) | class Convertor implements ConvertorInterface
    method __construct (line 55) | public function __construct(
    method convertImage (line 75) | public function convertImage(Image $image): Image
    method convert (line 105) | private function convert(string $sourceImagePath, string $targetImageP...
    method convertSrcSet (line 130) | private function convertSrcSet(Image $image): string

FILE: Exception/InvalidConvertorException.php
  class InvalidConvertorException (line 7) | class InvalidConvertorException extends Exception

FILE: Model/Config/Source/Encoding.php
  class Encoding (line 7) | class Encoding implements OptionSourceInterface
    method toOptionArray (line 9) | public function toOptionArray()

FILE: Plugin/AddCspInlineScripts.php
  class AddCspInlineScripts (line 8) | class AddCspInlineScripts
    method __construct (line 12) | public function __construct(
    method afterToHtml (line 18) | public function afterToHtml(Template $block, $html): string

FILE: Setup/UpgradeData.php
  class UpgradeData (line 12) | class UpgradeData implements UpgradeDataInterface
    method __construct (line 29) | public function __construct(
    method upgrade (line 43) | public function upgrade(ModuleDataSetupInterface $setup, ModuleContext...

FILE: Test/Integration/Common.php
  class Common (line 14) | class Common extends AbstractController
    method setUp (line 16) | protected function setUp(): void
    method fixtureImageFiles (line 26) | protected function fixtureImageFiles(): array
    method getImageProvider (line 71) | protected function getImageProvider(): ImageProvider
    method assertImageTagsExist (line 80) | protected function assertImageTagsExist(string $body, array $images)

FILE: Test/Integration/ImageConversionTest.php
  class ImageConversionTest (line 8) | class ImageConversionTest extends Common
    method testIfHtmlContainsImageWithCustomStyle (line 16) | public function testIfHtmlContainsImageWithCustomStyle()

FILE: Test/Integration/ImageWithCustomStyleTest.php
  class ImageWithCustomStyleTest (line 5) | class ImageWithCustomStyleTest extends Common
    method testIfHtmlContainsImageWithCustomStyle (line 17) | public function testIfHtmlContainsImageWithCustomStyle()

FILE: Test/Integration/ModuleTest.php
  class ModuleTest (line 10) | class ModuleTest extends TestCase
    method testIfModuleIsRegistered (line 15) | public function testIfModuleIsRegistered()
    method testIfModuleIsKnownAndEnabled (line 25) | public function testIfModuleIsKnownAndEnabled()

FILE: Test/Integration/MultipleImagesSameTest.php
  class MultipleImagesSameTest (line 7) | class MultipleImagesSameTest extends Common
    method testIfHtmlContainsSingleWebpImage (line 15) | public function testIfHtmlContainsSingleWebpImage()

FILE: Test/Integration/MultipleImagesTest.php
  class MultipleImagesTest (line 5) | class MultipleImagesTest extends Common
    method testIfHtmlContainsWebpImages (line 13) | public function testIfHtmlContainsWebpImages(): void

FILE: Test/Unit/Config/ConfigTest.php
  class ConfigTest (line 11) | class ConfigTest extends TestCase
    method testEnabled (line 13) | public function testEnabled()
    method testGetQualityLevel (line 25) | public function testGetQualityLevel()
    method testGetConvertors (line 49) | public function testGetConvertors()

FILE: Test/Unit/Convertor/ConvertorTest.php
  class ConvertorTest (line 15) | class ConvertorTest extends TestCase
    method testGetImage (line 20) | public function testGetImage()
    method testConvert (line 34) | public function testConvert()
    method testItWillConvertSrcSetIfFound (line 45) | public function testItWillConvertSrcSetIfFound()
    method getConvertor (line 88) | private function getConvertor(?Config $config = null): Convertor

FILE: Test/Utils/ConvertWrapperStub.php
  class ConvertWrapperStub (line 10) | class ConvertWrapperStub extends ConvertWrapper
    method convert (line 16) | public function convert(string $sourceImageFilename, string $destinati...

FILE: Test/Utils/ImageProvider.php
  class ImageProvider (line 8) | class ImageProvider implements ArgumentInterface
    method getImages (line 13) | public function getImages(): array
    method getImage (line 25) | public function getImage(): string
    method getNonExistingImage (line 34) | public function getNonExistingImage(): string
Condensed preview — 68 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (120K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 55,
    "preview": "github: yireo\ncustom: [\"https://www.paypal.me/yireo\"]\n\n"
  },
  {
    "path": ".github/workflows/compile.yml",
    "chars": 1614,
    "preview": "name: Magento 2 DI compilation\non: ['push', 'pull_request']\n\njobs:\n  compile:\n    name: Magento 2 DI compilation\n    #ru"
  },
  {
    "path": ".github/workflows/integration-tests/etc/install-config-mysql.php",
    "chars": 641,
    "preview": "<?php // phpcs:ignoreFile\n\nuse Yireo\\IntegrationTestHelper\\Utilities\\DisableModules;\nuse Yireo\\IntegrationTestHelper\\Uti"
  },
  {
    "path": ".github/workflows/integration-tests/etc/mysql-client-config.php",
    "chars": 96,
    "preview": "<?php // phpcs:ignoreFile\n\nreturn [\n    'client-mariadb' => [\n        'disable-ssl',\n    ],\n];\n\n"
  },
  {
    "path": ".github/workflows/integration-tests/phpunit10.xml",
    "chars": 1863,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n/**\n * Copyright © Magento, Inc. All rights reserved.\n * See COPYING.txt for"
  },
  {
    "path": ".github/workflows/integration-tests/phpunit9.xml",
    "chars": 1737,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:noNam"
  },
  {
    "path": ".github/workflows/integration-tests.yml",
    "chars": 3186,
    "preview": "name: Magento 2 Integration Tests\non: ['push', 'pull_request']\n\njobs:\n  integration-tests:\n    name: Magento 2 Integrati"
  },
  {
    "path": ".github/workflows/static-tests.yml",
    "chars": 2913,
    "preview": "name: Magento 2 Static Tests\non: ['push', 'pull_request']\n\njobs:\n  phpcs:\n    name: Magento PHPCS\n    runs-on: ubuntu-la"
  },
  {
    "path": ".github/workflows/unit-tests.yml",
    "chars": 1498,
    "preview": "name: Magento 2 Unit Tests\non: ['push', 'pull_request']\n\njobs:\n  unit-tests:\n    name: Magento 2 Unit Tests\n    #runs-on"
  },
  {
    "path": ".gitignore",
    "chars": 0,
    "preview": ""
  },
  {
    "path": ".magento/dev/tests/integration/etc/install-config-mysql.phps",
    "chars": 668,
    "preview": "<?php\n/**\n * Copyright © Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\nreturn [\n    'd"
  },
  {
    "path": ".magento/dev/tests/integration/phpunit.xml",
    "chars": 1599,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:noNam"
  },
  {
    "path": ".magento/dev/tests/unit/phpunit.xml",
    "chars": 994,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:noNam"
  },
  {
    "path": ".module.ini",
    "chars": 146,
    "preview": "EXTENSION_VENDOR=\"Yireo\"\nEXTENSION_NAME=\"Webp2\"\nMODULE_NAME=\"Yireo_Webp2\"\nCOMPOSER_NAME=\"yireo/magento2-webp2\"\nPHP_VERSI"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 9229,
    "preview": "# Changelog\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changel"
  },
  {
    "path": "Config/Config.php",
    "chars": 3967,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Config;\n\nuse Magento\\Framework\\App\\Config\\ScopeConfigInterface;\nus"
  },
  {
    "path": "Config/Frontend/Funding.php",
    "chars": 369,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Config\\Frontend;\n\nuse Magento\\Config\\Block\\System\\Config\\Form\\Fiel"
  },
  {
    "path": "Controller/Test/Images.php",
    "chars": 1015,
    "preview": "<?php\ndeclare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Controller\\Test;\n\nuse Magento\\Framework\\App\\Action\\Action;\nuse Mag"
  },
  {
    "path": "Controller/Test/Mail.php",
    "chars": 4504,
    "preview": "<?php\ndeclare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Controller\\Test;\n\nuse Magento\\Framework\\App\\Action\\Action;\nuse Mag"
  },
  {
    "path": "Convertor/ConvertWrapper.php",
    "chars": 2155,
    "preview": "<?php\ndeclare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Convertor;\n\nuse Exception;\nuse Psr\\Log\\LoggerInterface;\nuse WebPCo"
  },
  {
    "path": "Convertor/Convertor.php",
    "chars": 5147,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Convertor;\n\nuse Magento\\Framework\\Exception\\FileSystemException;\nu"
  },
  {
    "path": "Exception/InvalidConvertorException.php",
    "chars": 136,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Exception;\n\nuse Exception;\n\nclass InvalidConvertorException extend"
  },
  {
    "path": "LICENSE.txt",
    "chars": 10287,
    "preview": "Open Software License (\"OSL\") v. 3.0\n\nThis Open Software License (the \"License\") applies to any original work of authors"
  },
  {
    "path": "Model/Config/Source/Encoding.php",
    "chars": 447,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Model\\Config\\Source;\n\nuse Magento\\Framework\\Data\\OptionSourceInter"
  },
  {
    "path": "Plugin/AddCspInlineScripts.php",
    "chars": 678,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Plugin;\n\nuse Magento\\Framework\\View\\Element\\Template;\nuse Yireo\\Cs"
  },
  {
    "path": "README.md",
    "chars": 13562,
    "preview": "# Magento 2 module for WebP\n<img src=\"https://img.shields.io/packagist/dt/yireo/magento2-webp2\"/> <img src=\"https://img."
  },
  {
    "path": "Setup/UpgradeData.php",
    "chars": 1911,
    "preview": "<?php declare(strict_types=1);\n// phpcs:ignoreFile\n\nnamespace Yireo\\Webp2\\Setup;\n\nuse Magento\\Config\\Model\\ResourceModel"
  },
  {
    "path": "Test/Integration/Common.php",
    "chars": 3315,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Integration;\n\nuse Magento\\Framework\\App\\Filesystem\\DirectoryL"
  },
  {
    "path": "Test/Integration/ImageConversionTest.php",
    "chars": 969,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Integration;\n\nuse Yireo\\NextGenImages\\Image\\ImageFactory;\nuse"
  },
  {
    "path": "Test/Integration/ImageWithCustomStyleTest.php",
    "chars": 1328,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Integration;\n\nclass ImageWithCustomStyleTest extends Common\n{"
  },
  {
    "path": "Test/Integration/ModuleTest.php",
    "chars": 944,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Integration;\n\nuse Magento\\Framework\\Component\\ComponentRegist"
  },
  {
    "path": "Test/Integration/MultipleImagesSameTest.php",
    "chars": 1192,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Integration;\n\nuse Magento\\Framework\\View\\LayoutInterface;\n\ncl"
  },
  {
    "path": "Test/Integration/MultipleImagesTest.php",
    "chars": 1129,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Integration;\n\nclass MultipleImagesTest extends Common\n{\n    /"
  },
  {
    "path": "Test/Unit/Config/ConfigTest.php",
    "chars": 2488,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Unit\\Config;\n\nuse Magento\\Framework\\App\\Config\\ScopeConfigInt"
  },
  {
    "path": "Test/Unit/Convertor/ConvertorTest.php",
    "chars": 3814,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Unit\\Convertor;\n\nuse PHPUnit\\Framework\\TestCase;\nuse Yireo\\Ne"
  },
  {
    "path": "Test/Utils/ConvertWrapperStub.php",
    "chars": 547,
    "preview": "<?php declare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Utils;\n\nuse Yireo\\Webp2\\Convertor\\ConvertWrapper;\n\n/**\n * Cla"
  },
  {
    "path": "Test/Utils/ImageProvider.php",
    "chars": 728,
    "preview": "<?php\ndeclare(strict_types=1);\n\nnamespace Yireo\\Webp2\\Test\\Utils;\n\nuse Magento\\Framework\\View\\Element\\Block\\ArgumentInte"
  },
  {
    "path": "composer.json",
    "chars": 2054,
    "preview": "{\n    \"name\": \"yireo/magento2-webp2\",\n    \"license\": \"OSL-3.0\",\n    \"version\": \"0.14.3\",\n    \"type\": \"magento2-module\",\n"
  },
  {
    "path": "etc/acl.xml",
    "chars": 408,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSche"
  },
  {
    "path": "etc/adminhtml/system.xml",
    "chars": 3186,
    "preview": "<?xml version=\"1.0\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:m"
  },
  {
    "path": "etc/config.xml",
    "chars": 694,
    "preview": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Yireo Webp2 for Magento\n *\n * @author      Yireo (https://www.yireo.com/)\n * @copyrigh"
  },
  {
    "path": "etc/di.xml",
    "chars": 784,
    "preview": "<?xml version=\"1.0\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n        xsi:noNamespaceSchemaLocatio"
  },
  {
    "path": "etc/frontend/di.xml",
    "chars": 360,
    "preview": "<?xml version=\"1.0\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n        xsi:noNamespaceSchemaLocatio"
  },
  {
    "path": "etc/frontend/routes.xml",
    "chars": 310,
    "preview": "<?xml version=\"1.0\" ?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:"
  },
  {
    "path": "etc/module.xml",
    "chars": 512,
    "preview": "<?xml version=\"1.0\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:m"
  },
  {
    "path": "phpstan.neon",
    "chars": 51,
    "preview": "parameters:\n    excludePaths:\n        - */Test/*/*\n"
  },
  {
    "path": "registration.php",
    "chars": 340,
    "preview": "<?php\n/**\n * Webp2 module for Magento\n *\n * @author      Yireo (https://www.yireo.com/)\n * @copyright   Copyright 2019 Y"
  },
  {
    "path": "view/adminhtml/templates/funding.phtml",
    "chars": 2780,
    "preview": "<?php\n?>\n<div class=\"yireo-funding\">\n    <div class=\"github-logo\">\n        <svg xmlns=\"http://www.w3.org/2000/svg\" heigh"
  },
  {
    "path": "view/frontend/layout/hyva_catalog_category_view.xml",
    "chars": 395,
    "preview": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n      xsi:noNamespaceSchemaLocation=\"u"
  },
  {
    "path": "view/frontend/layout/hyva_catalog_product_view.xml",
    "chars": 395,
    "preview": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n      xsi:noNamespaceSchemaLocation=\"u"
  },
  {
    "path": "view/frontend/layout/hyva_default.xml",
    "chars": 405,
    "preview": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n      xsi:noNamespaceSchemaLocation=\"u"
  },
  {
    "path": "view/frontend/layout/webp_test_images_image_with_custom_style.xml",
    "chars": 624,
    "preview": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:mag"
  },
  {
    "path": "view/frontend/layout/webp_test_images_multiple_existing_picturesets.xml",
    "chars": 625,
    "preview": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:mag"
  },
  {
    "path": "view/frontend/layout/webp_test_images_multiple_images.xml",
    "chars": 599,
    "preview": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:mag"
  },
  {
    "path": "view/frontend/layout/webp_test_images_multiple_images_same.xml",
    "chars": 609,
    "preview": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:mag"
  },
  {
    "path": "view/frontend/layout/webp_test_images_unknown_image.xml",
    "chars": 597,
    "preview": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:mag"
  },
  {
    "path": "view/frontend/requirejs-config.js",
    "chars": 367,
    "preview": "var config = {\n    config: {\n        mixins: {\n            'Magento_Swatches/js/swatch-renderer': {\n                'Yir"
  },
  {
    "path": "view/frontend/templates/hyva/add-webp-class-to-body.phtml",
    "chars": 444,
    "preview": "<?php declare(strict_types=1); ?> <script>\n    function hasWebP() {\n        var elem = document.createElement('canvas');"
  },
  {
    "path": "view/frontend/templates/hyva/gallery-additions.phtml",
    "chars": 2248,
    "preview": "<script>\n    const yireoWebp2ReplaceImage = function (image) {\n        if (image.full && image.full_webp) {\n            "
  },
  {
    "path": "view/frontend/templates/test/image_with_custom_style.phtml",
    "chars": 612,
    "preview": "<?php declare(strict_types=1); /** @var $block \\Magento\\Framework\\View\\Element\\Template */ /** @var $imageProvider \\Yire"
  },
  {
    "path": "view/frontend/templates/test/multiple_existing_picturesets.phtml",
    "chars": 658,
    "preview": "<?php declare(strict_types=1); /** @var $block \\Magento\\Framework\\View\\Element\\Template */ /** @var $imageProvider \\Yire"
  },
  {
    "path": "view/frontend/templates/test/multiple_images.phtml",
    "chars": 648,
    "preview": "<?php declare(strict_types=1); /** @var $block \\Magento\\Framework\\View\\Element\\Template */ /** @var $imageProvider \\Yire"
  },
  {
    "path": "view/frontend/templates/test/multiple_images_same.phtml",
    "chars": 592,
    "preview": "<?php declare(strict_types=1); /** @var $block \\Magento\\Framework\\View\\Element\\Template */ /** @var $imageProvider \\Yire"
  },
  {
    "path": "view/frontend/templates/test/unknown_image.phtml",
    "chars": 292,
    "preview": "<?php declare(strict_types=1); /** @var $block \\Magento\\Framework\\View\\Element\\Template */ ?> <img src=\"https://example."
  },
  {
    "path": "view/frontend/web/js/add-webp-class-to-body.js",
    "chars": 185,
    "preview": "define([\n    'jquery',\n    './has-webp'\n], function($, hasWebP) {\n    if (hasWebP()) {\n        $('body').addClass('webp'"
  },
  {
    "path": "view/frontend/web/js/gallery-mixin.js",
    "chars": 899,
    "preview": "define([\n    'jquery',\n    './has-webp',\n    \"domReady!\"\n], function ($, hasWebP) {\n    'use strict';\n\n    var mixin = {"
  },
  {
    "path": "view/frontend/web/js/has-webp.js",
    "chars": 314,
    "preview": "define([], function () {\n    'use strict';\n\n    return function hasWebP() {\n        var elem = document.createElement('c"
  },
  {
    "path": "view/frontend/web/js/swatch-renderer-mixin.js",
    "chars": 1851,
    "preview": "define([\n    'jquery',\n    './has-webp',\n    \"domReady!\"\n], function ($, hasWebP) {\n    'use strict';\n\n    return functi"
  }
]

About this extraction

This page contains the full source code of the yireo/Yireo_Webp2 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 68 files (109.1 KB), approximately 30.4k tokens, and a symbol index with 67 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!