Boot.hx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. /*
  2. * Copyright (C)2005-2017 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. using php.Global;
  25. /**
  26. Various Haxe->PHP compatibility utilities.
  27. You should not use this class directly.
  28. **/
  29. @:keep
  30. @:dox(hide)
  31. class Boot {
  32. /** List of Haxe classes registered by their PHP class names */
  33. @:protected static var aliases = new NativeAssocArray<String>();
  34. /** Cache of HxClass instances */
  35. @:protected static var classes = new NativeAssocArray<HxClass>();
  36. /** List of getters (for Reflect) */
  37. @:protected static var getters = new NativeAssocArray<NativeAssocArray<Bool>>();
  38. /** List of setters (for Reflect) */
  39. @:protected static var setters = new NativeAssocArray<NativeAssocArray<Bool>>();
  40. /** Metadata storage */
  41. @:protected static var meta = new NativeAssocArray<{}>();
  42. /**
  43. Initialization stuff.
  44. This method is called once before invoking any Haxe-generated user code.
  45. **/
  46. static function __init__() {
  47. if (!Global.defined('HAXE_CUSTOM_ERROR_HANDLER') || !Const.HAXE_CUSTOM_ERROR_HANDLER) {
  48. var previousLevel = Global.error_reporting(Const.E_ALL);
  49. var previousHandler = Global.set_error_handler(
  50. function (errno:Int, errstr:String, errfile:String, errline:Int) {
  51. if (Global.error_reporting() & errno == 0) {
  52. return false;
  53. }
  54. throw new ErrorException(errstr, 0, errno, errfile, errline);
  55. }
  56. );
  57. //Already had user-defined handler. Return it.
  58. if (previousHandler != null) {
  59. Global.error_reporting(previousLevel);
  60. Global.set_error_handler(previousHandler);
  61. }
  62. }
  63. }
  64. /**
  65. Returns root namespace based on a value of `--php-prefix` compiler flag.
  66. Returns empty string if no `--php-prefix` provided.
  67. **/
  68. public static inline function getPrefix() : String {
  69. return untyped __php__('self::PHP_PREFIX');
  70. }
  71. /**
  72. Register list of getters to be able to call getters using reflection
  73. **/
  74. public static function registerGetters( phpClassName:String, list:NativeAssocArray<Bool> ) : Void {
  75. getters[phpClassName] = list;
  76. }
  77. /**
  78. Register list of setters to be able to call getters using reflection
  79. **/
  80. public static function registerSetters( phpClassName:String, list:NativeAssocArray<Bool> ) : Void {
  81. setters[phpClassName] = list;
  82. }
  83. /**
  84. Check if specified property has getter
  85. **/
  86. public static function hasGetter( phpClassName:String, property:String ) : Bool {
  87. ensureLoaded(phpClassName);
  88. var has = false;
  89. var phpClassName:haxe.extern.EitherType<Bool,String> = phpClassName;
  90. do {
  91. has = Global.isset(getters[phpClassName][property]);
  92. phpClassName = Global.get_parent_class(phpClassName);
  93. } while (!has && phpClassName != false && Global.class_exists(phpClassName));
  94. return has;
  95. }
  96. /**
  97. Check if specified property has setter
  98. **/
  99. public static function hasSetter( phpClassName:String, property:String ) : Bool {
  100. ensureLoaded(phpClassName);
  101. var has = false;
  102. var phpClassName:haxe.extern.EitherType<Bool,String> = phpClassName;
  103. do {
  104. has = Global.isset(setters[phpClassName][property]);
  105. phpClassName = Global.get_parent_class(phpClassName);
  106. } while (!has && phpClassName != false && Global.class_exists(phpClassName));
  107. return has;
  108. }
  109. /**
  110. Save metadata for specified class
  111. **/
  112. public static function registerMeta( phpClassName:String, data:Dynamic ) : Void {
  113. meta[phpClassName] = data;
  114. }
  115. /**
  116. Retrieve metadata for specified class
  117. **/
  118. public static function getMeta( phpClassName:String ) : Null<Dynamic> {
  119. ensureLoaded(phpClassName);
  120. return Global.isset(meta[phpClassName]) ? meta[phpClassName] : null;
  121. }
  122. /**
  123. Associate PHP class name with Haxe class name
  124. **/
  125. public static function registerClass( phpClassName:String, haxeClassName:String ) : Void {
  126. aliases[phpClassName] = haxeClassName;
  127. }
  128. /**
  129. Get Class<T> instance for PHP fully qualified class name (E.g. '\some\pack\MyClass')
  130. It's always the same instance for the same `phpClassName`
  131. **/
  132. public static function getClass( phpClassName:String ) : HxClass {
  133. if (phpClassName.charAt(0) == '\\') {
  134. phpClassName = phpClassName.substr(1);
  135. }
  136. if (!Global.isset(classes[phpClassName])) {
  137. classes[phpClassName] = new HxClass(phpClassName);
  138. }
  139. return classes[phpClassName];
  140. }
  141. /**
  142. Returns Class<HxAnon>
  143. **/
  144. public static inline function getHxAnon() : HxClass {
  145. return cast HxAnon;
  146. }
  147. /**
  148. Returns Class<HxClass>
  149. **/
  150. public static inline function getHxClass() : HxClass {
  151. return cast HxClass;
  152. }
  153. /**
  154. Returns either Haxe class name for specified `phpClassName` or (if no such Haxe class registered) `phpClassName`.
  155. **/
  156. public static function getClassName( phpClassName:String ) : String {
  157. var hxClass = getClass(phpClassName);
  158. var name = getHaxeName(hxClass);
  159. return (name == null ? hxClass.phpClassName : name);
  160. }
  161. /**
  162. Returns original Haxe fully qualified class name for this type (if exists)
  163. **/
  164. public static function getHaxeName( hxClass:HxClass) : Null<String> {
  165. switch (hxClass.phpClassName) {
  166. case 'Int': return 'Int';
  167. case 'String': return 'String';
  168. case 'Bool': return 'Bool';
  169. case 'Float': return 'Float';
  170. case 'Class': return 'Class';
  171. case 'Enum': return 'Enum';
  172. case 'Dynamic': return 'Dynamic';
  173. case _:
  174. }
  175. inline function exists() return Global.isset(aliases[hxClass.phpClassName]);
  176. if (exists()) {
  177. return aliases[hxClass.phpClassName];
  178. } else if (Global.class_exists(hxClass.phpClassName) && exists()) {
  179. return aliases[hxClass.phpClassName];
  180. } else if (Global.interface_exists(hxClass.phpClassName) && exists()) {
  181. return aliases[hxClass.phpClassName];
  182. }
  183. return null;
  184. }
  185. /**
  186. Find corresponding PHP class name.
  187. Returns `null` if specified class does not exist.
  188. **/
  189. public static function getPhpName( haxeName:String ) : Null<String> {
  190. var prefix = getPrefix();
  191. var phpParts = (prefix.length == 0 ? [] : [prefix]);
  192. var haxeParts = haxeName.split('.');
  193. for (part in haxeParts) {
  194. switch (part.toLowerCase()) {
  195. case "__halt_compiler" | "abstract" | "and" | "array" | "as" | "break" | "callable" | "case" | "catch" | "class"
  196. | "clone" | "const" | "continue" | "declare" | "default" | "die" | "do" | "echo" | "else" | "elseif" | "empty"
  197. | "enddeclare" | "endfor" | "endforeach" | "endif" | "endswitch" | "endwhile" | "eval" | "exit" | "extends"
  198. | "final" | "finally" | "for" | "foreach" | "function" | "global" | "goto" | "if" | "implements" | "include"
  199. | "include_once" | "instanceof" | "insteadof" | "interface" | "isset" | "list" | "namespace" | "new" | "or"
  200. | "print" | "private" | "protected" | "public" | "require" | "require_once" | "return" | "static" | "switch"
  201. | "throw" | "trait" | "try" | "unset" | "use" | "var" | "while" | "xor" | "yield" | "__class__" | "__dir__"
  202. | "__file__" | "__function__" | "__line__" | "__method__" | "__trait__" | "__namespace__" | "int" | "float"
  203. | "bool" | "string" | "true" | "false" | "null" | "parent" | "void" | "iterable":
  204. part += '_hx';
  205. case _:
  206. }
  207. phpParts.push(part);
  208. }
  209. return phpParts.join('\\');
  210. }
  211. /**
  212. Creates Haxe-compatible closure.
  213. @param type `this` for instance methods; full php class name for static methods
  214. @param func Method name
  215. **/
  216. public static inline function closure( target:Dynamic, func:Dynamic ) : HxClosure {
  217. return new HxClosure(target, func);
  218. }
  219. /**
  220. Unsafe cast to HxClosure
  221. **/
  222. public static inline function castClosure(value:Dynamic) : HxClosure {
  223. return value;
  224. }
  225. /**
  226. Returns `Class<T>` for `HxClosure`
  227. **/
  228. public static inline function closureHxClass() : HxClass {
  229. return cast HxClosure;
  230. }
  231. /**
  232. Implementation for `cast(value, Class<Dynamic>)`
  233. @throws HxException if `value` cannot be casted to this type
  234. **/
  235. public static function typedCast( hxClass:HxClass, value:Dynamic ) : Dynamic {
  236. switch (hxClass.phpClassName) {
  237. case 'Int':
  238. if (Boot.isNumber(value)) {
  239. return Global.intval(value);
  240. }
  241. case 'Float':
  242. if (Boot.isNumber(value)) {
  243. return value.floatval();
  244. }
  245. case 'Bool':
  246. if (value.is_bool()) {
  247. return value;
  248. }
  249. case 'String':
  250. if (value.is_string()) {
  251. return value;
  252. }
  253. case 'php\\NativeArray':
  254. if (value.is_array()) {
  255. return value;
  256. }
  257. case _:
  258. if (value.is_object() && Std.is(value, cast hxClass)) {
  259. return value;
  260. }
  261. }
  262. throw 'Cannot cast ' + Std.string(value) + ' to ' + getClassName(hxClass.phpClassName);
  263. }
  264. /**
  265. `trace()` implementation
  266. **/
  267. public static function trace( value:Dynamic, infos:PosInfos ) : Void {
  268. if (infos != null) {
  269. Global.echo('${infos.fileName}:${infos.lineNumber}: ');
  270. }
  271. Global.echo(stringify(value));
  272. if (infos.customParams != null) {
  273. for (value in infos.customParams) {
  274. Global.echo(',' + stringify(value));
  275. }
  276. }
  277. Global.echo('\n');
  278. }
  279. /**
  280. Returns string representation of `value`
  281. **/
  282. public static function stringify( value : Dynamic ) : String {
  283. if (value == null) {
  284. return 'null';
  285. }
  286. if (value.is_string()) {
  287. return value;
  288. }
  289. if (value.is_int() || value.is_float()) {
  290. return Syntax.string(value);
  291. }
  292. if (value.is_bool()) {
  293. return value ? 'true' : 'false';
  294. }
  295. if (value.is_array()) {
  296. var strings = Syntax.arrayDecl();
  297. Syntax.foreach(value, function(key:Dynamic, item:Dynamic) {
  298. Global.array_push(strings, (key:String) + ' => ' + stringify(item));
  299. });
  300. return '[' + Global.implode(', ', strings) + ']';
  301. }
  302. if (value.is_object()) {
  303. if (value.method_exists('toString')) {
  304. return value.toString();
  305. }
  306. if (value.method_exists('__toString')) {
  307. return value.__toString();
  308. }
  309. if (Std.is(value, StdClass)) {
  310. if (Global.isset(Syntax.getField(value, 'toString')) && value.toString.is_callable()) {
  311. return value.toString();
  312. }
  313. var result = new NativeIndexedArray<String>();
  314. var data = Global.get_object_vars(value);
  315. for (key in data.array_keys()) {
  316. result.array_push('$key : ' + stringify(data[key]));
  317. }
  318. return '{ ' + Global.implode(', ', result) + ' }';
  319. }
  320. if (isFunction(value)) {
  321. return '<function>';
  322. }
  323. if (Std.is(value, HxClass)) {
  324. return '[class ' + getClassName((value:HxClass).phpClassName) + ']';
  325. } else {
  326. return '[object ' + getClassName(Global.get_class(value)) + ']';
  327. }
  328. }
  329. throw "Unable to stringify value";
  330. }
  331. static public inline function isNumber( value:Dynamic ) {
  332. return value.is_int() || value.is_float();
  333. }
  334. /**
  335. Check if specified values are equal
  336. **/
  337. public static function equal( left:Dynamic, right:Dynamic ) : Bool {
  338. if (isNumber(left) && isNumber(right)) {
  339. return Syntax.binop(left, '==', right);
  340. }
  341. return Syntax.binop(left, '===', right);
  342. }
  343. /**
  344. Concat `left` and `right` if both are strings or string and null.
  345. Otherwise return sum of `left` and `right`.
  346. **/
  347. public static function addOrConcat( left:Dynamic, right:Dynamic ) : Dynamic {
  348. if (left.is_string() || right.is_string()) {
  349. return (left:String) + (right:String);
  350. }
  351. return Syntax.binop(left, '+', right);
  352. }
  353. /**
  354. `Std.is()` implementation
  355. **/
  356. public static function is( value:Dynamic, type:HxClass ) : Bool {
  357. if (type == null) return false;
  358. var phpType = type.phpClassName;
  359. switch (phpType) {
  360. case 'Dynamic':
  361. return true;
  362. case 'Int':
  363. return (
  364. value.is_int()
  365. || (
  366. value.is_float()
  367. && Syntax.binop(Syntax.int(value), '==', value)
  368. && !Global.is_nan(value)
  369. )
  370. )
  371. && Global.abs(value) <= 2147483648;
  372. case 'Float':
  373. return value.is_float() || value.is_int();
  374. case 'Bool':
  375. return value.is_bool();
  376. case 'String':
  377. return value.is_string();
  378. case 'php\\NativeArray', 'php\\_NativeArray\\NativeArray_Impl_':
  379. return value.is_array();
  380. case 'Enum', 'Class':
  381. if (Std.is(value, HxClass)) {
  382. var valuePhpClass = (cast value:HxClass).phpClassName;
  383. var enumPhpClass = (cast HxEnum:HxClass).phpClassName;
  384. var isEnumType = Global.is_subclass_of(valuePhpClass, enumPhpClass);
  385. return (phpType == 'Enum' ? isEnumType : !isEnumType);
  386. }
  387. case _:
  388. if (value.is_object()) {
  389. var type:Class<Dynamic> = cast type;
  390. return Syntax.instanceof(value, type);
  391. }
  392. }
  393. return false;
  394. }
  395. /**
  396. Check if `value` is a `Class<T>`
  397. **/
  398. public static inline function isClass(value:Dynamic) : Bool {
  399. return Std.is(value, HxClass);
  400. }
  401. /**
  402. Check if `value` is an enum constructor instance
  403. **/
  404. public static inline function isEnumValue(value:Dynamic) : Bool {
  405. return Std.is(value, HxEnum);
  406. }
  407. /**
  408. Check if `value` is a function
  409. **/
  410. public static inline function isFunction(value:Dynamic) : Bool {
  411. return Std.is(value, Closure) || Std.is(value, HxClosure);
  412. }
  413. /**
  414. Check if `value` is an instance of `HxClosure`
  415. **/
  416. public static inline function isHxClosure(value:Dynamic) : Bool {
  417. return Std.is(value, HxClosure);
  418. }
  419. /**
  420. Performs `left >>> right` operation
  421. **/
  422. public static function shiftRightUnsigned( left:Int, right:Int ) : Int {
  423. if (right == 0) {
  424. return left;
  425. } else if (left >= 0) {
  426. return (left >> right);
  427. } else {
  428. return (left >> right) & (0x7fffffff >> (right - 1));
  429. }
  430. }
  431. /**
  432. Helper method to avoid "Cannot use temporary expression in write context" error for expressions like this:
  433. ```
  434. (new MyClass()).fieldName = 'value';
  435. ```
  436. **/
  437. static public function deref( value:Dynamic ) : Dynamic {
  438. return value;
  439. }
  440. /**
  441. Create Haxe-compatible anonymous structure of `data` associative array
  442. **/
  443. static public inline function createAnon( data:NativeArray ) : Dynamic {
  444. return new HxAnon(data);
  445. }
  446. /**
  447. Make sure specified class is loaded
  448. **/
  449. static public inline function ensureLoaded(phpClassName:String ) : Bool {
  450. return Global.class_exists(phpClassName) || Global.interface_exists(phpClassName);
  451. }
  452. /**
  453. Get `field` of a dynamic `value` in a safe manner (avoid exceptions on trying to get a method)
  454. **/
  455. static public function dynamicField( value:Dynamic, field:String ) : Dynamic {
  456. if(Global.method_exists(value, field)) {
  457. return closure(value, field);
  458. }
  459. if(Global.is_string(value)) {
  460. value = @:privateAccess new HxDynamicStr(value);
  461. }
  462. return Syntax.getField(value, field);
  463. }
  464. }
  465. /**
  466. Class<T> implementation for Haxe->PHP internals.
  467. **/
  468. @:keep
  469. @:dox(hide)
  470. private class HxClass {
  471. public var phpClassName (default,null) : String;
  472. public function new( phpClassName:String ) : Void {
  473. this.phpClassName = phpClassName;
  474. }
  475. /**
  476. Magic method to call static methods of this class, when `HxClass` instance is in a `Dynamic` variable.
  477. **/
  478. @:phpMagic
  479. function __call( method:String, args:NativeArray ) : Dynamic {
  480. var callback = (phpClassName == 'String' ? (cast HxString:HxClass).phpClassName : phpClassName) + '::' + method;
  481. return Global.call_user_func_array(callback, args);
  482. }
  483. /**
  484. Magic method to get static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  485. **/
  486. @:phpMagic
  487. function __get( property:String ) : Dynamic {
  488. if (Boot.hasGetter(phpClassName, property)) {
  489. return Syntax.staticCall(phpClassName, 'get_$property');
  490. } else {
  491. return Syntax.getStaticField(phpClassName, property);
  492. }
  493. }
  494. /**
  495. Magic method to set static vars of this class, when `HxClass` instance is in a `Dynamic` variable.
  496. **/
  497. @:phpMagic
  498. function __set( property:String, value:Dynamic ) : Void {
  499. if (Boot.hasSetter(phpClassName, property)) {
  500. Syntax.staticCall(phpClassName, 'set_$property', value);
  501. } else {
  502. Syntax.setStaticField(phpClassName, property, value);
  503. }
  504. }
  505. }
  506. /**
  507. Base class for enum types
  508. **/
  509. @:keep
  510. @:dox(hide)
  511. private class HxEnum {
  512. static var singletons = new Map<String,HxEnum>();
  513. var tag : String;
  514. var index : Int;
  515. var params : NativeArray;
  516. /**
  517. Returns instances of constructors without arguments
  518. **/
  519. public static function singleton( enumClass:String, tag:String, index:Int ) : HxEnum {
  520. var key = '$enumClass::$tag';
  521. var instance = singletons.get(key);
  522. if (instance == null) {
  523. instance = Syntax.construct(enumClass, tag, index);
  524. singletons.set(key, instance);
  525. }
  526. return instance;
  527. }
  528. public function new( tag:String, index:Int, arguments:NativeArray = null ) : Void {
  529. this.tag = tag;
  530. this.index = index;
  531. params = (arguments == null ? new NativeArray() : arguments);
  532. }
  533. /**
  534. Get string representation of this `Class`
  535. **/
  536. public function toString() : String {
  537. return __toString();
  538. }
  539. /**
  540. PHP magic method to get string representation of this `Class`
  541. **/
  542. @:phpMagic
  543. public function __toString() : String {
  544. var result = tag;
  545. if (Global.count(params) > 0) {
  546. var strings = Global.array_map(function (item) return Boot.stringify(item), params);
  547. result += '(' + Global.implode(',', strings) + ')';
  548. }
  549. return result;
  550. }
  551. }
  552. /**
  553. `String` implementation
  554. **/
  555. @:keep
  556. @:dox(hide)
  557. private class HxString {
  558. public static function toUpperCase( str:String ) : String {
  559. return Global.strtoupper(str);
  560. }
  561. public static function toLowerCase( str:String ) : String {
  562. return Global.strtolower(str);
  563. }
  564. public static function charAt( str:String, index:Int) : String {
  565. if (index < 0 || index >= str.length) {
  566. return '';
  567. } else {
  568. return (str:NativeString)[index];
  569. }
  570. }
  571. public static function charCodeAt( str:String, index:Int) : Null<Int> {
  572. if (index < 0 || index >= str.length) {
  573. return null;
  574. } else {
  575. return Global.ord((str:NativeString)[index]);
  576. }
  577. }
  578. public static function indexOf( str:String, search:String, startIndex:Int = null ) : Int {
  579. if (startIndex == null) {
  580. startIndex = 0;
  581. } else if (startIndex < 0) {
  582. startIndex += str.length;
  583. }
  584. var index = Global.strpos(str, search, startIndex);
  585. return (index == false ? -1 : index);
  586. }
  587. public static function lastIndexOf( str:String, search:String, startIndex:Int = null ) : Int {
  588. var index = Global.strrpos(str, search, (startIndex == null ? 0 : startIndex - str.length));
  589. if (index == false) {
  590. return -1;
  591. } else {
  592. return index;
  593. }
  594. }
  595. public static function split( str:String, delimiter:String ) : Array<String> {
  596. if (delimiter == '') {
  597. return @:privateAccess Array.wrap(Global.str_split(str));
  598. } else {
  599. return @:privateAccess Array.wrap(Global.explode(delimiter, str));
  600. }
  601. }
  602. public static function substr( str:String, pos:Int, ?len:Int ) : String {
  603. if (pos < -str.length) {
  604. pos = 0;
  605. } else if (pos >= str.length) {
  606. return '';
  607. }
  608. if (len == null) {
  609. return Global.substr(str, pos);
  610. } else {
  611. var result = Global.substr(str, pos, len);
  612. return (result == false ? '' : result);
  613. }
  614. }
  615. public static function substring( str:String, startIndex:Int, ?endIndex:Int ) : String {
  616. if (endIndex == null) {
  617. endIndex = str.length;
  618. } else if (endIndex < 0) {
  619. endIndex = 0;
  620. }
  621. if (startIndex < 0) startIndex = 0;
  622. if (startIndex > endIndex) {
  623. var tmp = endIndex;
  624. endIndex = startIndex;
  625. startIndex = tmp;
  626. }
  627. var result = Global.substr(str, startIndex, endIndex - startIndex);
  628. return (result == false ? '' : result);
  629. }
  630. public static function toString( str:String ) : String {
  631. return str;
  632. }
  633. public static function fromCharCode( code:Int ) : String {
  634. return Global.chr(code);
  635. }
  636. }
  637. /**
  638. For Dynamic access which looks like String
  639. **/
  640. @:dox(hide)
  641. @:keep
  642. private class HxDynamicStr {
  643. static var hxString : String = (cast HxString:HxClass).phpClassName;
  644. var str : String;
  645. /**
  646. Returns HxDynamicStr instance if `value` is a string.
  647. Otherwise returns `value` as-is.
  648. **/
  649. static function wrap( value:Dynamic ) : Dynamic {
  650. if (value.is_string()) {
  651. return new HxDynamicStr(value);
  652. } else {
  653. return value;
  654. }
  655. }
  656. function new( str:String ) {
  657. this.str = str;
  658. }
  659. @:phpMagic
  660. function __get( field:String ) : Dynamic {
  661. switch (field) {
  662. case 'length': return str.length;
  663. case 'toUpperCase': return HxString.toUpperCase.bind(str);
  664. case 'toLowerCase': return HxString.toLowerCase.bind(str);
  665. case 'charAt': return HxString.charAt.bind(str);
  666. case 'indexOf': return HxString.indexOf.bind(str);
  667. case 'lastIndexOf': return HxString.lastIndexOf.bind(str);
  668. case 'split': return HxString.split.bind(str);
  669. case 'toString': return HxString.toString.bind(str);
  670. case 'substring': return HxString.substring.bind(str);
  671. case 'substr': return HxString.substr.bind(str);
  672. case 'charCodeAt': return HxString.charCodeAt.bind(str);
  673. }
  674. /** Force invalid field access error */
  675. return Syntax.getField(str, field);
  676. }
  677. @:phpMagic
  678. function __call( method:String, args:NativeArray ) : Dynamic {
  679. Global.array_unshift(args, str);
  680. return Global.call_user_func_array(hxString + '::' + method, args);
  681. }
  682. }
  683. /**
  684. Anonymous objects implementation
  685. **/
  686. @:keep
  687. @:dox(hide)
  688. private class HxAnon extends StdClass {
  689. public function new( fields:NativeArray = null ) {
  690. super();
  691. if (fields != null) {
  692. Syntax.foreach(fields, function(name, value) Syntax.setField(this, name, value));
  693. }
  694. }
  695. @:phpMagic
  696. function __get( name:String ) {
  697. return null;
  698. }
  699. @:phpMagic
  700. function __call( name:String, args:NativeArray ) : Dynamic {
  701. var method = Syntax.getField(this, name);
  702. Syntax.keepVar(method);
  703. return method(Syntax.splat(args));
  704. }
  705. }
  706. /**
  707. Closures implementation
  708. **/
  709. @:keep
  710. @:dox(hide)
  711. private class HxClosure {
  712. /** `this` for instance methods; php class name for static methods */
  713. var target : Dynamic;
  714. /** Method name for methods */
  715. var func : String;
  716. public function new( target:Dynamic, func:String ) : Void {
  717. this.target = target;
  718. this.func = func;
  719. //Force runtime error if trying to create a closure of an instance which happen to be `null`
  720. if (target.is_null()) {
  721. throw "Unable to create closure on `null`";
  722. }
  723. }
  724. /**
  725. @see http://php.net/manual/en/language.oop5.magic.php#object.invoke
  726. **/
  727. @:phpMagic
  728. public function __invoke() {
  729. return Global.call_user_func_array(getCallback(), Global.func_get_args());
  730. }
  731. /**
  732. Generates callable value for PHP
  733. **/
  734. public function getCallback(eThis:Dynamic = null) : NativeIndexedArray<Dynamic> {
  735. if (eThis == null) {
  736. eThis = target;
  737. }
  738. if (Std.is(eThis, StdClass)) {
  739. if (Std.is(eThis, HxAnon)) {
  740. return Syntax.getField(eThis, func);
  741. }
  742. }
  743. return Syntax.arrayDecl(eThis, func);
  744. }
  745. /**
  746. Check if this is the same closure
  747. **/
  748. public function equals( closure:HxClosure ) : Bool {
  749. return (target == closure.target && func == closure.func);
  750. }
  751. /**
  752. Invoke this closure with `newThis` instead of `this`
  753. **/
  754. public function callWith( newThis:Dynamic, args:NativeArray ) : Dynamic {
  755. return Global.call_user_func_array(getCallback(newThis), args);
  756. }
  757. }
  758. /**
  759. Special exception which is used to wrap non-throwable values
  760. **/
  761. @:keep
  762. @:dox(hide)
  763. private class HxException extends Exception {
  764. var e : Dynamic;
  765. public function new( e:Dynamic ) : Void {
  766. this.e = e;
  767. super(Boot.stringify(e));
  768. }
  769. }