<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

/**
 * This file loads all Shopware polyfills, by registering this path with the Enlight class
 * loader for the 'Shopware' namespace prefix. This achieves backwards compatibility of
 * classes, interfaces etc. that are required in newer Shopware versions (e.g. the CSRFWhitelistAware
 * interface), but not available in older versions. You should require this file in your
 * plugin Bootstrap's 'afterInit()' method:
 *
 * require_once __DIR__ . '/ViisonCommon/Polyfill/Loader.php';
 */
Shopware()->Container()->get('loader')->registerNamespace('Shopware', (__DIR__ . '/'));

// Set an error handler on E_USER_ERROR level to swallow any exceptions caused by missing subscriber
// callbacks in plugins. This is necessary because this file might be included before Shopware's
// own error handler is registered, but plugins using ViisonCommon might have removed their old loader
// subscribers, which causes errors on the E_USER_ERROR level.
if (!defined('VIISON_COMMON_ERROR_HANDLER_REGISTERED')) {
    // Remove the current error handler first, if available. We have to pass an empty function as the replacement
    // handler, because passing NULL is only allows in PHP >= 5.5 and triggers a warning on older PHP versions.
    $originalErrorHandler = set_error_handler(
        function () {
        },
        E_ALL
    );

    // Prepare and set the custom error handler
    $userErrorHandler = function ($errno, $errstr, $errfile, $errline, $errcontext = null) use ($originalErrorHandler) {
        if ($errno === E_USER_ERROR) {
            return true;
        } elseif ($originalErrorHandler) {
            return call_user_func($originalErrorHandler, $errno, $errstr, $errfile, $errline, $errcontext);
        }
    };
    set_error_handler($userErrorHandler, E_ALL);
    define('VIISON_COMMON_ERROR_HANDLER_REGISTERED', true);
}
