Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Use try/finally to restore error handlers #43778

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,11 @@ public function __construct($message, array $trace, $file)
}

set_error_handler(function () {});
$parsedMsg = unserialize($this->message);
restore_error_handler();
try {
$parsedMsg = unserialize($this->message);
} finally {
restore_error_handler();
}
if ($parsedMsg && isset($parsedMsg['deprecation'])) {
$this->message = $parsedMsg['deprecation'];
$this->originClass = $parsedMsg['class'];
Expand Down
7 changes: 5 additions & 2 deletions src/Symfony/Component/Cache/Traits/RedisTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,11 @@ public static function createConnection(string $dsn, array $options = [])
@$redis->{$connect}($host, $port, $params['timeout'], (string) $params['persistent_id'], $params['retry_interval'], $params['read_timeout'], ...\defined('Redis::SCAN_PREFIX') ? [['stream' => $params['ssl'] ?? null]] : []);

set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
$isConnected = $redis->isConnected();
restore_error_handler();
try {
$isConnected = $redis->isConnected();
} finally {
restore_error_handler();
}
if (!$isConnected) {
$error = preg_match('/^Redis::p?connect\(\): (.*)/', $error, $error) ? sprintf(' (%s)', $error[1]) : '';
throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$error.'.');
Expand Down
15 changes: 10 additions & 5 deletions src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,14 +254,19 @@ public function testSetDeprecated()
};

$prevErrorHandler = set_error_handler($deprecationHandler);
$node->finalize([]);
restore_error_handler();

try {
$node->finalize([]);
} finally {
restore_error_handler();
}
$this->assertFalse($deprecationTriggered, '->finalize() should not trigger if the deprecated node is not set');

$prevErrorHandler = set_error_handler($deprecationHandler);
$node->finalize(['foo' => []]);
restore_error_handler();
try {
$node->finalize(['foo' => []]);
} finally {
restore_error_handler();
}
$this->assertTrue($deprecationTriggered, '->finalize() should trigger if the deprecated node is set');
}

Expand Down
14 changes: 10 additions & 4 deletions src/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,19 @@ public function testSetDeprecated()
};

$prevErrorHandler = set_error_handler($deprecationHandler);
$node->finalize([]);
restore_error_handler();
try {
$node->finalize([]);
} finally {
restore_error_handler();
}
$this->assertSame(0, $deprecationTriggered, '->finalize() should not trigger if the deprecated node is not set');

$prevErrorHandler = set_error_handler($deprecationHandler);
$node->finalize(['foo' => '']);
restore_error_handler();
try {
$node->finalize(['foo' => '']);
} finally {
restore_error_handler();
}
$this->assertSame(1, $deprecationTriggered, '->finalize() should trigger if the deprecated node is set');
}

Expand Down
9 changes: 2 additions & 7 deletions src/Symfony/Component/Filesystem/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -737,15 +737,10 @@ private static function box(callable $func, ...$args)
self::$lastError = null;
set_error_handler(__CLASS__.'::handleError');
try {
$result = $func(...$args);
return $func(...$args);
} finally {
restore_error_handler();

return $result;
} catch (\Throwable $e) {
}
restore_error_handler();

throw $e;
}

