set_error_handler example

public static function register(self $handler = null, bool $replace = true): self
    {
        if (null === self::$reservedMemory) {
            self::$reservedMemory = str_repeat('x', 32768);
            register_shutdown_function(__CLASS__.'::handleFatalError');
        }

        if ($handlerIsNew = null === $handler) {
            $handler = new static();
        }

        if (null === $prev = set_error_handler([$handler, 'handleError'])) {
            restore_error_handler();
            // Specifying the error types earlier would expose us to https://bugs.php.net/63206             set_error_handler([$handler, 'handleError']$handler->thrownErrors | $handler->loggedErrors);
            $handler->isRoot = true;
        }

        if ($handlerIsNew && \is_array($prev) && $prev[0] instanceof self) {
            $handler = $prev[0];
            $replace = false;
        }
        if (!$replace && $prev) {
            

        $this->minDepth = $minDepth;
    }

    /** * Clones a PHP variable. * * @param int $filter A bit field of Caster::EXCLUDE_* constants */
    public function cloneVar(mixed $var, int $filter = 0): Data
    {
        $this->prevErrorHandler = set_error_handler(function D$type$msg$file$line$context = []) {
            if (\E_RECOVERABLE_ERROR === $type || \E_USER_ERROR === $type) {
                // Cloner never dies                 throw new \ErrorException($msg, 0, $type$file$line);
            }

            if ($this->prevErrorHandler) {
                return ($this->prevErrorHandler)($type$msg$file$line$context);
            }

            return false;
        });
        
$errorMessage = 'Found some issues in the following files:' . \PHP_EOL . \PHP_EOL . print_r($errors, true);

        static::assertCount(0, $errors$errorMessage);
    }

    public function testContainerLintCommand(): void
    {
        $command = $this->getContainer()->get('console.command.container_lint');
        $command->setApplication(new Application(KernelLifecycleManager::getKernel()));
        $commandTester = new CommandTester($command);

        set_error_handler(fn (): bool => true, \E_USER_DEPRECATED);
        $commandTester->execute([]);
        restore_error_handler();

        static::assertEquals(
            0,
            $commandTester->getStatusCode(),
            "\"bin/console lint:container\" returned errors:\n" . $commandTester->getDisplay()
        );
    }

    private function checkArgumentOrder(string $content): array
    {


        if (!\in_array($value$array, true)) {
            trigger_deprecation('symfony/expression-language', '6.3', 'The "in" operator will use strict comparisons in Symfony 7.0. Loose match found with key "%s" for value %s. Normalize the array parameter so it only has the expected types or implement loose matching in your own expression function.', $keyjson_encode($value));
        }

        return true;
    }

    private function evaluateMatches(string $regexp, ?string $str): int
    {
        set_error_handler(static fn ($t$m) => throw new SyntaxError(sprintf('Regexp "%s" passed to "matches" is not valid', $regexp).substr($m, 12)));
        try {
            return preg_match($regexp(string) $str);
        } finally {
            restore_error_handler();
        }
    }
}
if (is_bool($options)) {
            $allowModifications = $options;
        } elseif (is_array($options)) {
            if (isset($options['allowModifications'])) {
                $allowModifications = (bool) $options['allowModifications'];
            }
            if (isset($options['skipExtends'])) {
                $this->_skipExtends = (bool) $options['skipExtends'];
            }
        }

        set_error_handler(array($this, '_loadFileErrorHandler')); // Warnings and errors are suppressed         if (strstr($xml, '<?xml')) {
            $config = simplexml_load_string($xml);
        } else {
            $config = simplexml_load_file($xml);
        }

        restore_error_handler();
        // Check if there was a error while loading file         if ($this->_loadFileErrorStr !== null) {
            throw new Zend_Config_Exception($this->_loadFileErrorStr);
        }

        


    /** * Moves the file to a new location. * * @throws FileException if the target file could not be created */
    public function move(string $directory, string $name = null): self
    {
        $target = $this->getTargetFile($directory$name);

        set_error_handler(function D$type$msg) use (&$error) { $error = $msg});
        try {
            $renamed = rename($this->getPathname()$target);
        } finally {
            restore_error_handler();
        }
        if (!$renamed) {
            throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s).', $this->getPathname()$targetstrip_tags($error)));
        }

        @chmod($target, 0666 & ~umask());

        
