forked from php-pm/php-pm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.php
More file actions
108 lines (94 loc) · 2.95 KB
/
Utils.php
File metadata and controls
108 lines (94 loc) · 2.95 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace PHPPM;
/**
* Nitty gritty helper methods to hijack objects. Useful to reset properties that would otherwise run amok
* and result in memory leaks.
*/
class Utils
{
/**
* Executes a function in the context of an object. This basically bypasses the private/protected check of PHP.
*
* @param callable $fn
* @param object $newThis
* @param array $args
* @param string $bindClass
*/
public static function bindAndCall(callable $fn, $newThis, $args = [], $bindClass = null)
{
$func = \Closure::bind($fn, $newThis, $bindClass ?: \get_class($newThis));
if ($args) {
\call_user_func_array($func, $args);
} else {
$func(); //faster
}
}
/**
* Changes a property value of an object. (hijack because you can also change private/protected properties)
*
* @param object $object
* @param string $propertyName
* @param mixed $newValue
*/
public static function hijackProperty($object, $propertyName, $newValue)
{
Utils::bindAndCall(function () use ($object, $propertyName, $newValue) {
$object->$propertyName = $newValue;
}, $object);
}
/**
* Generates stronger session ids for session handling.
*
* @return string
*/
public static function generateSessionId()
{
return \bin2hex(\random_bytes(32));
}
/**
* @return int bytes
*/
public static function getMaxMemory()
{
$memoryLimit = \ini_get('memory_limit');
// if no limit
if (-1 == $memoryLimit) {
return 134217728; //128 * 1024 * 1024 default 128mb
}
// if set to exact byte
if (\is_numeric($memoryLimit)) {
return (int) $memoryLimit;
}
// if short hand version http://php.net/manual/en/faq.using.php#faq.using.shorthandbytes
return (int) \substr($memoryLimit, 0, -1) * [
'g' => 1073741824, // 1024 * 1024 * 1024
'm' => 1048576, // 1024 * 1024
'k' => 1024
][\strtolower(\substr($memoryLimit, -1))];
}
/**
* @param string $path
*
* @return string|boolean false when path resolution resolved to out of range
*/
public static function parseQueryPath($path)
{
$path = '/' . \ltrim($path, '/');
$path = \preg_replace('/[\x00-\x1F\x7F]/', '', $path);
//examples:
//1.> /images/../foo.png
//2.> /foo.png
//1.> /images/../../foo.png
//2.> /foo.png
//3.> false
while (false !== $pos = \strpos($path, '/../')) {
$leftSlashNext = \strrpos(\substr($path, 0, $pos), '/');
if (false === $leftSlashNext) {
// one /../ too much, without space to the left/up
return false;
}
$path = \substr($path, 0, $leftSlashNext + 1) . \substr($path, $pos + 4);
}
return $path;
}
}