/**
Expand Down
7 changes: 5 additions & 2 deletions src/Symfony/Component/Finder/SplFileInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,11 @@ public function getFilenameWithoutExtension(): string
public function getContents()
{
set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
$content = file_get_contents($this->getPathname());
restore_error_handler();
try {
$content = file_get_contents($this->getPathname());
} finally {
restore_error_handler();
}
if (false === $content) {
throw new \RuntimeException($error);
}
Expand Down
7 changes: 5 additions & 2 deletions src/Symfony/Component/HttpFoundation/File/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,11 @@ public function move(string $directory, string $name = null)
$target = $this->getTargetFile($directory, $name);

set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
$renamed = rename($this->getPathname(), $target);
restore_error_handler();
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(), $target, strip_tags($error)));
}
Expand Down
7 changes: 5 additions & 2 deletions src/Symfony/Component/HttpFoundation/File/UploadedFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,11 @@ public function move(string $directory, string $name = null)
$target = $this->getTargetFile($directory, $name);

set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
$moved = move_uploaded_file($this->getPathname(), $target);
restore_error_handler();
try {
$moved = move_uploaded_file($this->getPathname(), $target);
} finally {
restore_error_handler();
}
if (!$moved) {
throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s).', $this->getPathname(), $target, strip_tags($error)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ public function testConfigure()
try {
$listener->configure();
} catch (\Exception $exception) {
} finally {
restore_exception_handler();
restore_error_handler();
}
restore_exception_handler();
restore_error_handler();

if (null !== $exception) {
throw $exception;
Expand Down Expand Up @@ -116,9 +117,10 @@ public function testConsoleEvent()
try {
$dispatcher->dispatch($event, ConsoleEvents::COMMAND);
} catch (\Exception $exception) {
} finally {
restore_exception_handler();
restore_error_handler();
}
restore_exception_handler();
restore_error_handler();

if (null !== $exception) {
throw $exception;
Expand Down
17 changes: 10 additions & 7 deletions src/Symfony/Component/Lock/Store/FlockStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,18 @@ private function lock(Key $key, bool $read, bool $blocking)

// Silence error reporting
set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
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');
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();
}
restore_error_handler();
}

if (!$handle) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -537,11 +537,13 @@ public function testDeprecationMessages(\Closure $configureOptions, array $optio
});
$e = error_reporting(0);

$configureOptions($this->resolver);
$this->resolver->resolve($options);

error_reporting($e);
restore_error_handler();
try {
$configureOptions($this->resolver);
$this->resolver->resolve($options);
} finally {
error_reporting($e);
restore_error_handler();
}

$lastError = error_get_last();
unset($lastError['file'], $lastError['line']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,40 +151,43 @@ private function getCommonPrefix(string $prefix, string $anotherPrefix): array
$staticLength = null;
set_error_handler([__CLASS__, 'handleError']);

for ($i = $baseLength; $i < $end && $prefix[$i] === $anotherPrefix[$i]; ++$i) {
if ('(' === $prefix[$i]) {
$staticLength = $staticLength ?? $i;
for ($j = 1 + $i, $n = 1; $j < $end && 0 < $n; ++$j) {
if ($prefix[$j] !== $anotherPrefix[$j]) {
break 2;
try {
for ($i = $baseLength; $i < $end && $prefix[$i] === $anotherPrefix[$i]; ++$i) {
if ('(' === $prefix[$i]) {
$staticLength = $staticLength ?? $i;
for ($j = 1 + $i, $n = 1; $j < $end && 0 < $n; ++$j) {
if ($prefix[$j] !== $anotherPrefix[$j]) {
break 2;
}
if ('(' === $prefix[$j]) {
++$n;
} elseif (')' === $prefix[$j]) {
--$n;
} elseif ('\\' === $prefix[$j] && (++$j === $end || $prefix[$j] !== $anotherPrefix[$j])) {
--$j;
break;
}
}
if ('(' === $prefix[$j]) {
++$n;
} elseif (')' === $prefix[$j]) {
--$n;
} elseif ('\\' === $prefix[$j] && (++$j === $end || $prefix[$j] !== $anotherPrefix[$j])) {
--$j;
if (0 < $n) {
break;
}
}
if (0 < $n) {
break;
}
if (('?' === ($prefix[$j] ?? '') || '?' === ($anotherPrefix[$j] ?? '')) && ($prefix[$j] ?? '') !== ($anotherPrefix[$j] ?? '')) {
break;
}
$subPattern = substr($prefix, $i, $j - $i);
if ($prefix !== $anotherPrefix && !preg_match('/^\(\[[^\]]++\]\+\+\)$/', $subPattern) && !preg_match('{(?<!'.$subPattern.')}', '')) {
// sub-patterns of variable length are not considered as common prefixes because their greediness would break in-order matching
if (('?' === ($prefix[$j] ?? '') || '?' === ($anotherPrefix[$j] ?? '')) && ($prefix[$j] ?? '') !== ($anotherPrefix[$j] ?? '')) {
break;
}
$subPattern = substr($prefix, $i, $j - $i);
if ($prefix !== $anotherPrefix && !preg_match('/^\(\[[^\]]++\]\+\+\)$/', $subPattern) && !preg_match('{(?<!'.$subPattern.')}', '')) {
// sub-patterns of variable length are not considered as common prefixes because their greediness would break in-order matching
break;
}
$i = $j - 1;
} elseif ('\\' === $prefix[$i] && (++$i === $end || $prefix[$i] !== $anotherPrefix[$i])) {
--$i;
break;
}
$i = $j - 1;
} elseif ('\\' === $prefix[$i] && (++$i === $end || $prefix[$i] !== $anotherPrefix[$i])) {
--$i;
break;
}
} finally {
restore_error_handler();
}
restore_error_handler();
if ($i < $end && 0b10 === (\ord($prefix[$i]) >> 6) && preg_match('//u', $prefix.' '.$anotherPrefix)) {
do {
// Prevent cutting in the middle of an UTF-8 characters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,29 +298,28 @@ protected function refreshUser(TokenInterface $token): ?TokenInterface

private function safelyUnserialize(string $serializedToken)
{
$e = $token = null;
$token = null;
$prevUnserializeHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
$prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$prevErrorHandler) {
if (__FILE__ === $file) {
throw new \ErrorException($msg, 0x37313bc, $type, $file, $line);
throw new \ErrorException($msg, 0x37313BC, $type, $file, $line);
}

return $prevErrorHandler ? $prevErrorHandler($type, $msg, $file, $line, $context) : false;
});

try {
$token = unserialize($serializedToken);
} catch (\Throwable $e) {
}
restore_error_handler();
ini_set('unserialize_callback_func', $prevUnserializeHandler);
if ($e) {
if (!$e instanceof \ErrorException || 0x37313bc !== $e->getCode()) {
} catch (\ErrorException $e) {
if (0x37313BC !== $e->getCode()) {
throw $e;
}
if ($this->logger) {
$this->logger->warning('Failed to unserialize the security token from the session.', ['key' => $this->sessionKey, 'received' => $serializedToken, 'exception' => $e]);
}
} finally {
restore_error_handler();
ini_set('unserialize_callback_func', $prevUnserializeHandler);
}

return $token;
Expand Down Expand Up @@ -388,7 +387,7 @@ private static function hasUserChanged($originalUser, TokenInterface $refreshedT
*/
public static function handleUnserializeCallback(string $class)
{
throw new \ErrorException('Class not found: '.$class, 0x37313bc);
throw new \ErrorException('Class not found: '.$class, 0x37313BC);
}

/**
Expand Down