2
0

Boot.hx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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.isOfType(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. Unsafe cast to HxEnum
  263. **/
  264. public static inline function castEnumValue(enm:EnumValue):HxEnum {
  265. return cast enm;
  266. }
  267. /**
  268. Returns `Class<T>` for `HxClosure`
  269. **/
  270. public static inline function closureHxClass():HxClass {
  271. return cast HxClosure;
  272. }
  273. /**
  274. Implementation for `cast(value, Class<Dynamic>)`
  275. @throws haxe.ValueError if `value` cannot be casted to this type
  276. **/
  277. public static function typedCast(hxClass:HxClass, value:Dynamic):Dynamic {
  278. if (value == null)
  279. return null;
  280. switch (hxClass.phpClassName) {
  281. case 'Int':
  282. if (Boot.isNumber(value)) {
  283. return Global.intval(value);
  284. }
  285. case 'Float':
  286. if (Boot.isNumber(value)) {
  287. return value.floatval();
  288. }
  289. case 'Bool':
  290. if (value.is_bool()) {
  291. return value;
  292. }
  293. case 'String':
  294. if (value.is_string()) {
  295. return value;
  296. }
  297. case 'php\\NativeArray':
  298. if (value.is_array()) {
  299. return value;
  300. }
  301. case _:
  302. if (value.is_object() && Std.isOfType(value, cast hxClass)) {
  303. return value;
  304. }
  305. }
  306. throw 'Cannot cast ' + Std.string(value) + ' to ' + getClassName(hxClass.phpClassName);
  307. }
  308. /**
  309. Returns string representation of `value`
  310. **/
  311. public static function stringify(value:Dynamic, maxRecursion:Int = 10):String {
  312. if (maxRecursion <= 0) {
  313. return '<...>';
  314. }
  315. if (value == null) {
  316. return 'null';
  317. }
  318. if (value.is_string()) {
  319. return value;
  320. }
  321. if (value.is_int() || value.is_float()) {
  322. return Syntax.string(value);
  323. }
  324. if (value.is_bool()) {
  325. return value ? 'true' : 'false';
  326. }
  327. if (value.is_array()) {
  328. var strings = Syntax.arrayDecl();
  329. Syntax.foreach(value, function(key:Dynamic, item:Dynamic) {
  330. strings.push(Syntax.string(key) + ' => ' + stringify(item, maxRecursion - 1));
  331. });
  332. return '[' + Global.implode(', ', strings) + ']';
  333. }
  334. if (value.is_object()) {
  335. if (Std.isOfType(value, Array)) {
  336. return inline stringifyNativeIndexedArray(value.arr, maxRecursion - 1);
  337. }
  338. if (Std.isOfType(value, HxEnum)) {
  339. var e:HxEnum = value;
  340. var result = e.tag;
  341. if (Global.count(e.params) > 0) {
  342. var strings = Global.array_map(function(item) return Boot.stringify(item, maxRecursion - 1), e.params);
  343. result += '(' + Global.implode(',', strings) + ')';
  344. }
  345. return result;
  346. }
  347. if (value.method_exists('toString')) {
  348. return value.toString();
  349. }
  350. if (value.method_exists('__toString')) {
  351. return value.__toString();
  352. }
  353. if (Std.isOfType(value, StdClass)) {
  354. if (Global.isset(Syntax.field(value, 'toString')) && value.toString.is_callable()) {
  355. return value.toString();
  356. }
  357. var result = new NativeIndexedArray<String>();
  358. var data = Global.get_object_vars(value);
  359. for (key in data.array_keys()) {
  360. result.array_push('$key : ' + stringify(data[key], maxRecursion - 1));
  361. }
  362. return '{ ' + Global.implode(', ', result) + ' }';
  363. }
  364. if (isFunction(value)) {
  365. return '<function>';
  366. }
  367. if (Std.isOfType(value, HxClass)) {
  368. return '[class ' + getClassName((value : HxClass).phpClassName) + ']';
  369. } else {
  370. return '[object ' + getClassName(Global.get_class(value)) + ']';
  371. }
  372. }
  373. throw "Unable to stringify value";
  374. }
  375. static public function stringifyNativeIndexedArray<T>(arr:NativeIndexedArray<T>, maxRecursion:Int = 10):String {
  376. var strings = Syntax.arrayDecl();
  377. Syntax.foreach(arr, function(index:Int, value:T) {
  378. strings[index] = Boot.stringify(value, maxRecursion - 1);
  379. });
  380. return '[' + Global.implode(',', strings) + ']';
  381. }
  382. static public inline function isNumber(value:Dynamic) {
  383. return value.is_int() || value.is_float();
  384. }
  385. /**
  386. Check if specified values are equal
  387. **/
  388. public static function equal(left:Dynamic, right:Dynamic):Bool {
  389. if (isNumber(left) && isNumber(right)) {
  390. return Syntax.equal(left, right);
  391. }
  392. if (Std.isOfType(left, HxClosure) && Std.isOfType(right, HxClosure)) {
  393. return (left : HxClosure).equals(right);
  394. }
  395. return Syntax.strictEqual(left, right);
  396. }
  397. /**
  398. Concat `left` and `right` if both are strings or string and null.
  399. Otherwise return sum of `left` and `right`.
  400. **/
  401. public static function addOrConcat(left:Dynamic, right:Dynamic):Dynamic {
  402. if (left.is_string() || right.is_string()) {
  403. return (left : String) + (right : String);
  404. }
  405. return Syntax.add(left, right);
  406. }
  407. @:deprecated('php.Boot.is() is deprecated. Use php.Boot.isOfType() instead')
  408. public static inline function is(value:Dynamic, type:HxClass):Bool {
  409. return isOfType(value, type);
  410. }
  411. /**
  412. `Std.isOfType()` implementation
  413. **/
  414. public static function isOfType(value:Dynamic, type:HxClass):Bool {
  415. if (type == null)
  416. return false;
  417. var phpType = type.phpClassName;
  418. #if php_prefix
  419. var prefix = getPrefix();
  420. if (Global.substr(phpType, 0, Global.strlen(prefix) + 1) == '$prefix\\') {
  421. phpType = Global.substr(phpType, Global.strlen(prefix) + 1);
  422. }
  423. #end
  424. switch (phpType) {
  425. case 'Dynamic':
  426. return value != null;
  427. case 'Int':
  428. return (value.is_int() || (value.is_float() && Syntax.equal(Syntax.int(value), value) && !Global.is_nan(value)))
  429. && Global.abs(value) <= 2147483648;
  430. case 'Float':
  431. return value.is_float() || value.is_int();
  432. case 'Bool':
  433. return value.is_bool();
  434. case 'String':
  435. return value.is_string();
  436. case 'php\\NativeArray', 'php\\_NativeArray\\NativeArray_Impl_':
  437. return value.is_array();
  438. case 'Enum' | 'Class':
  439. if (Std.isOfType(value, HxClass)) {
  440. var valuePhpClass = (cast value : HxClass).phpClassName;
  441. var enumPhpClass = (cast HxEnum : HxClass).phpClassName;
  442. var isEnumType = Global.is_subclass_of(valuePhpClass, enumPhpClass);
  443. return (phpType == 'Enum' ? isEnumType : !isEnumType);
  444. }
  445. case _:
  446. if (value.is_object()) {
  447. var type:Class<Dynamic> = cast type;
  448. return Syntax.instanceof(value, type);
  449. }
  450. }
  451. return false;
  452. }
  453. /**
  454. Check if `value` is a `Class<T>`
  455. **/
  456. public static inline function isClass(value:Dynamic):Bool {
  457. return Std.isOfType(value, HxClass);
  458. }
  459. /**
  460. Check if `value` is an enum constructor instance
  461. **/
  462. public static inline function isEnumValue(value:Dynamic):Bool {
  463. return Std.isOfType(value, HxEnum);
  464. }
  465. /**
  466. Check if `value` is a function
  467. **/
  468. public static inline function isFunction(value:Dynamic):Bool {
  469. return Std.isOfType(value, Closure) || Std.isOfType(value, HxClosure);
  470. }
  471. /**
  472. Check if `value` is an instance of `HxClosure`
  473. **/
  474. public static inline function isHxClosure(value:Dynamic):Bool {
  475. return Std.isOfType(value, HxClosure);
  476. }
  477. /**
  478. Performs `left >>> right` operation
  479. **/
  480. public static function shiftRightUnsigned(left:Int, right:Int):Int {
  481. if (right == 0) {
  482. return left;
  483. } else if (left >= 0) {
  484. return (left >> right) & ~((1 << (8 * Const.PHP_INT_SIZE - 1)) >> (right - 1));
  485. } else {
  486. return (left >> right) & (0x7fffffff >> (right - 1));
  487. }
  488. }
  489. /**
  490. Helper method to avoid "Cannot use temporary expression in write context" error for expressions like this:
  491. ```haxe
  492. (new MyClass()).fieldName = 'value';
  493. ```
  494. **/
  495. static public function deref(value:Dynamic):Dynamic {
  496. return value;
  497. }
  498. /**
  499. Create Haxe-compatible anonymous structure of `data` associative array
  500. **/
  501. static public inline function createAnon(data:NativeArray):Dynamic {
  502. return new HxAnon(data);
  503. }
  504. /**
  505. Make sure specified class is loaded
  506. **/
  507. static public inline function ensureLoaded(phpClassName:String):Bool {
  508. return Global.class_exists(phpClassName) || Global.interface_exists(phpClassName);
  509. }
  510. /**
  511. Get `field` of a dynamic `value` in a safe manner (avoid exceptions on trying to get a method)
  512. **/
  513. static public function dynamicField(value:Dynamic, field:String):Dynamic {
  514. if (Global.method_exists(value, field)) {
  515. return closure(value, field);
  516. }
  517. if (Global.is_string(value)) {
  518. value = @:privateAccess new HxDynamicStr(value);
  519. }
  520. return Syntax.field(value, field);
  521. }
  522. public static function dynamicString(str:String):HxDynamicStr {
  523. return @:privateAccess new HxDynamicStr(str);
  524. }
  525. /**
  526. Creates Haxe-compatible closure of an instance method.
  527. @param obj - any object
  528. **/
  529. public static function getInstanceClosure(obj:{?__hx_closureCache:NativeAssocArray<HxClosure>}, methodName:String) {
  530. var result = Syntax.coalesce(obj.__hx_closureCache[methodName], null);
  531. if (result != null) {
  532. return result;
  533. }
  534. result = new HxClosure(obj, methodName);
  535. if (!Global.property_exists(obj, '__hx_closureCache')) {
  536. obj.__hx_closureCache = new NativeAssocArray();
  537. }
  538. obj.__hx_closureCache[methodName] = result;
  539. return result;
  540. }
  541. /**
  542. Creates Haxe-compatible closure of a static method.
  543. **/
  544. public static function getStaticClosure(phpClassName:String, methodName:String) {
  545. var result = Syntax.coalesce(staticClosures[phpClassName][methodName], null);
  546. if (result != null) {
  547. return result;
  548. }
  549. result = new HxClosure(phpClassName, methodName);
  550. if (!Global.array_key_exists(phpClassName, staticClosures)) {
  551. staticClosures[phpClassName] = new NativeAssocArray();
  552. }
  553. staticClosures[phpClassName][methodName] = result;
  554. return result;
  555. }
  556. /**
  557. Creates Haxe-compatible closure.
  558. @param type `this` for instance methods; full php class name for static methods
  559. @param func Method name
  560. **/
  561. public static inline function closure(target:Dynamic, func:String):HxClosure {
  562. return target.is_string() ? getStaticClosure(target, func) : getInstanceClosure(target, func);
  563. }
  564. /**
  565. Get UTF-8 code of the first character in `s` without any checks
  566. **/
  567. static public inline function unsafeOrd(s:NativeString):Int {
  568. var code = Global.ord(s[0]);
  569. if (code < 0xC0) {
  570. return code;
  571. } else if (code < 0xE0) {
  572. return ((code - 0xC0) << 6) + Global.ord(s[1]) - 0x80;
  573. } else if (code < 0xF0) {
  574. return ((code - 0xE0) << 12) + ((Global.ord(s[1]) - 0x80) << 6) + Global.ord(s[2]) - 0x80;
  575. } else {
  576. return ((code - 0xF0) << 18) + ((Global.ord(s[1]) - 0x80) << 12) + ((Global.ord(s[2]) - 0x80) << 6) + Global.ord(s[3]) - 0x80;
  577. }
  578. }
  579. }
  580. /**
  581. Class<T> implementation for Haxe->PHP internals.
  582. **/
  583. @:keep
  584. @:dox(hide)
  585. private class HxClass {
  586. public var phpClassName(default, null):String;
  587. public function new(phpClassName:String):Void {
  588. this.phpClassName = phpClassName;
  589. }
  590. /**
  591. Magic method to call static methods of this class, when `HxClass` instance is in a `Dynamic` variable.
  592. **/
  593. @:phpMagic
  594. function __call(method:String, args:NativeArray):Dynamic {
  595. var callback = (phpClassName == 'String' ? Syntax.nativeClassName(HxString) : phpClassName) + '::' + method;
  596. return Global.call_user_func_array(callback, args);
  597. }
  598. /**
  599. Magic method to get static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  600. **/
  601. @:phpMagic
  602. function __get(property:String):Dynamic {
  603. if (Global.defined('$phpClassName::$property')) {
  604. return Global.constant('$phpClassName::$property');
  605. } else if (Boot.hasGetter(phpClassName, property)) {
  606. return Syntax.staticCall(phpClassName, 'get_$property');
  607. } else if (phpClassName.method_exists(property)) {
  608. return new HxClosure(phpClassName, property);
  609. } else {
  610. return Syntax.getStaticField(phpClassName, property);
  611. }
  612. }
  613. /**
  614. Magic method to set static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  615. **/
  616. @:phpMagic
  617. function __set(property:String, value:Dynamic):Void {
  618. if (Boot.hasSetter(phpClassName, property)) {
  619. Syntax.staticCall(phpClassName, 'set_$property', value);
  620. } else {
  621. Syntax.setStaticField(phpClassName, property, value);
  622. }
  623. }
  624. }
  625. /**
  626. Base class for enum types
  627. **/
  628. @:keep
  629. @:dox(hide)
  630. @:allow(php.Boot.stringify)
  631. @:allow(Type)
  632. private class HxEnum {
  633. final tag:String;
  634. final index:Int;
  635. final params:NativeArray;
  636. public function new(tag:String, index:Int, arguments:NativeArray = null):Void {
  637. this.tag = tag;
  638. this.index = index;
  639. params = (arguments == null ? new NativeArray() : arguments);
  640. }
  641. /**
  642. Get string representation of this `Class`
  643. **/
  644. public function toString():String {
  645. return __toString();
  646. }
  647. /**
  648. PHP magic method to get string representation of this `Class`
  649. **/
  650. @:phpMagic
  651. public function __toString():String {
  652. return Boot.stringify(this);
  653. }
  654. extern public static function __hx__list():Array<String>;
  655. }
  656. /**
  657. `String` implementation
  658. **/
  659. @:keep
  660. @:dox(hide)
  661. private class HxString {
  662. public static function toUpperCase(str:String):String {
  663. return Global.mb_strtoupper(str);
  664. }
  665. public static function toLowerCase(str:String):String {
  666. return Global.mb_strtolower(str);
  667. }
  668. public static function charAt(str:String, index:Int):String {
  669. return index < 0 ? '' : Global.mb_substr(str, index, 1);
  670. }
  671. public static function charCodeAt(str:String, index:Int):Null<Int> {
  672. if (index < 0 || str == '') {
  673. return null;
  674. }
  675. if (index == 0) {
  676. return Boot.unsafeOrd(str);
  677. }
  678. var char = Global.mb_substr(str, index, 1);
  679. return char == '' ? null : Boot.unsafeOrd(char);
  680. }
  681. public static function indexOf(str:String, search:String, startIndex:Int = null):Int {
  682. if (startIndex == null) {
  683. startIndex = 0;
  684. } else {
  685. var length = str.length;
  686. if (startIndex < 0) {
  687. startIndex += length;
  688. if (startIndex < 0) {
  689. startIndex = 0;
  690. }
  691. }
  692. if (startIndex >= length && search != '') {
  693. return -1;
  694. }
  695. }
  696. var index:EitherType<Int, Bool> = if (search == '') {
  697. var length = str.length;
  698. startIndex > length ? length : startIndex;
  699. } else {
  700. Global.mb_strpos(str, search, startIndex);
  701. }
  702. return (index == false ? -1 : index);
  703. }
  704. public static function lastIndexOf(str:String, search:String, startIndex:Int = null):Int {
  705. var start = startIndex;
  706. if (start == null) {
  707. start = 0;
  708. } else {
  709. var length = str.length;
  710. if (start >= 0) {
  711. start = start - length;
  712. if (start > 0) {
  713. start = 0;
  714. }
  715. } else if (start < -length) {
  716. start = -length;
  717. }
  718. }
  719. var index:EitherType<Int, Bool> = if (search == '') {
  720. var length = str.length;
  721. startIndex == null || startIndex > length ? length : startIndex;
  722. } else {
  723. Global.mb_strrpos(str, search, start);
  724. }
  725. if (index == false) {
  726. return -1;
  727. } else {
  728. return index;
  729. }
  730. }
  731. public static function split(str:String, delimiter:String):Array<String> {
  732. var arr:NativeArray = if (delimiter == '') {
  733. Global.preg_split('//u', str, -1, Const.PREG_SPLIT_NO_EMPTY);
  734. } else {
  735. delimiter = Global.preg_quote(delimiter, '/');
  736. Global.preg_split('/$delimiter/', str);
  737. }
  738. return @:privateAccess Array.wrap(arr);
  739. }
  740. public static function substr(str:String, pos:Int, ?len:Int):String {
  741. return Global.mb_substr(str, pos, len);
  742. }
  743. public static function substring(str:String, startIndex:Int, ?endIndex:Int):String {
  744. if (endIndex == null) {
  745. if (startIndex < 0) {
  746. startIndex = 0;
  747. }
  748. return Global.mb_substr(str, startIndex);
  749. }
  750. if (endIndex < 0) {
  751. endIndex = 0;
  752. }
  753. if (startIndex < 0) {
  754. startIndex = 0;
  755. }
  756. if (startIndex > endIndex) {
  757. var tmp = endIndex;
  758. endIndex = startIndex;
  759. startIndex = tmp;
  760. }
  761. return Global.mb_substr(str, startIndex, endIndex - startIndex);
  762. }
  763. public static function toString(str:String):String {
  764. return str;
  765. }
  766. public static function fromCharCode(code:Int):String {
  767. return Global.mb_chr(code);
  768. }
  769. }
  770. /**
  771. For Dynamic access which looks like String.
  772. Instances of this class should not be saved anywhere.
  773. Instead it should be used to immediately invoke a String field right after instance creation one time only.
  774. **/
  775. @:dox(hide)
  776. @:keep
  777. private class HxDynamicStr extends HxClosure {
  778. static var hxString:String = (cast HxString : HxClass).phpClassName;
  779. /**
  780. Returns HxDynamicStr instance if `value` is a string.
  781. Otherwise returns `value` as-is.
  782. **/
  783. static function wrap(value:Dynamic):Dynamic {
  784. if (value.is_string()) {
  785. return new HxDynamicStr(value);
  786. } else {
  787. return value;
  788. }
  789. }
  790. static inline function invoke(str:String, method:String, args:NativeArray):Dynamic {
  791. Global.array_unshift(args, str);
  792. return Global.call_user_func_array(hxString + '::' + method, args);
  793. }
  794. function new(str:String) {
  795. super(str, null);
  796. }
  797. @:phpMagic
  798. function __get(field:String):Dynamic {
  799. switch (field) {
  800. case 'length':
  801. return (target : String).length;
  802. case _:
  803. func = field;
  804. return this;
  805. }
  806. }
  807. @:phpMagic
  808. function __call(method:String, args:NativeArray):Dynamic {
  809. return invoke(target, method, args);
  810. }
  811. /**
  812. @see http://php.net/manual/en/language.oop5.magic.php#object.invoke
  813. **/
  814. @:phpMagic
  815. override public function __invoke() {
  816. return invoke(target, func, Global.func_get_args());
  817. }
  818. /**
  819. Generates callable value for PHP
  820. **/
  821. override public function getCallback(eThis:Dynamic = null):NativeIndexedArray<Dynamic> {
  822. if (eThis == null) {
  823. return Syntax.arrayDecl((this : Dynamic), func);
  824. }
  825. return Syntax.arrayDecl((new HxDynamicStr(eThis) : Dynamic), func);
  826. }
  827. /**
  828. Invoke this closure with `newThis` instead of `this`
  829. **/
  830. override public function callWith(newThis:Dynamic, args:NativeArray):Dynamic {
  831. if (newThis == null) {
  832. newThis = target;
  833. }
  834. return invoke(newThis, func, args);
  835. }
  836. }
  837. /**
  838. Anonymous objects implementation
  839. **/
  840. @:keep
  841. @:dox(hide)
  842. private class HxAnon extends StdClass {
  843. public function new(fields:NativeArray = null) {
  844. super();
  845. if (fields != null) {
  846. Syntax.foreach(fields, function(name, value) Syntax.setField(this, name, value));
  847. }
  848. }
  849. @:phpMagic
  850. function __get(name:String) {
  851. return null;
  852. }
  853. @:phpMagic
  854. function __call(name:String, args:NativeArray):Dynamic {
  855. return Syntax.code("($this->{0})(...{1})", name, args);
  856. }
  857. }
  858. /**
  859. Closures implementation
  860. **/
  861. @:keep
  862. @:dox(hide)
  863. private class HxClosure {
  864. /** `this` for instance methods; php class name for static methods */
  865. var target:Dynamic;
  866. /** Method name for methods */
  867. var func:String;
  868. /** A callable value, which can be invoked by PHP */
  869. var callable:Any;
  870. public function new(target:Dynamic, func:String):Void {
  871. this.target = target;
  872. this.func = func;
  873. // Force runtime error if trying to create a closure of an instance which happen to be `null`
  874. if (target.is_null()) {
  875. throw "Unable to create closure on `null`";
  876. }
  877. callable = Std.isOfType(target, HxAnon) ? Syntax.field(target, func) : Syntax.arrayDecl(target, func);
  878. }
  879. /**
  880. @see http://php.net/manual/en/language.oop5.magic.php#object.invoke
  881. **/
  882. @:phpMagic
  883. public function __invoke() {
  884. return Global.call_user_func_array(callable, Global.func_get_args());
  885. }
  886. /**
  887. Generates callable value for PHP
  888. **/
  889. public function getCallback(eThis:Dynamic = null):NativeIndexedArray<Dynamic> {
  890. if (eThis == null) {
  891. eThis = target;
  892. }
  893. if (Std.isOfType(eThis, HxAnon)) {
  894. return Syntax.field(eThis, func);
  895. }
  896. return Syntax.arrayDecl(eThis, func);
  897. }
  898. /**
  899. Check if this is the same closure
  900. **/
  901. public function equals(closure:HxClosure):Bool {
  902. return (target == closure.target && func == closure.func);
  903. }
  904. /**
  905. Invoke this closure with `newThis` instead of `this`
  906. **/
  907. public function callWith(newThis:Dynamic, args:NativeArray):Dynamic {
  908. return Global.call_user_func_array(getCallback(newThis), args);
  909. }
  910. }