-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathPhpUnserializer.php
More file actions
70 lines (60 loc) · 1.9 KB
/
Copy pathPhpUnserializer.php
File metadata and controls
70 lines (60 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
/*
* This file is part of php-cache organization.
*
* (c) 2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\Adapter\Common;
final class PhpUnserializer
{
public static function unserialize(string $payload, mixed &$value): bool
{
try {
return self::decodeWith(static fn (): mixed => @unserialize($payload), $value)
&& (false !== $value || 'b:0;' === $payload);
} catch (\Throwable) {
return false;
}
}
/**
* @param \Closure(): mixed $decoder
*/
public static function decodeWith(\Closure $decoder, mixed &$value): bool
{
$autoloadedClasses = [];
$trackAutoload = static function (string $class) use (&$autoloadedClasses) {
$autoloadedClasses[$class] = true;
};
spl_autoload_register($trackAutoload, true, true);
try {
try {
$value = $decoder();
} catch (\Throwable $exception) {
if ($exception instanceof \Error || self::isUnserializationFailure($exception)) {
return false;
}
throw $exception;
}
} finally {
spl_autoload_unregister($trackAutoload);
}
foreach (array_keys($autoloadedClasses) as $class) {
if (!class_exists($class, false)) {
return false;
}
}
return true;
}
private static function isUnserializationFailure(\Throwable $exception): bool
{
foreach ($exception->getTrace() as $frame) {
if (\in_array($frame['function'], ['unserialize', '__unserialize', '__wakeup'], true)) {
return true;
}
}
return false;
}
}