Debian Codegraph @

vendor/zordius/lightncandy/src/Exporter.php

raw
1 <?php
2 /*
3
4 MIT License
5 Copyright 2013-2021 Zordius Chen. All Rights Reserved.
6 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9
10 Origin: https://github.com/zordius/lightncandy
11 */
12
13 /**
14 * file to keep LightnCandy Exporter
15 *
16 * @package LightnCandy
17 * @author Zordius <[email protected]>
18 */
19
20 namespace LightnCandy;
21
22 /**
23 * LightnCandy major static class
24 */
25 class Exporter
26 {
27 /**
28 * Get PHP code string from a closure of function as string
29 *
30 * @param array<string,array|string|integer> $context current compile context
31 * @param object $closure Closure object
32 *
33 * @return string
34 *
35 * @expect 'function($a) {return;}' when input array('flags' => array('standalone' => 0)), function ($a) {return;}
36 * @expect 'function($a) {return;}' when input array('flags' => array('standalone' => 0)), function ($a) {return;}
37 */
38 protected static function closure($context, $closure)
39 {
40 if (is_string($closure) && preg_match('/(.+)::(.+)/', $closure, $matched)) {
41 $ref = new \ReflectionMethod($matched[1], $matched[2]);
42 } else {
43 $ref = new \ReflectionFunction($closure);
44 }
45 $meta = static::getMeta($ref);
46
47 return preg_replace('/^.*?function(\s+[^\s\\(]+?)?\s*\\((.+)\\}.*?\s*$/s', 'function($2}', static::replaceSafeString($context, $meta['code']));
48 }
49
50 /**
51 * Export required custom helper functions
52 *
53 * @param array<string,array|string|integer> $context current compile context
54 *
55 * @return string
56 */
57 public static function helpers($context)
58 {
59 $ret = '';
60 foreach ($context['helpers'] as $name => $func) {
61 if (!isset($context['usedCount']['helpers'][$name])) {
62 continue;
63 }
64 if ((is_object($func) && ($func instanceof \Closure)) || ($context['flags']['exhlp'] == 0)) {
65 $ret .= (" '$name' => " . static::closure($context, $func) . ",\n");
66 continue;
67 }
68 $ret .= " '$name' => '$func',\n";
69 }
70
71 return "array($ret)";
72 }
73
74 /**
75 * Replace SafeString class with alias class name
76 *
77 * @param array<string,array|string|integer> $context current compile context
78 * @param string $str the PHP code to be replaced
79 *
80 * @return string
81 */
82 protected static function replaceSafeString($context, $str)
83 {
84 return $context['flags']['standalone'] ? str_replace($context['safestring'], $context['safestringalias'], $str) : $str;
85 }
86
87 /**
88 * Get methods from ReflectionClass
89 *
90 * @param array<string,array|string|integer> $context current compile context
91 * @param \ReflectionClass $class instance of the ReflectionClass
92 *
93 * @return array
94 */
95 public static function getClassMethods($context, $class)
96 {
97 $methods = array();
98
99 foreach ($class->getMethods() as $method) {
100 $meta = static::getMeta($method);
101 $methods[$meta['name']] = static::scanDependency($context, preg_replace('/public static function (.+)\\(/', "function {$context['funcprefix']}\$1(", $meta['code']), $meta['code']);
102 }
103
104 return $methods;
105 }
106
107 /**
108 * Get statics code from ReflectionClass
109 *
110 * @param \ReflectionClass $class instance of the ReflectionClass
111 *
112 * @return string
113 */
114 public static function getClassStatics($class)
115 {
116 $ret = '';
117
118 foreach ($class->getStaticProperties() as $name => $value) {
119 $ret .= " public static \${$name} = " . var_export($value, true) . ";\n";
120 }
121
122 return $ret;
123 }
124
125
126
127
128
129 /**
130 * Get metadata from ReflectionObject
131 *
132 * @param object $refobj instance of the ReflectionObject
133 *
134 * @return array
135 */
136 public static function getMeta($refobj)
137 {
138 $fname = $refobj->getFileName();
139 $lines = file_get_contents($fname);
140 $file = new \SplFileObject($fname);
141
142 $start = $refobj->getStartLine() - 2;
143 $end = $refobj->getEndLine() - 1;
144
145 if (version_compare(\PHP_VERSION, '8.0.0') >= 0) {
146 $start++;
147 $end++;
148 }
149
150 $file->seek($start);
151 $spos = $file->ftell();
152 $file->seek($end);
153 $epos = $file->ftell();
154 unset($file);
155
156 return array(
157 'name' => $refobj->getName(),
158 'code' => substr($lines, $spos, $epos - $spos)
159 );
160 }
161
162 /**
163 * Export SafeString class as string
164 *
165 * @param array<string,array|string|integer> $context current compile context
166 *
167 * @return string
168 */
169 public static function safestring($context)
170 {
171 $class = new \ReflectionClass($context['safestring']);
172
173 return array_reduce(static::getClassMethods($context, $class), function ($in, $cur) {
174 return $in . $cur[2];
175 }, "if (!class_exists(\"" . addslashes($context['safestringalias']) . "\")) {\nclass {$context['safestringalias']} {\n" . static::getClassStatics($class)) . "}\n}\n";
176 }
177
178 /**
179 * Export StringObject class as string
180 *
181 * @param array<string,array|string|integer> $context current compile context
182 *
183 * @return string
184 */
185 public static function stringobject($context)
186 {
187 if ($context['flags']['standalone'] == 0) {
188 return 'use \\LightnCandy\\StringObject as StringObject;';
189 }
190 $class = new \ReflectionClass('\\LightnCandy\\StringObject');
191 $meta = static::getMeta($class);
192 return "if (!class_exists(\"StringObject\")) {\n{$meta['code']}}\n";
193 }
194
195 /**
196 * Export required standalone Runtime methods
197 *
198 * @param array<string,array|string|integer> $context current compile context
199 *
200 * @return string
201 */
202 public static function runtime($context)
203 {
204 $class = new \ReflectionClass($context['runtime']);
205 $ret = '';
206 $methods = static::getClassMethods($context, $class);
207
208 $exports = array_keys($context['usedCount']['runtime']);
209
210 while (true) {
211 if (array_sum(array_map(function ($name) use (&$exports, $methods) {
212 $n = 0;
213 foreach ($methods[$name][1] as $child => $count) {
214 if (!in_array($child, $exports)) {
215 $exports[] = $child;
216 $n++;
217 }
218 }
219 return $n;
220 }, $exports)) == 0) {
221 break;
222 }
223 }
224
225 foreach ($exports as $export) {
226 $ret .= ($methods[$export][0] . "\n");
227 }
228
229 return $ret;
230 }
231
232 /**
233 * Export Runtime constants
234 *
235 * @param array<string,array|string|integer> $context current compile context
236 *
237 * @return string
238 */
239 public static function constants($context)
240 {
241 if ($context['flags']['standalone'] == 0) {
242 return 'array()';
243 }
244
245 $class = new \ReflectionClass($context['runtime']);
246 $constants = $class->getConstants();
247 $ret = " array(\n";
248 foreach ($constants as $name => $value) {
249 $ret .= " '$name' => ". (is_string($value) ? "'$value'" : $value) . ",\n";
250 }
251 $ret .= " )";
252 return $ret;
253 }
254
255 /**
256 * Scan for required standalone functions
257 *
258 * @param array<string,array|string|integer> $context current compile context
259 * @param string $code patched PHP code string of the method
260 * @param string $ocode original PHP code string of the method
261 *
262 * @return array<string|array> list of converted code and children array
263 */
264 protected static function scanDependency($context, $code, $ocode)
265 {
266 $child = array();
267
268 $code = preg_replace_callback('/static::(\w+?)\s*\(/', function ($matches) use ($context, &$child) {
269 if (!isset($child[$matches[1]])) {
270 $child[$matches[1]] = 0;
271 }
272 $child[$matches[1]]++;
273
274 return "{$context['funcprefix']}{$matches[1]}(";
275 }, $code);
276
277 // replace the constants
278 $code = preg_replace('/static::([A-Z0-9_]+)/', "\$cx['constants']['$1']", $code);
279
280 // compress space
281 $code = preg_replace('/ /', ' ', $code);
282
283 return array(static::replaceSafeString($context, $code), $child, $ocode);
284 }
285 }