forked from php-pm/php-pm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Utils.php
113 lines (98 loc) · 2.97 KB
/
Utils.php
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
109
110
111
112
113
<?php
namespace PHPPM;
/**
* Helper class to avoid creating closures in static context
* See https://bugs.php.net/bug.php?id=64761
*/
class ClosureHelper
{
/**
* Return a closure that assigns a property value
*/
public function getPropertyAccessor($propertyName, $newValue) {
return function () use ($propertyName, $newValue) {
$this->$propertyName = $newValue;
};
}
}
/**
* 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)
{
$closure = (new ClosureHelper())->getPropertyAccessor($propertyName, $newValue);
Utils::bindAndCall($closure, $object);
}
/**
* @return bool
*/
public static function isWindows()
{
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}
/**
* Generates stronger session ids for session handling.
*
* @return string
*/
public static function generateSessionId()
{
$entropy = '';
$entropy .= uniqid(mt_rand(), true);
$entropy .= microtime(true);
if (function_exists('openssl_random_pseudo_bytes')) {
$entropy .= openssl_random_pseudo_bytes(32, $strong);
}
if (function_exists('mcrypt_create_iv')) {
$entropy .= mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
}
$hash = hash('whirlpool', $entropy);
return $hash;
}
/**
* @return int bytes
*/
public static function getMaxMemory()
{
$memoryLimit = ini_get('memory_limit');
if (-1 === $memoryLimit) {
return 128 * 1024 * 1024; //default 128mb
}
$lastChar = strtolower(substr($memoryLimit, -1));
if ('g' === $lastChar) {
$memoryLimit = substr($memoryLimit, 0, -1) * 1024 * 1024 * 1024;
} else if ('m' === $lastChar) {
$memoryLimit = substr($memoryLimit, 0, -1) * 1024 * 1024;
} else if ('k' === $lastChar) {
$memoryLimit = substr($memoryLimit, 0, -1) * 1024;
}
return $memoryLimit;
}
}