forked from thecodingmachine/safe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileCreator.php
More file actions
227 lines (195 loc) · 6.88 KB
/
FileCreator.php
File metadata and controls
227 lines (195 loc) · 6.88 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
<?php
declare(strict_types=1);
namespace Safe\Generator;
use Safe\XmlDocParser\ErrorType;
use Safe\XmlDocParser\Scanner;
use Safe\XmlDocParser\Method;
use function array_merge;
use function file_exists;
class FileCreator
{
/**
* This function generate an improved php lib function in a php file
*
* @param Method[] $functions
*/
public function generatePhpFile(
// These aren't actually sensitive, they just fill the
// stack traces with tons of useless information.
#[\SensitiveParameter] array $functions,
string $path
): void {
$path = rtrim($path, '/').'/';
$phpFunctionsByModule = [];
foreach ($functions as $function) {
$writePhpFunction = new WritePhpFunction($function);
$phpFunctionsByModule[$function->getModuleName()][] = $writePhpFunction->getPhpFunctionalFunction();
}
foreach ($phpFunctionsByModule as $module => $phpFunctions) {
$lcModule = \lcfirst($module);
if (!is_dir($path)) {
\mkdir($path);
}
$stream = \fopen($path.$lcModule.'.php', 'w');
if ($stream === false) {
throw new \RuntimeException('Unable to write to '.$path);
}
// Write file header
\fwrite($stream, "<?php\n
namespace Safe;
use Safe\\Exceptions\\".self::toExceptionName($module). ';');
// Write safe wrappers for non-safe functions
foreach ($phpFunctions as $phpFunction) {
\fwrite($stream, "\n".$phpFunction);
}
\fclose($stream);
}
}
/**
* @param string[] $versions
*/
public function generateVersionSplitters(string $module, string $path, array $versions, bool $return = false): void
{
$lcModule = \lcfirst($module);
$availableVersions = \array_filter(
$versions,
static function (string $version) use ($path, $lcModule): bool {
return \file_exists("$path/$version/$lcModule.php");
}
);
if ($availableVersions === []) {
throw new \RuntimeException('No versions found for '.$module);
}
$stream = \fopen($path.$lcModule.'.php', 'w');
if ($stream === false) {
throw new \RuntimeException('Unable to write to '.$path);
}
// Pick up the latest compatible version
\rsort($availableVersions);
$versionsArrayContent = \implode(
', ',
\array_map(
function (string $version): string {
return '\'' . $version . '\'';
},
$availableVersions
)
);
$return = $return ? "return " : "";
\fwrite(
$stream,
"<?php\n\n" .
'\call_user_func(' . "\n" .
' function() {' . "\n" .
' foreach ([' . $versionsArrayContent . '] as $phpVersion) {' . "\n" .
' if (\version_compare(PHP_VERSION, $phpVersion) >= 0) {' . "\n" .
' ' . $return . 'require_once __DIR__ . \'/\' . $phpVersion . \'/' . $lcModule . '.php;\'' . "\n" .
' break;' . "\n" .
' }' . "\n" .
' }' . "\n" .
' }' . "\n" .
');' . "\n"
);
\fclose($stream);
}
/**
* @param Method[] $functions
* @return string[]
*/
private function getFunctionsNameList(array $functions): array
{
$functions = array_filter(
$functions,
fn($function) => $function->getErrorType() !== ErrorType::UNKNOWN
);
$functionNames = array_map(function (Method $function) {
return $function->getFunctionName();
}, $functions);
$functionNames = array_merge($functionNames, Scanner::getSpecialCases());
$functionNames = array_diff($functionNames, Scanner::getHiddenFunctions());
natcasesort($functionNames);
return $functionNames;
}
/**
* This function generate a PHP file containing the list of functions we can handle.
*
* @param Method[] $functions
*/
public function generateFunctionsList(array $functions, string $path): void
{
$functionNames = $this->getFunctionsNameList($functions);
$stream = fopen($path, 'w');
if ($stream === false) {
throw new \RuntimeException('Unable to write to '.$path);
}
fwrite($stream, "<?php\n
return [\n");
foreach ($functionNames as $functionName) {
fwrite($stream, ' '.\var_export($functionName, true).",\n");
}
fwrite($stream, "];\n");
fclose($stream);
}
/**
* Generates a configuration file for replacing all functions when using rector/rector.
*
* @param Method[] $functions
*/
public function generateRectorFile(array $functions, string $path): void
{
$functionNames = $this->getFunctionsNameList($functions);
$stream = fopen($path, 'w');
if ($stream === false) {
throw new \RuntimeException('Unable to write to '.$path);
}
$header = <<<'TXT'
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\Renaming\Rector\FuncCall\RenameFunctionRector;
// This file configures rector/rector to replace all PHP functions with their equivalent "safe" functions.
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->ruleWithConfiguration(
RenameFunctionRector::class,
[
TXT;
fwrite($stream, $header);
foreach ($functionNames as $functionName) {
fwrite($stream, " '$functionName' => 'Safe\\$functionName',\n");
}
fwrite($stream, " ]\n );\n};\n");
fclose($stream);
}
public function createExceptionFile(string $moduleName): void
{
$exceptionName = self::toExceptionName($moduleName);
if (!file_exists(FileCreator::getSafeRootDir() . '/lib/Exceptions/'.$exceptionName.'.php')) {
\file_put_contents(
FileCreator::getSafeRootDir() . '/generated/Exceptions/'.$exceptionName.'.php',
<<<EOF
<?php
namespace Safe\Exceptions;
class {$exceptionName} extends \ErrorException implements SafeExceptionInterface
{
public static function createFromPhpError(): self
{
\$error = error_get_last();
return new self(\$error['message'] ?? 'An error occurred', 0, \$error['type'] ?? 1);
}
}
EOF
);
}
}
public static function getSafeRootDir(): string
{
return __DIR__ . '/../../..';
}
/**
* Generates the name of the exception class
*/
public static function toExceptionName(string $moduleName): string
{
return str_replace('-', '', \ucfirst($moduleName)).'Exception';
}
}