|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of the box project. |
|
7
|
|
|
* |
|
8
|
|
|
* (c) Kevin Herrera <[email protected]> |
|
9
|
|
|
* Théo Fidry <[email protected]> |
|
10
|
|
|
* |
|
11
|
|
|
* This source file is subject to the MIT license that is bundled |
|
12
|
|
|
* with this source code in the file LICENSE. |
|
13
|
|
|
*/ |
|
14
|
|
|
|
|
15
|
|
|
namespace KevinGH\Box\PhpScoper; |
|
16
|
|
|
|
|
17
|
|
|
use Closure; |
|
18
|
|
|
use function func_get_args; |
|
19
|
|
|
use Humbug\PhpScoper\Scoper as HumbugPhpScoperScoper; |
|
20
|
|
|
use Humbug\PhpScoper\Whitelist; |
|
21
|
|
|
use Opis\Closure\SerializableClosure; |
|
22
|
|
|
use Serializable; |
|
23
|
|
|
use function serialize; |
|
24
|
|
|
use function unserialize; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Humbug PHP-Scoper scoper which leverages closures to ensure the scoper is serializable. |
|
28
|
|
|
*/ |
|
29
|
|
|
final class SerializablePhpScoper implements HumbugPhpScoperScoper, Serializable |
|
30
|
|
|
{ |
|
31
|
|
|
private $createScoper; |
|
32
|
|
|
private $scoper; |
|
33
|
|
|
|
|
34
|
|
|
public function __construct(Closure $createScoper) |
|
35
|
|
|
{ |
|
36
|
|
|
$this->createScoper = new SerializableClosure($createScoper); |
|
37
|
|
|
|
|
38
|
|
|
// Checks that the closure used is serializable upfront instead of lazily: the overhead generated is negligible |
|
39
|
|
|
// hence worth the security this check provides |
|
40
|
|
|
unserialize(serialize($this->createScoper)); |
|
41
|
|
|
|
|
42
|
|
|
// Checks that the scoper is instantiable upfront instead of lazily: the overhead generated is negligible hence |
|
43
|
|
|
// worth the security this check provides |
|
44
|
|
|
$this->getScoper(); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* {@inheritdoc} |
|
49
|
|
|
*/ |
|
50
|
|
|
public function scope(string $filePath, string $contents): string |
|
51
|
|
|
{ |
|
52
|
|
|
return $this->getScoper()->scope(...func_get_args()); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* {@inheritdoc} |
|
57
|
|
|
*/ |
|
58
|
|
|
public function serialize(): string |
|
59
|
|
|
{ |
|
60
|
|
|
return serialize($this->createScoper); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* {@inheritdoc} |
|
65
|
|
|
*/ |
|
66
|
|
|
public function unserialize($serialized): void |
|
67
|
|
|
{ |
|
68
|
|
|
$this->createScoper = unserialize($serialized); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public function getScoper(): HumbugPhpScoperScoper |
|
72
|
|
|
{ |
|
73
|
|
|
if (null === $this->scoper) { |
|
74
|
|
|
$this->scoper = ($this->createScoper)(); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
return $this->scoper; |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|