Boot.hx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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):Null<HxClosure> {
  530. var result = Syntax.coalesce(obj.__hx_closureCache[methodName], null);
  531. if (result != null) {
  532. return result;
  533. }
  534. if(!Global.method_exists(obj, methodName) && !Global.isset(Syntax.field(obj, methodName))) {
  535. return null;
  536. }
  537. result = new HxClosure(obj, methodName);
  538. if (!Global.property_exists(obj, '__hx_closureCache')) {
  539. obj.__hx_closureCache = new NativeAssocArray();
  540. }
  541. obj.__hx_closureCache[methodName] = result;
  542. return result;
  543. }
  544. /**
  545. Creates Haxe-compatible closure of a static method.
  546. **/
  547. public static function getStaticClosure(phpClassName:String, methodName:String) {
  548. var result = Syntax.coalesce(staticClosures[phpClassName][methodName], null);
  549. if (result != null) {
  550. return result;
  551. }
  552. result = new HxClosure(phpClassName, methodName);
  553. if (!Global.array_key_exists(phpClassName, staticClosures)) {
  554. staticClosures[phpClassName] = new NativeAssocArray();
  555. }
  556. staticClosures[phpClassName][methodName] = result;
  557. return result;
  558. }
  559. /**
  560. Creates Haxe-compatible closure.
  561. @param type `this` for instance methods; full php class name for static methods
  562. @param func Method name
  563. **/
  564. public static inline function closure(target:Dynamic, func:String):HxClosure {
  565. return target.is_string() ? getStaticClosure(target, func) : getInstanceClosure(target, func);
  566. }
  567. /**
  568. Get UTF-8 code of the first character in `s` without any checks
  569. **/
  570. static public inline function unsafeOrd(s:NativeString):Int {
  571. var code = Global.ord(s[0]);
  572. if (code < 0xC0) {
  573. return code;
  574. } else if (code < 0xE0) {
  575. return ((code - 0xC0) << 6) + Global.ord(s[1]) - 0x80;
  576. } else if (code < 0xF0) {
  577. return ((code - 0xE0) << 12) + ((Global.ord(s[1]) - 0x80) << 6) + Global.ord(s[2]) - 0x80;
  578. } else {
  579. return ((code - 0xF0) << 18) + ((Global.ord(s[1]) - 0x80) << 12) + ((Global.ord(s[2]) - 0x80) << 6) + Global.ord(s[3]) - 0x80;
  580. }
  581. }
  582. }
  583. /**
  584. Class<T> implementation for Haxe->PHP internals.
  585. **/
  586. @:keep
  587. @:dox(hide)
  588. private class HxClass {
  589. public var phpClassName(default, null):String;
  590. public function new(phpClassName:String):Void {
  591. this.phpClassName = phpClassName;
  592. }
  593. /**
  594. Magic method to call static methods of this class, when `HxClass` instance is in a `Dynamic` variable.
  595. **/
  596. @:phpMagic
  597. function __call(method:String, args:NativeArray):Dynamic {
  598. var callback = (phpClassName == 'String' ? Syntax.nativeClassName(HxString) : phpClassName) + '::' + method;
  599. return Global.call_user_func_array(callback, args);
  600. }
  601. /**
  602. Magic method to get static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  603. **/
  604. @:phpMagic
  605. function __get(property:String):Dynamic {
  606. if (Global.defined('$phpClassName::$property')) {
  607. return Global.constant('$phpClassName::$property');
  608. } else if (Boot.hasGetter(phpClassName, property)) {
  609. return Syntax.staticCall(phpClassName, 'get_$property');
  610. } else if (phpClassName.method_exists(property)) {
  611. return Boot.getStaticClosure(phpClassName, property);
  612. } else {
  613. return Syntax.getStaticField(phpClassName, property);
  614. }
  615. }
  616. /**
  617. Magic method to set static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  618. **/
  619. @:phpMagic
  620. function __set(property:String, value:Dynamic):Void {
  621. if (Boot.hasSetter(phpClassName, property)) {
  622. Syntax.staticCall(phpClassName, 'set_$property', value);
  623. } else {
  624. Syntax.setStaticField(phpClassName, property, value);
  625. }
  626. }
  627. }
  628. /**
  629. Base class for enum types
  630. **/
  631. @:keep
  632. @:dox(hide)
  633. @:allow(php.Boot.stringify)
  634. @:allow(Type)
  635. private class HxEnum {
  636. final tag:String;
  637. final index:Int;
  638. final params:NativeArray;
  639. public function new(tag:String, index:Int, arguments:NativeArray = null):Void {
  640. this.tag = tag;
  641. this.index = index;
  642. params = (arguments == null ? new NativeArray() : arguments);
  643. }
  644. /**
  645. Get string representation of this `Class`
  646. **/
  647. public function toString():String {
  648. return __toString();
  649. }
  650. /**
  651. PHP magic method to get string representation of this `Class`
  652. **/
  653. @:phpMagic
  654. public function __toString():String {
  655. return Boot.stringify(this);
  656. }
  657. extern public static function __hx__list():Array<String>;
  658. }
  659. /**
  660. `String` implementation
  661. **/
  662. @:keep
  663. @:dox(hide)
  664. private class HxString {
  665. public static function toUpperCase(str:String):String {
  666. return Global.mb_strtoupper(str);
  667. }
  668. public static function toLowerCase(str:String):String {
  669. return Global.mb_strtolower(str);
  670. }
  671. public static function charAt(str:String, index:Int):String {
  672. return index < 0 ? '' : Global.mb_substr(str, index, 1);
  673. }
  674. public static function charCodeAt(str:String, index:Int):Null<Int> {
  675. if (index < 0 || str == '') {
  676. return null;
  677. }
  678. if (index == 0) {
  679. return Boot.unsafeOrd(str);
  680. }
  681. var char = Global.mb_substr(str, index, 1);
  682. return char == '' ? null : Boot.unsafeOrd(char);
  683. }
  684. public static function indexOf(str:String, search:String, startIndex:Int = null):Int {
  685. if (startIndex == null) {
  686. startIndex = 0;
  687. } else {
  688. var length = str.length;
  689. if (startIndex < 0) {
  690. startIndex += length;
  691. if (startIndex < 0) {
  692. startIndex = 0;
  693. }
  694. }
  695. if (startIndex >= length && search != '') {
  696. return -1;
  697. }
  698. }
  699. var index:EitherType<Int, Bool> = if (search == '') {
  700. var length = str.length;
  701. startIndex > length ? length : startIndex;
  702. } else {
  703. Global.mb_strpos(str, search, startIndex);
  704. }
  705. return (index == false ? -1 : index);
  706. }
  707. public static function lastIndexOf(str:String, search:String, startIndex:Int = null):Int {
  708. var start = startIndex;
  709. if (start == null) {
  710. start = 0;
  711. } else {
  712. var length = str.length;
  713. if (start >= 0) {
  714. start = start - length;
  715. if (start > 0) {
  716. start = 0;
  717. }
  718. } else if (start < -length) {
  719. start = -length;
  720. }
  721. }
  722. var index:EitherType<Int, Bool> = if (search == '') {
  723. var length = str.length;
  724. startIndex == null || startIndex > length ? length : startIndex;
  725. } else {
  726. Global.mb_strrpos(str, search, start);
  727. }
  728. if (index == false) {
  729. return -1;
  730. } else {
  731. return index;
  732. }
  733. }
  734. public static function split(str:String, delimiter:String):Array<String> {
  735. var arr:NativeArray = if (delimiter == '') {
  736. Global.preg_split('//u', str, -1, Const.PREG_SPLIT_NO_EMPTY);
  737. } else {
  738. delimiter = Global.preg_quote(delimiter, '/');
  739. Global.preg_split('/$delimiter/', str);
  740. }
  741. return @:privateAccess Array.wrap(arr);
  742. }
  743. public static function substr(str:String, pos:Int, ?len:Int):String {
  744. return Global.mb_substr(str, pos, len);
  745. }
  746. public static function substring(str:String, startIndex:Int, ?endIndex:Int):String {
  747. if (endIndex == null) {
  748. if (startIndex < 0) {
  749. startIndex = 0;
  750. }
  751. return Global.mb_substr(str, startIndex);
  752. }
  753. if (endIndex < 0) {
  754. endIndex = 0;
  755. }
  756. if (startIndex < 0) {
  757. startIndex = 0;
  758. }
  759. if (startIndex > endIndex) {
  760. var tmp = endIndex;
  761. endIndex = startIndex;
  762. startIndex = tmp;
  763. }
  764. return Global.mb_substr(str, startIndex, endIndex - startIndex);
  765. }
  766. public static function toString(str:String):String {
  767. return str;
  768. }
  769. public static function fromCharCode(code:Int):String {
  770. return Global.mb_chr(code);
  771. }
  772. }
  773. /**
  774. For Dynamic access which looks like String.
  775. Instances of this class should not be saved anywhere.
  776. Instead it should be used to immediately invoke a String field right after instance creation one time only.
  777. **/
  778. @:dox(hide)
  779. @:keep
  780. private class HxDynamicStr extends HxClosure {
  781. static var hxString:String = (cast HxString : HxClass).phpClassName;
  782. /**
  783. Returns HxDynamicStr instance if `value` is a string.
  784. Otherwise returns `value` as-is.
  785. **/
  786. static function wrap(value:Dynamic):Dynamic {
  787. if (value.is_string()) {
  788. return new HxDynamicStr(value);
  789. } else {
  790. return value;
  791. }
  792. }
  793. static inline function invoke(str:String, method:String, args:NativeArray):Dynamic {
  794. Global.array_unshift(args, str);
  795. return Global.call_user_func_array(hxString + '::' + method, args);
  796. }
  797. function new(str:String) {
  798. super(str, null);
  799. }
  800. @:phpMagic
  801. function __get(field:String):Dynamic {
  802. switch (field) {
  803. case 'length':
  804. return (target : String).length;
  805. case _:
  806. func = field;
  807. return this;
  808. }
  809. }
  810. @:phpMagic
  811. function __call(method:String, args:NativeArray):Dynamic {
  812. return invoke(target, method, args);
  813. }
  814. /**
  815. @see http://php.net/manual/en/language.oop5.magic.php#object.invoke
  816. **/
  817. @:phpMagic
  818. override public function __invoke() {
  819. return invoke(target, func, Global.func_get_args());
  820. }
  821. /**
  822. Generates callable value for PHP
  823. **/
  824. override public function getCallback(eThis:Dynamic = null):NativeIndexedArray<Dynamic> {
  825. if (eThis == null) {
  826. return Syntax.arrayDecl((this : Dynamic), func);
  827. }
  828. return Syntax.arrayDecl((new HxDynamicStr(eThis) : Dynamic), func);
  829. }
  830. /**
  831. Invoke this closure with `newThis` instead of `this`
  832. **/
  833. override public function callWith(newThis:Dynamic, args:NativeArray):Dynamic {
  834. if (newThis == null) {
  835. newThis = target;
  836. }
  837. return invoke(newThis, func, args);
  838. }
  839. }
  840. /**
  841. Anonymous objects implementation
  842. **/
  843. @:keep
  844. @:dox(hide)
  845. private class HxAnon extends StdClass {
  846. public function new(fields:NativeArray = null) {
  847. super();
  848. if (fields != null) {
  849. Syntax.foreach(fields, function(name, value) Syntax.setField(this, name, value));
  850. }
  851. }
  852. @:phpMagic
  853. function __get(name:String) {
  854. return null;
  855. }
  856. @:phpMagic
  857. function __call(name:String, args:NativeArray):Dynamic {
  858. return Syntax.code("($this->{0})(...{1})", name, args);
  859. }
  860. }
  861. /**
  862. Closures implementation
  863. **/
  864. @:keep
  865. @:dox(hide)
  866. private class HxClosure {
  867. /** `this` for instance methods; php class name for static methods */
  868. var target:Dynamic;
  869. /** Method name for methods */
  870. var func:String;
  871. /** A callable value, which can be invoked by PHP */
  872. var callable:Any;
  873. public function new(target:Dynamic, func:String):Void {
  874. this.target = target;
  875. this.func = func;
  876. // Force runtime error if trying to create a closure of an instance which happen to be `null`
  877. if (target.is_null()) {
  878. throw "Unable to create closure on `null`";
  879. }
  880. callable = Std.isOfType(target, HxAnon) ? Syntax.field(target, func) : Syntax.arrayDecl(target, func);
  881. }
  882. /**
  883. @see http://php.net/manual/en/language.oop5.magic.php#object.invoke
  884. **/
  885. @:phpMagic
  886. public function __invoke() {
  887. return Global.call_user_func_array(callable, Global.func_get_args());
  888. }
  889. /**
  890. Generates callable value for PHP
  891. **/
  892. public function getCallback(eThis:Dynamic = null):NativeIndexedArray<Dynamic> {
  893. if (eThis == null) {
  894. eThis = target;
  895. }
  896. if (Std.isOfType(eThis, HxAnon)) {
  897. return Syntax.field(eThis, func);
  898. }
  899. return Syntax.arrayDecl(eThis, func);
  900. }
  901. /**
  902. Check if this is the same closure
  903. **/
  904. public function equals(closure:HxClosure):Bool {
  905. return (target == closure.target && func == closure.func);
  906. }
  907. /**
  908. Invoke this closure with `newThis` instead of `this`
  909. **/
  910. public function callWith(newThis:Dynamic, args:NativeArray):Dynamic {
  911. return Global.call_user_func_array(getCallback(newThis), args);
  912. }
  913. }