Boot.hx 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package php;
  23. import haxe.PosInfos;
  24. import haxe.extern.EitherType;
  25. using php.Global;
  26. /**
  27. Various Haxe->PHP compatibility utilities.
  28. You should not use this class directly.
  29. **/
  30. @:keep
  31. @:dox(hide)
  32. class Boot {
  33. /** List of Haxe classes registered by their PHP class names */
  34. @:protected static var aliases = new NativeAssocArray<String>();
  35. /** Cache of HxClass instances */
  36. @:protected static var classes = new NativeAssocArray<HxClass>();
  37. /** List of getters (for Reflect) */
  38. @:protected static var getters = new NativeAssocArray<NativeAssocArray<Bool>>();
  39. /** List of setters (for Reflect) */
  40. @:protected static var setters = new NativeAssocArray<NativeAssocArray<Bool>>();
  41. /** Metadata storage */
  42. @:protected static var meta = new NativeAssocArray<{}>();
  43. /** Cache for closures created of static methods */
  44. @:protected static var staticClosures = new NativeAssocArray<NativeAssocArray<HxClosure>>();
  45. /**
  46. Initialization stuff.
  47. This method is called once before invoking any Haxe-generated user code.
  48. **/
  49. static function __init__() {
  50. Global.mb_internal_encoding('UTF-8');
  51. if (!Global.defined('HAXE_CUSTOM_ERROR_HANDLER') || !Const.HAXE_CUSTOM_ERROR_HANDLER) {
  52. var previousLevel = Global.error_reporting(Const.E_ALL);
  53. var previousHandler = Global.set_error_handler(function(errno:Int, errstr:String, errfile:String, errline:Int) {
  54. if (Global.error_reporting() & errno == 0) {
  55. return false;
  56. }
  57. /*
  58. * Division by zero should not throw
  59. * @see https://github.com/HaxeFoundation/haxe/issues/7034#issuecomment-394264544
  60. */
  61. if (errno == Const.E_WARNING && errstr == 'Division by zero') {
  62. return true;
  63. }
  64. throw new ErrorException(errstr, 0, errno, errfile, errline);
  65. });
  66. // Already had user-defined handler. Return it.
  67. if (previousHandler != null) {
  68. Global.error_reporting(previousLevel);
  69. Global.set_error_handler(previousHandler);
  70. }
  71. }
  72. }
  73. /**
  74. Returns root namespace based on a value of `-D php-prefix=value` compiler flag.
  75. Returns empty string if no `-D php-prefix=value` provided.
  76. **/
  77. public static function getPrefix():String {
  78. return Syntax.code('self::PHP_PREFIX');
  79. }
  80. /**
  81. Register list of getters to be able to call getters using reflection
  82. **/
  83. public static function registerGetters(phpClassName:String, list:NativeAssocArray<Bool>):Void {
  84. getters[phpClassName] = list;
  85. }
  86. /**
  87. Register list of setters to be able to call getters using reflection
  88. **/
  89. public static function registerSetters(phpClassName:String, list:NativeAssocArray<Bool>):Void {
  90. setters[phpClassName] = list;
  91. }
  92. /**
  93. Check if specified property has getter
  94. **/
  95. public static function hasGetter(phpClassName:String, property:String):Bool {
  96. ensureLoaded(phpClassName);
  97. var has = false;
  98. var phpClassName:haxe.extern.EitherType<Bool, String> = phpClassName;
  99. do {
  100. has = Global.isset(getters[phpClassName][property]);
  101. phpClassName = Global.get_parent_class(phpClassName);
  102. } while (!has && phpClassName != false && Global.class_exists(phpClassName));
  103. return has;
  104. }
  105. /**
  106. Check if specified property has setter
  107. **/
  108. public static function hasSetter(phpClassName:String, property:String):Bool {
  109. ensureLoaded(phpClassName);
  110. var has = false;
  111. var phpClassName:haxe.extern.EitherType<Bool, String> = phpClassName;
  112. do {
  113. has = Global.isset(setters[phpClassName][property]);
  114. phpClassName = Global.get_parent_class(phpClassName);
  115. } while (!has && phpClassName != false && Global.class_exists(phpClassName));
  116. return has;
  117. }
  118. /**
  119. Save metadata for specified class
  120. **/
  121. public static function registerMeta(phpClassName:String, data:Dynamic):Void {
  122. meta[phpClassName] = data;
  123. }
  124. /**
  125. Retrieve metadata for specified class
  126. **/
  127. public static function getMeta(phpClassName:String):Null<Dynamic> {
  128. ensureLoaded(phpClassName);
  129. return Global.isset(meta[phpClassName]) ? meta[phpClassName] : null;
  130. }
  131. /**
  132. Associate PHP class name with Haxe class name
  133. **/
  134. public static function registerClass(phpClassName:String, haxeClassName:String):Void {
  135. aliases[phpClassName] = haxeClassName;
  136. }
  137. /**
  138. Returns a list of currently loaded haxe-generated classes.
  139. **/
  140. public static function getRegisteredClasses():Array<Class<Dynamic>> {
  141. var result = [];
  142. Syntax.foreach(aliases, function(phpName, haxeName) {
  143. result.push(cast getClass(phpName));
  144. });
  145. return result;
  146. }
  147. /**
  148. Returns a list of phpName=>haxeName for currently loaded haxe-generated classes.
  149. **/
  150. public static function getRegisteredAliases():NativeAssocArray<String> {
  151. return aliases;
  152. }
  153. /**
  154. Get Class<T> instance for PHP fully qualified class name (E.g. '\some\pack\MyClass')
  155. It's always the same instance for the same `phpClassName`
  156. **/
  157. public static function getClass(phpClassName:String):HxClass {
  158. if (phpClassName.charAt(0) == '\\') {
  159. phpClassName = phpClassName.substr(1);
  160. }
  161. if (!Global.isset(classes[phpClassName])) {
  162. classes[phpClassName] = new HxClass(phpClassName);
  163. }
  164. return classes[phpClassName];
  165. }
  166. /**
  167. Returns Class<HxAnon>
  168. **/
  169. public static inline function getHxAnon():HxClass {
  170. return cast HxAnon;
  171. }
  172. /**
  173. Check if provided value is an anonymous object
  174. **/
  175. public static inline function isAnon(v:Any):Bool {
  176. return Std.is(v, HxAnon);
  177. }
  178. /**
  179. Returns Class<HxClass>
  180. **/
  181. public static inline function getHxClass():HxClass {
  182. return cast HxClass;
  183. }
  184. /**
  185. Returns either Haxe class name for specified `phpClassName` or (if no such Haxe class registered) `phpClassName`.
  186. **/
  187. public static function getClassName(phpClassName:String):String {
  188. var hxClass = getClass(phpClassName);
  189. var name = getHaxeName(hxClass);
  190. return (name == null ? hxClass.phpClassName : name);
  191. }
  192. /**
  193. Returns original Haxe fully qualified class name for this type (if exists)
  194. **/
  195. public static function getHaxeName(hxClass:HxClass):Null<String> {
  196. switch (hxClass.phpClassName) {
  197. case 'Int':
  198. return 'Int';
  199. case 'String':
  200. return 'String';
  201. case 'Bool':
  202. return 'Bool';
  203. case 'Float':
  204. return 'Float';
  205. case 'Class':
  206. return 'Class';
  207. case 'Enum':
  208. return 'Enum';
  209. case 'Dynamic':
  210. return 'Dynamic';
  211. case _:
  212. }
  213. inline function exists()
  214. return Global.isset(aliases[hxClass.phpClassName]);
  215. if (exists()) {
  216. return aliases[hxClass.phpClassName];
  217. } else if (Global.class_exists(hxClass.phpClassName) && exists()) {
  218. return aliases[hxClass.phpClassName];
  219. } else if (Global.interface_exists(hxClass.phpClassName) && exists()) {
  220. return aliases[hxClass.phpClassName];
  221. }
  222. return null;
  223. }
  224. /**
  225. Find corresponding PHP class name.
  226. Returns `null` if specified class does not exist.
  227. **/
  228. public static function getPhpName(haxeName:String):Null<String> {
  229. var prefix = getPrefix();
  230. var phpParts = (Global.strlen(prefix) == 0 ? [] : [prefix]);
  231. var haxeParts = haxeName.split('.');
  232. for (part in haxeParts) {
  233. if (isPhpKeyword(part)) {
  234. part += '_hx';
  235. }
  236. phpParts.push(part);
  237. }
  238. return phpParts.join('\\');
  239. }
  240. /**
  241. Check if the value of `str` is a reserved keyword in PHP
  242. @see https://www.php.net/manual/en/reserved.keywords.php
  243. **/
  244. @:pure(false)
  245. static public function isPhpKeyword(str:String):Bool {
  246. //The body of this method is generated by the compiler
  247. return false;
  248. }
  249. /**
  250. Unsafe cast to HxClosure
  251. **/
  252. public static inline function castClosure(value:Dynamic):HxClosure {
  253. return value;
  254. }
  255. /**
  256. Unsafe cast to HxClass
  257. **/
  258. public static inline function castClass(cls:Class<Dynamic>):HxClass {
  259. return cast cls;
  260. }
  261. /**
  262. Returns `Class<T>` for `HxClosure`
  263. **/
  264. public static inline function closureHxClass():HxClass {
  265. return cast HxClosure;
  266. }
  267. /**
  268. Implementation for `cast(value, Class<Dynamic>)`
  269. @throws HxException if `value` cannot be casted to this type
  270. **/
  271. public static function typedCast(hxClass:HxClass, value:Dynamic):Dynamic {
  272. if (value == null)
  273. return null;
  274. switch (hxClass.phpClassName) {
  275. case 'Int':
  276. if (Boot.isNumber(value)) {
  277. return Global.intval(value);
  278. }
  279. case 'Float':
  280. if (Boot.isNumber(value)) {
  281. return value.floatval();
  282. }
  283. case 'Bool':
  284. if (value.is_bool()) {
  285. return value;
  286. }
  287. case 'String':
  288. if (value.is_string()) {
  289. return value;
  290. }
  291. case 'php\\NativeArray':
  292. if (value.is_array()) {
  293. return value;
  294. }
  295. case _:
  296. if (value.is_object() && Std.is(value, cast hxClass)) {
  297. return value;
  298. }
  299. }
  300. throw 'Cannot cast ' + Std.string(value) + ' to ' + getClassName(hxClass.phpClassName);
  301. }
  302. /**
  303. Returns string representation of `value`
  304. **/
  305. public static function stringify(value:Dynamic, maxRecursion:Int = 10):String {
  306. if (maxRecursion <= 0) {
  307. return '<...>';
  308. }
  309. if (value == null) {
  310. return 'null';
  311. }
  312. if (value.is_string()) {
  313. return value;
  314. }
  315. if (value.is_int() || value.is_float()) {
  316. return Syntax.string(value);
  317. }
  318. if (value.is_bool()) {
  319. return value ? 'true' : 'false';
  320. }
  321. if (value.is_array()) {
  322. var strings = Syntax.arrayDecl();
  323. Syntax.foreach(value, function(key:Dynamic, item:Dynamic) {
  324. strings.push(Syntax.string(key) + ' => ' + stringify(item, maxRecursion - 1));
  325. });
  326. return '[' + Global.implode(', ', strings) + ']';
  327. }
  328. if (value.is_object()) {
  329. if (Std.is(value, Array)) {
  330. return inline stringifyNativeIndexedArray(value.arr, maxRecursion - 1);
  331. }
  332. if (Std.is(value, HxEnum)) {
  333. var e:HxEnum = value;
  334. var result = e.tag;
  335. if (Global.count(e.params) > 0) {
  336. var strings = Global.array_map(function(item) return Boot.stringify(item, maxRecursion - 1), e.params);
  337. result += '(' + Global.implode(',', strings) + ')';
  338. }
  339. return result;
  340. }
  341. if (value.method_exists('toString')) {
  342. return value.toString();
  343. }
  344. if (value.method_exists('__toString')) {
  345. return value.__toString();
  346. }
  347. if (Std.is(value, StdClass)) {
  348. if (Global.isset(Syntax.field(value, 'toString')) && value.toString.is_callable()) {
  349. return value.toString();
  350. }
  351. var result = new NativeIndexedArray<String>();
  352. var data = Global.get_object_vars(value);
  353. for (key in data.array_keys()) {
  354. result.array_push('$key : ' + stringify(data[key], maxRecursion - 1));
  355. }
  356. return '{ ' + Global.implode(', ', result) + ' }';
  357. }
  358. if (isFunction(value)) {
  359. return '<function>';
  360. }
  361. if (Std.is(value, HxClass)) {
  362. return '[class ' + getClassName((value : HxClass).phpClassName) + ']';
  363. } else {
  364. return '[object ' + getClassName(Global.get_class(value)) + ']';
  365. }
  366. }
  367. throw "Unable to stringify value";
  368. }
  369. static public function stringifyNativeIndexedArray<T>(arr:NativeIndexedArray<T>, maxRecursion:Int = 10):String {
  370. var strings = Syntax.arrayDecl();
  371. Syntax.foreach(arr, function(index:Int, value:T) {
  372. strings[index] = Boot.stringify(value, maxRecursion - 1);
  373. });
  374. return '[' + Global.implode(',', strings) + ']';
  375. }
  376. static public inline function isNumber(value:Dynamic) {
  377. return value.is_int() || value.is_float();
  378. }
  379. /**
  380. Check if specified values are equal
  381. **/
  382. public static function equal(left:Dynamic, right:Dynamic):Bool {
  383. if (isNumber(left) && isNumber(right)) {
  384. return Syntax.equal(left, right);
  385. }
  386. if (Std.is(left, HxClosure) && Std.is(right, HxClosure)) {
  387. return (left : HxClosure).equals(right);
  388. }
  389. return Syntax.strictEqual(left, right);
  390. }
  391. /**
  392. Concat `left` and `right` if both are strings or string and null.
  393. Otherwise return sum of `left` and `right`.
  394. **/
  395. public static function addOrConcat(left:Dynamic, right:Dynamic):Dynamic {
  396. if (left.is_string() || right.is_string()) {
  397. return (left : String) + (right : String);
  398. }
  399. return Syntax.add(left, right);
  400. }
  401. /**
  402. `Std.is()` implementation
  403. **/
  404. public static function is(value:Dynamic, type:HxClass):Bool {
  405. if (type == null)
  406. return false;
  407. var phpType = type.phpClassName;
  408. #if php_prefix
  409. var prefix = getPrefix();
  410. if (Global.substr(phpType, 0, Global.strlen(prefix) + 1) == '$prefix\\') {
  411. phpType = Global.substr(phpType, Global.strlen(prefix) + 1);
  412. }
  413. #end
  414. switch (phpType) {
  415. case 'Dynamic':
  416. return value != null;
  417. case 'Int':
  418. return (value.is_int() || (value.is_float() && Syntax.equal(Syntax.int(value), value) && !Global.is_nan(value)))
  419. && Global.abs(value) <= 2147483648;
  420. case 'Float':
  421. return value.is_float() || value.is_int();
  422. case 'Bool':
  423. return value.is_bool();
  424. case 'String':
  425. return value.is_string();
  426. case 'php\\NativeArray', 'php\\_NativeArray\\NativeArray_Impl_':
  427. return value.is_array();
  428. case 'Enum' | 'Class':
  429. if (Std.is(value, HxClass)) {
  430. var valuePhpClass = (cast value : HxClass).phpClassName;
  431. var enumPhpClass = (cast HxEnum : HxClass).phpClassName;
  432. var isEnumType = Global.is_subclass_of(valuePhpClass, enumPhpClass);
  433. return (phpType == 'Enum' ? isEnumType : !isEnumType);
  434. }
  435. case _:
  436. if (value.is_object()) {
  437. var type:Class<Dynamic> = cast type;
  438. return Syntax.instanceof(value, type);
  439. }
  440. }
  441. return false;
  442. }
  443. /**
  444. Check if `value` is a `Class<T>`
  445. **/
  446. public static inline function isClass(value:Dynamic):Bool {
  447. return Std.is(value, HxClass);
  448. }
  449. /**
  450. Check if `value` is an enum constructor instance
  451. **/
  452. public static inline function isEnumValue(value:Dynamic):Bool {
  453. return Std.is(value, HxEnum);
  454. }
  455. /**
  456. Check if `value` is a function
  457. **/
  458. public static inline function isFunction(value:Dynamic):Bool {
  459. return Std.is(value, Closure) || Std.is(value, HxClosure);
  460. }
  461. /**
  462. Check if `value` is an instance of `HxClosure`
  463. **/
  464. public static inline function isHxClosure(value:Dynamic):Bool {
  465. return Std.is(value, HxClosure);
  466. }
  467. /**
  468. Performs `left >>> right` operation
  469. **/
  470. public static function shiftRightUnsigned(left:Int, right:Int):Int {
  471. if (right == 0) {
  472. return left;
  473. } else if (left >= 0) {
  474. return (left >> right) & ~((1 << (8 * Const.PHP_INT_SIZE - 1)) >> (right - 1));
  475. } else {
  476. return (left >> right) & (0x7fffffff >> (right - 1));
  477. }
  478. }
  479. /**
  480. Helper method to avoid "Cannot use temporary expression in write context" error for expressions like this:
  481. ```haxe
  482. (new MyClass()).fieldName = 'value';
  483. ```
  484. **/
  485. static public function deref(value:Dynamic):Dynamic {
  486. return value;
  487. }
  488. /**
  489. Create Haxe-compatible anonymous structure of `data` associative array
  490. **/
  491. static public inline function createAnon(data:NativeArray):Dynamic {
  492. return new HxAnon(data);
  493. }
  494. /**
  495. Make sure specified class is loaded
  496. **/
  497. static public inline function ensureLoaded(phpClassName:String):Bool {
  498. return Global.class_exists(phpClassName) || Global.interface_exists(phpClassName);
  499. }
  500. /**
  501. Get `field` of a dynamic `value` in a safe manner (avoid exceptions on trying to get a method)
  502. **/
  503. static public function dynamicField(value:Dynamic, field:String):Dynamic {
  504. if (Global.method_exists(value, field)) {
  505. return closure(value, field);
  506. }
  507. if (Global.is_string(value)) {
  508. value = @:privateAccess new HxDynamicStr(value);
  509. }
  510. return Syntax.field(value, field);
  511. }
  512. public static function dynamicString(str:String):HxDynamicStr {
  513. return @:privateAccess new HxDynamicStr(str);
  514. }
  515. /**
  516. Creates Haxe-compatible closure of an instance method.
  517. @param obj - any object
  518. **/
  519. public static function getInstanceClosure(obj:{?__hx_closureCache:NativeAssocArray<HxClosure>}, methodName:String) {
  520. var result = Syntax.coalesce(obj.__hx_closureCache[methodName], null);
  521. if (result != null) {
  522. return result;
  523. }
  524. result = new HxClosure(obj, methodName);
  525. if (!Global.property_exists(obj, '__hx_closureCache')) {
  526. obj.__hx_closureCache = new NativeAssocArray();
  527. }
  528. obj.__hx_closureCache[methodName] = result;
  529. return result;
  530. }
  531. /**
  532. Creates Haxe-compatible closure of a static method.
  533. **/
  534. public static function getStaticClosure(phpClassName:String, methodName:String) {
  535. var result = Syntax.coalesce(staticClosures[phpClassName][methodName], null);
  536. if (result != null) {
  537. return result;
  538. }
  539. result = new HxClosure(phpClassName, methodName);
  540. if (!Global.array_key_exists(phpClassName, staticClosures)) {
  541. staticClosures[phpClassName] = new NativeAssocArray();
  542. }
  543. staticClosures[phpClassName][methodName] = result;
  544. return result;
  545. }
  546. /**
  547. Creates Haxe-compatible closure.
  548. @param type `this` for instance methods; full php class name for static methods
  549. @param func Method name
  550. **/
  551. public static inline function closure(target:Dynamic, func:String):HxClosure {
  552. return target.is_string() ? getStaticClosure(target, func) : getInstanceClosure(target, func);
  553. }
  554. /**
  555. Get UTF-8 code of che first character in `s` without any checks
  556. **/
  557. static public inline function unsafeOrd(s:NativeString):Int {
  558. var code = Global.ord(s[0]);
  559. if (code < 0xC0) {
  560. return code;
  561. } else if (code < 0xE0) {
  562. return ((code - 0xC0) << 6) + Global.ord(s[1]) - 0x80;
  563. } else if (code < 0xF0) {
  564. return ((code - 0xE0) << 12) + ((Global.ord(s[1]) - 0x80) << 6) + Global.ord(s[2]) - 0x80;
  565. } else {
  566. return ((code - 0xF0) << 18) + ((Global.ord(s[1]) - 0x80) << 12) + ((Global.ord(s[2]) - 0x80) << 6) + Global.ord(s[3]) - 0x80;
  567. }
  568. }
  569. }
  570. /**
  571. Class<T> implementation for Haxe->PHP internals.
  572. **/
  573. @:keep
  574. @:dox(hide)
  575. private class HxClass {
  576. public var phpClassName(default, null):String;
  577. public function new(phpClassName:String):Void {
  578. this.phpClassName = phpClassName;
  579. }
  580. /**
  581. Magic method to call static methods of this class, when `HxClass` instance is in a `Dynamic` variable.
  582. **/
  583. @:phpMagic
  584. function __call(method:String, args:NativeArray):Dynamic {
  585. var callback = (phpClassName == 'String' ? Syntax.nativeClassName(HxString) : phpClassName) + '::' + method;
  586. return Global.call_user_func_array(callback, args);
  587. }
  588. /**
  589. Magic method to get static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  590. **/
  591. @:phpMagic
  592. function __get(property:String):Dynamic {
  593. if (Global.defined('$phpClassName::$property')) {
  594. return Global.constant('$phpClassName::$property');
  595. } else if (Boot.hasGetter(phpClassName, property)) {
  596. return Syntax.staticCall(phpClassName, 'get_$property');
  597. } else if (phpClassName.method_exists(property)) {
  598. return new HxClosure(phpClassName, property);
  599. } else {
  600. return Syntax.getStaticField(phpClassName, property);
  601. }
  602. }
  603. /**
  604. Magic method to set static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  605. **/
  606. @:phpMagic
  607. function __set(property:String, value:Dynamic):Void {
  608. if (Boot.hasSetter(phpClassName, property)) {
  609. Syntax.staticCall(phpClassName, 'set_$property', value);
  610. } else {
  611. Syntax.setStaticField(phpClassName, property, value);
  612. }
  613. }
  614. }
  615. /**
  616. Base class for enum types
  617. **/
  618. @:keep
  619. @:dox(hide)
  620. @:allow(php.Boot.stringify)
  621. private class HxEnum {
  622. final tag:String;
  623. final index:Int;
  624. final params:NativeArray;
  625. public function new(tag:String, index:Int, arguments:NativeArray = null):Void {
  626. this.tag = tag;
  627. this.index = index;
  628. params = (arguments == null ? new NativeArray() : arguments);
  629. }
  630. /**
  631. Get string representation of this `Class`
  632. **/
  633. public function toString():String {
  634. return __toString();
  635. }
  636. /**
  637. PHP magic method to get string representation of this `Class`
  638. **/
  639. @:phpMagic
  640. public function __toString():String {
  641. return Boot.stringify(this);
  642. }
  643. }
  644. /**
  645. `String` implementation
  646. **/
  647. @:keep
  648. @:dox(hide)
  649. private class HxString {
  650. public static function toUpperCase(str:String):String {
  651. return Global.mb_strtoupper(str);
  652. }
  653. public static function toLowerCase(str:String):String {
  654. return Global.mb_strtolower(str);
  655. }
  656. public static function charAt(str:String, index:Int):String {
  657. return index < 0 ? '' : Global.mb_substr(str, index, 1);
  658. }
  659. public static function charCodeAt(str:String, index:Int):Null<Int> {
  660. if (index < 0 || str == '') {
  661. return null;
  662. }
  663. if (index == 0) {
  664. return Boot.unsafeOrd(str);
  665. }
  666. var char = Global.mb_substr(str, index, 1);
  667. return char == '' ? null : Boot.unsafeOrd(char);
  668. }
  669. public static function indexOf(str:String, search:String, startIndex:Int = null):Int {
  670. if (startIndex == null) {
  671. startIndex = 0;
  672. } else {
  673. var length = str.length;
  674. if (startIndex < 0) {
  675. startIndex += length;
  676. if (startIndex < 0) {
  677. startIndex = 0;
  678. }
  679. }
  680. if (startIndex >= length && search != '') {
  681. return -1;
  682. }
  683. }
  684. var index:EitherType<Int, Bool> = if (search == '') {
  685. var length = str.length;
  686. startIndex > length ? length : startIndex;
  687. } else {
  688. Global.mb_strpos(str, search, startIndex);
  689. }
  690. return (index == false ? -1 : index);
  691. }
  692. public static function lastIndexOf(str:String, search:String, startIndex:Int = null):Int {
  693. var start = startIndex;
  694. if (start == null) {
  695. start = 0;
  696. } else {
  697. var length = str.length;
  698. if (start >= 0) {
  699. start = start - length;
  700. if (start > 0) {
  701. start = 0;
  702. }
  703. } else if (start < -length) {
  704. start = -length;
  705. }
  706. }
  707. var index:EitherType<Int, Bool> = if (search == '') {
  708. var length = str.length;
  709. startIndex == null || startIndex > length ? length : startIndex;
  710. } else {
  711. Global.mb_strrpos(str, search, start);
  712. }
  713. if (index == false) {
  714. return -1;
  715. } else {
  716. return index;
  717. }
  718. }
  719. public static function split(str:String, delimiter:String):Array<String> {
  720. var arr:NativeArray = if (delimiter == '') {
  721. Global.preg_split('//u', str, -1, Const.PREG_SPLIT_NO_EMPTY);
  722. } else {
  723. delimiter = Global.preg_quote(delimiter, '/');
  724. Global.preg_split('/$delimiter/', str);
  725. }
  726. return @:privateAccess Array.wrap(arr);
  727. }
  728. public static function substr(str:String, pos:Int, ?len:Int):String {
  729. return Global.mb_substr(str, pos, len);
  730. }
  731. public static function substring(str:String, startIndex:Int, ?endIndex:Int):String {
  732. if (endIndex == null) {
  733. if (startIndex < 0) {
  734. startIndex = 0;
  735. }
  736. return Global.mb_substr(str, startIndex);
  737. }
  738. if (endIndex < 0) {
  739. endIndex = 0;
  740. }
  741. if (startIndex < 0) {
  742. startIndex = 0;
  743. }
  744. if (startIndex > endIndex) {
  745. var tmp = endIndex;
  746. endIndex = startIndex;
  747. startIndex = tmp;
  748. }
  749. return Global.mb_substr(str, startIndex, endIndex - startIndex);
  750. }
  751. public static function toString(str:String):String {
  752. return str;
  753. }
  754. public static function fromCharCode(code:Int):String {
  755. return Global.mb_chr(code);
  756. }
  757. }
  758. /**
  759. For Dynamic access which looks like String.
  760. Instances of this class should not be saved anywhere.
  761. Instead it should be used to immediately invoke a String field right after instance creation one time only.
  762. **/
  763. @:dox(hide)
  764. @:keep
  765. private class HxDynamicStr extends HxClosure {
  766. static var hxString:String = (cast HxString : HxClass).phpClassName;
  767. /**
  768. Returns HxDynamicStr instance if `value` is a string.
  769. Otherwise returns `value` as-is.
  770. **/
  771. static function wrap(value:Dynamic):Dynamic {
  772. if (value.is_string()) {
  773. return new HxDynamicStr(value);
  774. } else {
  775. return value;
  776. }
  777. }
  778. static inline function invoke(str:String, method:String, args:NativeArray):Dynamic {
  779. Global.array_unshift(args, str);
  780. return Global.call_user_func_array(hxString + '::' + method, args);
  781. }
  782. function new(str:String) {
  783. super(str, null);
  784. }
  785. @:phpMagic
  786. function __get(field:String):Dynamic {
  787. switch (field) {
  788. case 'length':
  789. return (target : String).length;
  790. case _:
  791. func = field;
  792. return this;
  793. }
  794. }
  795. @:phpMagic
  796. function __call(method:String, args:NativeArray):Dynamic {
  797. return invoke(target, method, args);
  798. }
  799. /**
  800. @see http://php.net/manual/en/language.oop5.magic.php#object.invoke
  801. **/
  802. @:phpMagic
  803. override public function __invoke() {
  804. return invoke(target, func, Global.func_get_args());
  805. }
  806. /**
  807. Generates callable value for PHP
  808. **/
  809. override public function getCallback(eThis:Dynamic = null):NativeIndexedArray<Dynamic> {
  810. if (eThis == null) {
  811. return Syntax.arrayDecl((this : Dynamic), func);
  812. }
  813. return Syntax.arrayDecl((new HxDynamicStr(eThis) : Dynamic), func);
  814. }
  815. /**
  816. Invoke this closure with `newThis` instead of `this`
  817. **/
  818. override public function callWith(newThis:Dynamic, args:NativeArray):Dynamic {
  819. if (newThis == null) {
  820. newThis = target;
  821. }
  822. return invoke(newThis, func, args);
  823. }
  824. }
  825. /**
  826. Anonymous objects implementation
  827. **/
  828. @:keep
  829. @:dox(hide)
  830. private class HxAnon extends StdClass {
  831. public function new(fields:NativeArray = null) {
  832. super();
  833. if (fields != null) {
  834. Syntax.foreach(fields, function(name, value) Syntax.setField(this, name, value));
  835. }
  836. }
  837. @:phpMagic
  838. function __get(name:String) {
  839. return null;
  840. }
  841. @:phpMagic
  842. function __call(name:String, args:NativeArray):Dynamic {
  843. return Syntax.code("($this->{0})(...{1})", name, args);
  844. }
  845. }
  846. /**
  847. Closures implementation
  848. **/
  849. @:keep
  850. @:dox(hide)
  851. private class HxClosure {
  852. /** `this` for instance methods; php class name for static methods */
  853. var target:Dynamic;
  854. /** Method name for methods */
  855. var func:String;
  856. /** A callable value, which can be invoked by PHP */
  857. var callable:Any;
  858. public function new(target:Dynamic, func:String):Void {
  859. this.target = target;
  860. this.func = func;
  861. // Force runtime error if trying to create a closure of an instance which happen to be `null`
  862. if (target.is_null()) {
  863. throw "Unable to create closure on `null`";
  864. }
  865. callable = Std.is(target, HxAnon) ? Syntax.field(target, func) : Syntax.arrayDecl(target, func);
  866. }
  867. /**
  868. @see http://php.net/manual/en/language.oop5.magic.php#object.invoke
  869. **/
  870. @:phpMagic
  871. public function __invoke() {
  872. return Global.call_user_func_array(callable, Global.func_get_args());
  873. }
  874. /**
  875. Generates callable value for PHP
  876. **/
  877. public function getCallback(eThis:Dynamic = null):NativeIndexedArray<Dynamic> {
  878. if (eThis == null) {
  879. eThis = target;
  880. }
  881. if (Std.is(eThis, HxAnon)) {
  882. return Syntax.field(eThis, func);
  883. }
  884. return Syntax.arrayDecl(eThis, func);
  885. }
  886. /**
  887. Check if this is the same closure
  888. **/
  889. public function equals(closure:HxClosure):Bool {
  890. return (target == closure.target && func == closure.func);
  891. }
  892. /**
  893. Invoke this closure with `newThis` instead of `this`
  894. **/
  895. public function callWith(newThis:Dynamic, args:NativeArray):Dynamic {
  896. return Global.call_user_func_array(getCallback(newThis), args);
  897. }
  898. }
  899. /**
  900. Special exception which is used to wrap non-throwable values
  901. **/
  902. @:keep
  903. @:dox(hide)
  904. private class HxException extends Exception {
  905. var e:Dynamic;
  906. public function new(e:Dynamic):Void {
  907. this.e = e;
  908. super(Boot.stringify(e));
  909. }
  910. }