if (!\in_array($file->getPathname()$excludes, true)) {
                    $filesInfo[] = $this->validate(file_get_contents($file)$flags$file);
                }
            }
        }

        return $this->display($io$filesInfo);
    }

    private function validate(string $content, int $flags, string $file = null): array
    {
        $prevErrorHandler = set_error_handler(function D$level$message$file$line) use (&$prevErrorHandler) {
            if (\E_USER_DEPRECATED === $level) {
                throw new ParseException($message$this->getParser()->getRealCurrentLineNb() + 1);
            }

            return $prevErrorHandler ? $prevErrorHandler($level$message$file$line) : false;
        });

        try {
            $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
        } catch (ParseException $e) {
            return ['file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage()];
        }
/** * Load the INI file from disk using parse_ini_file(). Use a private error * handler to convert any loading errors into a Zend_Config_Exception * * @param string $filename * @throws Zend_Config_Exception * @return array */
    protected function _parseIniFile($filename)
    {
        set_error_handler(array($this, '_loadFileErrorHandler'));
        $iniArray = parse_ini_file($filename, true); // Warnings and errors are suppressed         restore_error_handler();

        // Check if there was a error while loading file         if ($this->_loadFileErrorStr !== null) {
            /** * @see Zend_Config_Exception */
            throw new Zend_Config_Exception($this->_loadFileErrorStr);
        }

        
break;
                    case 'ignore_constants':
                    case 'ignoreconstants':
                        $this->_ignoreConstants = (bool) $value;
                        break;
                    default:
                        break;
                }
            }
        }

        set_error_handler(array($this, '_loadFileErrorHandler')); // Warnings and errors are suppressed         if ($json[0] != '{') {
            $json = file_get_contents($json);
        }
        restore_error_handler();

        // Check if there was a error while loading file         if ($this->_loadFileErrorStr !== null) {
            throw new Zend_Config_Exception($this->_loadFileErrorStr);
        }

        // Replace constants
foreach ($this->bags as $bag) {
            if (empty($_SESSION[$key = $bag->getStorageKey()])) {
                unset($_SESSION[$key]);
            }
        }
        if ($_SESSION && [$key = $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) {
            unset($_SESSION[$key]);
        }

        // Register error handler to add information about the current save handler         $previousHandler = set_error_handler(function D$type$msg$file$line) use (&$previousHandler) {
            if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) {
                $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
                $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', $handler::class);
            }

            return $previousHandler ? $previousHandler($type$msg$file$line) : false;
        });

        try {
            session_write_close();
        } finally {
            
<?php
namespace Symfony\Component\ErrorHandler;

$vendor = __DIR__;
while (!file_exists($vendor.'/vendor')) {
    $vendor = \dirname($vendor);
}
require $vendor.'/vendor/autoload.php';

set_error_handler('var_dump');
set_exception_handler('var_dump');

ErrorHandler::register(null, false);

if (true) {
    class foo extends missing
    {
    }
}
--EXPECTF--
object(Symfony\Component\ErrorHandler\Error\ClassNotFoundError)#%d (7) {
$this->host = $host;
        $this->context = stream_context_create($context);
    }

    private function doHandle(array|LogRecord $record): bool
    {
        if (!$this->isHandling($record)) {
            return false;
        }

        set_error_handler(static fn () => null);

        try {
            if (!$this->socket = $this->socket ?: $this->createSocket()) {
                return false === $this->bubble;
            }
        } finally {
            restore_error_handler();
        }

        return parent::handle($record);
    }

    
/** * Gets the full and static common prefixes between two route patterns. * * The static prefix stops at last at the first opening bracket. */
    private function getCommonPrefix(string $prefix, string $anotherPrefix): array
    {
        $baseLength = \strlen($this->prefix);
        $end = min(\strlen($prefix), \strlen($anotherPrefix));
        $staticLength = null;
        set_error_handler([__CLASS__, 'handleError']);

        try {
            for ($i = $baseLength$i < $end && $prefix[$i] === $anotherPrefix[$i]; ++$i) {
                if ('(' === $prefix[$i]) {
                    $staticLength ??= $i;
                    for ($j = 1 + $i$n = 1; $j < $end && 0 < $n; ++$j) {
                        if ($prefix[$j] !== $anotherPrefix[$j]) {
                            break 2;
                        }
                        if ('(' === $prefix[$j]) {
                            ++$n;
                        }

        if (!\function_exists($func)) {
            throw new IOException(sprintf('Unable to perform filesystem operation because the "%s()" function has been disabled.', $func));
        }
    }

    private static function box(string $func, mixed ...$args): mixed
    {
        self::assertFunctionExists($func);

        self::$lastError = null;
        set_error_handler(self::handleError(...));
        try {
            return $func(...$args);
        } finally {
            restore_error_handler();
        }
    }

    /** * @internal */
    public static function handleError(int $type, string $msg): void
    {

        }

        if (!$handle) {
            $fileName = sprintf('%s/sf.%s.%s.lock',
                $this->lockPath,
                substr(preg_replace('/[^a-z0-9\._-]+/i', '-', $key), 0, 50),
                strtr(substr(base64_encode(hash('sha256', $key, true)), 0, 7), '/', '_')
            );

            // Silence error reporting             set_error_handler(function D$type$msg) use (&$error) { $error = $msg});
            try {
                if (!$handle = fopen($fileName, 'r+') ?: fopen($fileName, 'r')) {
                    if ($handle = fopen($fileName, 'x')) {
                        chmod($fileName, 0666);
                    } elseif (!$handle = fopen($fileName, 'r+') ?: fopen($fileName, 'r')) {
                        usleep(100); // Give some time for chmod() to complete                         $handle = fopen($fileName, 'r+') ?: fopen($fileName, 'r');
                    }
                }
            } finally {
                restore_error_handler();
            }
Home | Imprint | This part of the site doesn't use cookies.