Update Files

This commit is contained in:
2025-01-22 16:18:30 +01:00
parent ed4603cf95
commit a36294b518
16718 changed files with 2960346 additions and 0 deletions

View File

@ -0,0 +1,35 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
Native PHP interface.
@see http://php.net/manual/en/class.arrayaccess.php
**/
@:native('ArrayAccess')
extern interface ArrayAccess<K, V> {
function offsetExists(offset:K):Bool;
function offsetGet(offset:K):V;
function offsetSet(offset:K, value:V):Void;
function offsetUnset(offset:K):Void;
}

View File

@ -0,0 +1,57 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/class.arrayiterator.php
**/
@:native('ArrayIterator')
extern class ArrayIterator<K, V> implements php.ArrayAccess<K, V> implements SeekableIterator<K, V> implements Countable implements Serializable {
@:phpClassConst static final STD_PROP_LIST:Int;
@:phpClassConst static final ARRAY_AS_PROPS:Int;
function new(?array:NativeArray, ?flags:Int);
function append(value:V):Void;
function asort():Void;
function count():Int;
function current():V;
function getArrayCopy():NativeArray;
function getFlags():Int;
function key():K;
function ksort():Void;
function natcasesort():Void;
function natsort():Void;
function next():Void;
function offsetExists(offset:K):Bool;
function offsetGet(offset:K):V;
function offsetSet(offset:K, value:V):Void;
function offsetUnset(offset:K):Void;
function rewind():Void;
function seek(position:Int):Void;
function serialize():String;
function setFlags(flags:Int):Void;
function uasort(cmp_function:(a:V, b:V) -> Int):Void;
function uksort(cmp_function:(a:K, b:K) -> Int):Void;
function unserialize(serialized:String):Void;
function valid():Bool;
}

View File

@ -0,0 +1,38 @@
/*
* Copyright (C)2005-2021 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/language.attributes.php
**/
@:native("Attribute")
extern final class Attribute {
@:phpClassConst static final IS_REPEATABLE: Int;
@:phpClassConst static final TARGET_ALL: Int;
@:phpClassConst static final TARGET_CLASS_CONSTANT: Int;
@:phpClassConst static final TARGET_CLASS: Int;
@:phpClassConst static final TARGET_FUNCTION: Int;
@:phpClassConst static final TARGET_METHOD: Int;
@:phpClassConst static final TARGET_PARAMETER: Int;
@:phpClassConst static final TARGET_PROPERTY: Int;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,34 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.Rest;
/**
@see http://php.net/manual/en/class.closure.php
**/
@:native('Closure')
extern class Closure {
function bindTo(newthis:{}, newscope:Dynamic = "static"):Closure;
function call(newthis:{}, args:Rest<Dynamic>):Dynamic;
}

View File

@ -0,0 +1,71 @@
/*
* Copyright (C)2005-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.collator.php
**/
@:native("Collator")
extern class Collator {
@:phpClassConst static final ALTERNATE_HANDLING: Int;
@:phpClassConst static final CASE_FIRST: Int;
@:phpClassConst static final CASE_LEVEL: Int;
@:phpClassConst static final DEFAULT_STRENGTH: Int;
@:phpClassConst static final DEFAULT_VALUE: Int;
@:phpClassConst static final FRENCH_COLLATION: Int;
@:phpClassConst static final HIRAGANA_QUATERNARY_MODE: Int;
@:phpClassConst static final IDENTICAL: Int;
@:phpClassConst static final LOWER_FIRST: Int;
@:phpClassConst static final NON_IGNORABLE: Int;
@:phpClassConst static final NORMALIZATION_MODE: Int;
@:phpClassConst static final NUMERIC_COLLATION: Int;
@:phpClassConst static final OFF: Int;
@:phpClassConst static final ON: Int;
@:phpClassConst static final PRIMARY: Int;
@:phpClassConst static final QUATERNARY: Int;
@:phpClassConst static final SECONDARY: Int;
@:phpClassConst static final SHIFTED: Int;
@:phpClassConst static final SORT_NUMERIC: Int;
@:phpClassConst static final SORT_REGULAR: Int;
@:phpClassConst static final SORT_STRING: Int;
@:phpClassConst static final STRENGTH: Int;
@:phpClassConst static final TERTIARY: Int;
@:phpClassConst static final UPPER_FIRST: Int;
function new(locale: String);
function asort(arr: Ref<NativeAssocArray<String>>, ?sort_flag: Int): Bool;
function compare(str1: String, str2: String): EitherType<Int, Bool>;
static function create(locale: String): Null<Collator>;
function getAttribute(attr: Int): EitherType<Int, Bool>;
function getErrorCode(): Int;
function getErrorMessage(): String;
function getLocale(type: Int): EitherType<String, Bool>;
function getSortKey(str: String): EitherType<String, Bool>;
function getStrength(): EitherType<Int, Bool>;
function setAttribute(attr: Int, val: Int): Bool;
function setStrength(strength: Int): Bool;
function sort(arr: Ref<NativeArray>, ?sort_flag: Int): Bool;
function sortWithSortKeys(arr: Ref<NativeArray>): Bool;
}

View File

@ -0,0 +1,622 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
This class contains externs for native PHP constants defined in global namespace.
For native PHP functions in global namespace see `php.Global`.
**/
@:phpGlobal
extern class Const {
/**
If this constant is defined and equals `true` then Haxe will not set error handler automatically.
**/
static final HAXE_CUSTOM_ERROR_HANDLER:Bool;
/**
@see http://php.net/manual/en/reserved.constants.php
**/
static final PHP_VERSION_ID:Int;
static final PHP_OS:String;
static final PHP_SAPI:String;
static final PHP_BINARY:String;
static final PHP_EOL:String;
static final PHP_INT_MAX:Int;
static final PHP_INT_MIN:Int;
static final PHP_INT_SIZE:Int;
/**
@see http://php.net/manual/en/language.constants.predefined.php
**/
static final __LINE__:Int;
static final __FILE__:String;
static final __DIR__:String;
static final __FUNCTION__:String;
static final __CLASS__:String;
static final __TRAIT__:String;
static final __METHOD__:String;
static final __NAMESPACE__:String;
/**
@see https://php.net/manual/en/dir.constants.php
**/
static final DIRECTORY_SEPARATOR:String;
static final PATH_SEPARATOR:String;
static final SCANDIR_SORT_ASCENDING:Int;
static final SCANDIR_SORT_DESCENDING:Int;
static final SCANDIR_SORT_NONE:Int;
/**
@see http://php.net/manual/en/errorfunc.constants.php
**/
static final E_ERROR:Int;
static final E_WARNING:Int;
static final E_PARSE:Int;
static final E_NOTICE:Int;
static final E_CORE_ERROR:Int;
static final E_CORE_WARNING:Int;
static final E_COMPILE_ERROR:Int;
static final E_COMPILE_WARNING:Int;
static final E_USER_ERROR:Int;
static final E_USER_WARNING:Int;
static final E_USER_NOTICE:Int;
static final E_STRICT:Int;
static final E_RECOVERABLE_ERROR:Int;
static final E_DEPRECATED:Int;
static final E_USER_DEPRECATED:Int;
static final E_ALL:Int;
/**
@see http://php.net/manual/en/function.count.php
**/
static final COUNT_NORMAL:Int;
static final COUNT_RECURSIVE:Int;
/**
@see http://php.net/manual/en/function.array-filter.php
**/
static final ARRAY_FILTER_USE_KEY:Int;
static final ARRAY_FILTER_USE_BOTH:Int;
/**
@see http://php.net/manual/en/function.debug-backtrace.php
**/
static final DEBUG_BACKTRACE_PROVIDE_OBJECT:Int;
static final DEBUG_BACKTRACE_IGNORE_ARGS:Int;
/**
@see http://php.net/manual/en/math.constants.php
**/
static final M_PI:Float;
static final M_E:Float;
static final M_LOG2E:Float;
static final M_LOG10E:Float;
static final M_LN2:Float;
static final M_LN10:Float;
static final M_PI_2:Float;
static final M_PI_4:Float;
static final M_1_PI:Float;
static final M_2_PI:Float;
static final M_SQRTPI:Float;
static final M_2_SQRTPI:Float;
static final M_SQRT2:Float;
static final M_SQRT3:Float;
static final M_SQRT1_2:Float;
static final M_LNPI:Float;
static final M_EULER:Float;
static final PHP_ROUND_HALF_UP:Int;
static final PHP_ROUND_HALF_DOWN:Int;
static final PHP_ROUND_HALF_EVEN:Int;
static final PHP_ROUND_HALF_ODD:Int;
static final NAN:Float;
static final INF:Float;
/**
@see http://php.net/manual/en/function.setlocale.php
**/
static final LC_ALL:Int;
static final LC_COLLATE:Int;
static final LC_CTYPE:Int;
static final LC_MONETARY:Int;
static final LC_NUMERIC:Int;
static final LC_TIME:Int;
static final LC_MESSAGES:Int;
/**
@see http://php.net/manual/en/features.commandline.io-streams.php
**/
static final STDIN:Resource;
static final STDOUT:Resource;
static final STDERR:Resource;
/**
@see http://php.net/manual/en/function.preg-match-all.php
**/
static final PREG_PATTERN_ORDER:Int;
static final PREG_SET_ORDER:Int;
static final PREG_OFFSET_CAPTURE:Int;
/**
@see http://php.net/manual/en/function.preg-split.php
**/
static final PREG_SPLIT_NO_EMPTY:Int;
static final PREG_SPLIT_DELIM_CAPTURE:Int;
static final PREG_SPLIT_OFFSET_CAPTURE:Int;
/**
@see http://php.net/manual/en/function.preg-last-error.php
**/
static final PREG_NO_ERROR:Int;
static final PREG_INTERNAL_ERROR:Int;
static final PREG_BACKTRACK_LIMIT_ERROR:Int;
static final PREG_RECURSION_LIMIT_ERROR:Int;
static final PREG_BAD_UTF8_ERROR:Int;
static final PREG_BAD_UTF8_OFFSET_ERROR:Int;
static final PREG_JIT_STACKLIMIT_ERROR:Int;
/**
@see http://php.net/manual/en/function.htmlspecialchars.php
**/
static final ENT_COMPAT:Int;
static final ENT_QUOTES:Int;
static final ENT_NOQUOTES:Int;
static final ENT_IGNORE:Int;
static final ENT_SUBSTITUTE:Int;
static final ENT_DISALLOWED:Int;
static final ENT_HTML401:Int;
static final ENT_XML1:Int;
static final ENT_XHTML:Int;
static final ENT_HTML5:Int;
/**
@see http://php.net/manual/en/function.str-pad.php
**/
static final STR_PAD_RIGHT:Int;
static final STR_PAD_LEFT:Int;
static final STR_PAD_BOTH:Int;
/**
@see http://php.net/manual/en/function.feof.php
**/
static final SEEK_SET:Int;
static final SEEK_CUR:Int;
static final SEEK_END:Int;
/**
@see http://php.net/manual/en/function.stream-socket-server.php
**/
static final STREAM_SERVER_BIND:Int;
static final STREAM_SERVER_LISTEN:Int;
/**
@see http://php.net/manual/en/function.stream-socket-client.php
**/
static final STREAM_CLIENT_CONNECT:Int;
static final STREAM_CLIENT_ASYNC_CONNECT:Int;
static final STREAM_CLIENT_PERSISTENT:Int;
/**
@see http://php.net/manual/en/sockets.constants.php
**/
static final SOCK_STREAM:Int;
static final SOCK_DGRAM:Int;
static final SOCK_SEQPACKET:Int;
static final SOCK_RAW:Int;
static final SOCK_RDM:Int;
static final AF_INET:Int;
static final AF_INET6:Int;
static final AF_UNIX:Int;
static final SOL_TCP:Int;
static final SOL_SOCKET:Int;
static final SO_RCVTIMEO:Int;
static final SO_SNDTIMEO:Int;
static final TCP_NODELAY:Int;
static final PHP_BINARY_READ:Int;
/**
@see http://php.net/manual/en/function.session-status.php
**/
static final PHP_SESSION_DISABLED:Int;
static final PHP_SESSION_NONE:Int;
static final PHP_SESSION_ACTIVE:Int;
/**
@see http://php.net/manual/en/json.constants.php
**/
static final JSON_ERROR_NONE:Int;
static final JSON_ERROR_DEPTH:Int;
static final JSON_ERROR_STATE_MISMATCH:Int;
static final JSON_ERROR_CTRL_CHAR:Int;
static final JSON_ERROR_SYNTAX:Int;
static final JSON_ERROR_UTF8:Int;
static final JSON_ERROR_RECURSION:Int;
static final JSON_ERROR_INF_OR_NAN:Int;
static final JSON_ERROR_UNSUPPORTED_TYPE:Int;
static final JSON_HEX_TAG:Int;
static final JSON_HEX_AMP:Int;
static final JSON_HEX_APOS:Int;
static final JSON_HEX_QUOT:Int;
static final JSON_FORCE_OBJECT:Int;
static final JSON_NUMERIC_CHECK:Int;
static final JSON_BIGINT_AS_STRING:Int;
static final JSON_PRETTY_PRINT:Int;
static final JSON_UNESCAPED_SLASHES:Int;
static final JSON_UNESCAPED_UNICODE:Int;
static final JSON_PARTIAL_OUTPUT_ON_ERROR:Int;
static final JSON_PRESERVE_ZERO_FRACTION:Int;
/**
@see http://php.net/manual/en/mysqli.constants.php
**/
static final MYSQLI_READ_DEFAULT_GROUP:Int;
static final MYSQLI_READ_DEFAULT_FILE:Int;
static final MYSQLI_OPT_CONNECT_TIMEOUT:Int;
static final MYSQLI_OPT_LOCAL_INFILE:Int;
static final MYSQLI_INIT_COMMAND:Int;
static final MYSQLI_CLIENT_SSL:Int;
static final MYSQLI_CLIENT_COMPRESS:Int;
static final MYSQLI_CLIENT_INTERACTIVE:Int;
static final MYSQLI_CLIENT_IGNORE_SPACE:Int;
static final MYSQLI_CLIENT_NO_SCHEMA:Int;
static final MYSQLI_CLIENT_MULTI_QUERIES:Int;
static final MYSQLI_STORE_RESULT:Int;
static final MYSQLI_USE_RESULT:Int;
static final MYSQLI_ASSOC:Int;
static final MYSQLI_NUM:Int;
static final MYSQLI_BOTH:Int;
static final MYSQLI_NOT_NULL_FLAG:Int;
static final MYSQLI_PRI_KEY_FLAG:Int;
static final MYSQLI_UNIQUE_KEY_FLAG:Int;
static final MYSQLI_MULTIPLE_KEY_FLAG:Int;
static final MYSQLI_BLOB_FLAG:Int;
static final MYSQLI_UNSIGNED_FLAG:Int;
static final MYSQLI_ZEROFILL_FLAG:Int;
static final MYSQLI_AUTO_INCREMENT_FLAG:Int;
static final MYSQLI_TIMESTAMP_FLAG:Int;
static final MYSQLI_SET_FLAG:Int;
static final MYSQLI_NUM_FLAG:Int;
static final MYSQLI_PART_KEY_FLAG:Int;
static final MYSQLI_GROUP_FLAG:Int;
static final MYSQLI_TYPE_DECIMAL:Int;
static final MYSQLI_TYPE_NEWDECIMAL:Int;
static final MYSQLI_TYPE_BIT:Int;
static final MYSQLI_TYPE_TINY:Int;
static final MYSQLI_TYPE_SHORT:Int;
static final MYSQLI_TYPE_LONG:Int;
static final MYSQLI_TYPE_FLOAT:Int;
static final MYSQLI_TYPE_DOUBLE:Int;
static final MYSQLI_TYPE_NULL:Int;
static final MYSQLI_TYPE_TIMESTAMP:Int;
static final MYSQLI_TYPE_LONGLONG:Int;
static final MYSQLI_TYPE_INT24:Int;
static final MYSQLI_TYPE_DATE:Int;
static final MYSQLI_TYPE_TIME:Int;
static final MYSQLI_TYPE_DATETIME:Int;
static final MYSQLI_TYPE_YEAR:Int;
static final MYSQLI_TYPE_NEWDATE:Int;
static final MYSQLI_TYPE_INTERVAL:Int;
static final MYSQLI_TYPE_ENUM:Int;
static final MYSQLI_TYPE_SET:Int;
static final MYSQLI_TYPE_TINY_BLOB:Int;
static final MYSQLI_TYPE_MEDIUM_BLOB:Int;
static final MYSQLI_TYPE_LONG_BLOB:Int;
static final MYSQLI_TYPE_BLOB:Int;
static final MYSQLI_TYPE_VAR_STRING:Int;
static final MYSQLI_TYPE_STRING:Int;
static final MYSQLI_TYPE_CHAR:Int;
static final MYSQLI_TYPE_GEOMETRY:Int;
static final MYSQLI_NEED_DATA:Int;
static final MYSQLI_NO_DATA:Int;
static final MYSQLI_DATA_TRUNCATED:Int;
static final MYSQLI_ENUM_FLAG:Int;
static final MYSQLI_BINARY_FLAG:Int;
static final MYSQLI_CURSOR_TYPE_FOR_UPDATE:Int;
static final MYSQLI_CURSOR_TYPE_NO_CURSOR:Int;
static final MYSQLI_CURSOR_TYPE_READ_ONLY:Int;
static final MYSQLI_CURSOR_TYPE_SCROLLABLE:Int;
static final MYSQLI_STMT_ATTR_CURSOR_TYPE:Int;
static final MYSQLI_STMT_ATTR_PREFETCH_ROWS:Int;
static final MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH:Int;
static final MYSQLI_SET_CHARSET_NAME:Int;
static final MYSQLI_REPORT_INDEX:Int;
static final MYSQLI_REPORT_ERROR:Int;
static final MYSQLI_REPORT_STRICT:Int;
static final MYSQLI_REPORT_ALL:Int;
static final MYSQLI_REPORT_OFF:Int;
static final MYSQLI_DEBUG_TRACE_ENABLED:Int;
static final MYSQLI_SERVER_QUERY_NO_GOOD_INDEX_USED:Int;
static final MYSQLI_SERVER_QUERY_NO_INDEX_USED:Int;
static final MYSQLI_REFRESH_GRANT:Int;
static final MYSQLI_REFRESH_LOG:Int;
static final MYSQLI_REFRESH_TABLES:Int;
static final MYSQLI_REFRESH_HOSTS:Int;
static final MYSQLI_REFRESH_STATUS:Int;
static final MYSQLI_REFRESH_THREADS:Int;
static final MYSQLI_REFRESH_SLAVE:Int;
static final MYSQLI_REFRESH_MASTER:Int;
static final MYSQLI_TRANS_COR_AND_CHAIN:Int;
static final MYSQLI_TRANS_COR_AND_NO_CHAIN:Int;
static final MYSQLI_TRANS_COR_RELEASE:Int;
static final MYSQLI_TRANS_COR_NO_RELEASE:Int;
static final MYSQLI_TRANS_START_READ_ONLY:Int;
static final MYSQLI_TRANS_START_READ_WRITE:Int;
static final MYSQLI_TRANS_START_CONSISTENT_SNAPSHOT:Int;
/**
@see http://php.net/manual/en/sqlite3.constants.php
**/
static final SQLITE3_ASSOC:Int;
static final SQLITE3_NUM:Int;
static final SQLITE3_BOTH:Int;
static final SQLITE3_INTEGER:Int;
static final SQLITE3_FLOAT:Int;
static final SQLITE3_TEXT:Int;
static final SQLITE3_BLOB:Int;
static final SQLITE3_NULL:Int;
static final SQLITE3_OPEN_READONLY:Int;
static final SQLITE3_OPEN_READWRITE:Int;
static final SQLITE3_OPEN_CREATE:Int;
/**
@see http://php.net/manual/en/function.glob.php
**/
static final GLOB_MARK:Int;
static final GLOB_NOSORT:Int;
static final GLOB_NOCHECK:Int;
static final GLOB_NOESCAPE:Int;
static final GLOB_BRACE:Int;
static final GLOB_ONLYDIR:Int;
static final GLOB_ERR:Int;
/**
@see http://php.net/manual/en/zlib.constants.php
**/
static final FORCE_GZIP:Int;
static final FORCE_DEFLATE:Int;
static final ZLIB_ENCODING_RAW:Int;
static final ZLIB_ENCODING_DEFLATE:Int;
static final ZLIB_ENCODING_GZIP:Int;
static final ZLIB_FILTERED:Int;
static final ZLIB_HUFFMAN_ONLY:Int;
static final ZLIB_FIXED:Int;
static final ZLIB_RLE:Int;
static final ZLIB_DEFAULT_STRATEGY:Int;
static final ZLIB_BLOCK:Int;
static final ZLIB_NO_FLUSH:Int;
static final ZLIB_PARTIAL_FLUSH:Int;
static final ZLIB_SYNC_FLUSH:Int;
static final ZLIB_FULL_FLUSH:Int;
static final ZLIB_FINISH:Int;
/**
@see http://php.net/manual/en/outcontrol.constants.php
**/
static final PHP_OUTPUT_HANDLER_CLEAN:Int;
static final PHP_OUTPUT_HANDLER_CLEANABLE:Int;
static final PHP_OUTPUT_HANDLER_CONT:Int;
static final PHP_OUTPUT_HANDLER_END:Int;
static final PHP_OUTPUT_HANDLER_FINAL:Int;
static final PHP_OUTPUT_HANDLER_FLUSH:Int;
static final PHP_OUTPUT_HANDLER_FLUSHABLE:Int;
static final PHP_OUTPUT_HANDLER_REMOVABLE:Int;
static final PHP_OUTPUT_HANDLER_START:Int;
static final PHP_OUTPUT_HANDLER_STDFLAGS:Int;
static final PHP_OUTPUT_HANDLER_WRITE:Int;
/**
@see http://php.net/manual/en/function.flock.php
**/
static final LOCK_EX:Int;
static final LOCK_NB:Int;
static final LOCK_SH:Int;
static final LOCK_UN:Int;
/**
@see http://php.net/manual/en/function.fnmatch.php
**/
static final FNM_CASEFOLD:Int;
static final FNM_NOESCAPE:Int;
static final FNM_PATHNAME:Int;
static final FNM_PERIOD:Int;
/**
@see http://php.net/manual/en/function.parse-ini-file.php
**/
static final INI_SCANNER_NORMAL:Int;
static final INI_SCANNER_RAW:Int;
static final INI_SCANNER_TYPED:Int;
/**
@see http://php.net/manual/en/function.pathinfo.php
**/
static final PATHINFO_BASENAME:Int;
static final PATHINFO_DIRNAME:Int;
static final PATHINFO_EXTENSION:Int;
static final PATHINFO_FILENAME:Int;
/**
@see http://php.net/manual/en/function.dns-get-record.php
**/
static final DNS_A:Int;
static final DNS_AAAA:Int;
static final DNS_ALL:Int;
static final DNS_ANY:Int;
static final DNS_CAA:Int;
static final DNS_CNAME:Int;
static final DNS_HINFO:Int;
static final DNS_MX:Int;
static final DNS_NS:Int;
static final DNS_PTR:Int;
static final DNS_SOA:Int;
static final DNS_TXT:Int;
/**
@see http://php.net/manual/en/intl.constants.php
**/
static final IDNA_ALLOW_UNASSIGNED:Int;
static final IDNA_CHECK_BIDI:Int;
static final IDNA_CHECK_CONTEXTJ:Int;
static final IDNA_DEFAULT:Int;
static final IDNA_ERROR_BIDI:Int;
static final IDNA_ERROR_CONTEXTJ:Int;
static final IDNA_ERROR_DISALLOWED:Int;
static final IDNA_ERROR_DOMAIN_NAME_TOO_LONG:Int;
static final IDNA_ERROR_EMPTY_LABEL:Int;
static final IDNA_ERROR_HYPHEN_3_4:Int;
static final IDNA_ERROR_INVALID_ACE_LABEL:Int;
static final IDNA_ERROR_LABEL_HAS_DOT:Int;
static final IDNA_ERROR_LABEL_TOO_LONG:Int;
static final IDNA_ERROR_LEADING_COMBINING_MARK:Int;
static final IDNA_ERROR_LEADING_HYPHEN:Int;
static final IDNA_ERROR_PUNYCODE:Int;
static final IDNA_ERROR_TRAILING_HYPHEN:Int;
static final IDNA_NONTRANSITIONAL_TO_ASCII:Int;
static final IDNA_NONTRANSITIONAL_TO_UNICODE:Int;
static final IDNA_USE_STD3_RULES:Int;
static final INTL_ICU_VERSION:String;
static final INTL_IDNA_VARIANT_2003:Int;
static final INTL_IDNA_VARIANT_UTS46:Int;
static final INTL_MAX_LOCALE_LEN:Int;
/**
@see http://php.net/manual/en/array.constants.php
**/
static final CASE_LOWER:Int;
static final CASE_UPPER:Int;
static final EXTR_IF_EXISTS:Int;
static final EXTR_OVERWRITE:Int;
static final EXTR_PREFIX_ALL:Int;
static final EXTR_PREFIX_IF_EXISTS:Int;
static final EXTR_PREFIX_INVALID:Int;
static final EXTR_PREFIX_SAME:Int;
static final EXTR_REFS:Int;
static final EXTR_SKIP:Int;
static final SORT_ASC:Int;
static final SORT_DESC:Int;
static final SORT_FLAG_CASE:Int;
static final SORT_LOCALE_STRING:Int;
static final SORT_NATURAL:Int;
static final SORT_NUMERIC:Int;
static final SORT_REGULAR:Int;
static final SORT_STRING:Int;
/**
@see http://php.net/manual/en/filter.constants.php
**/
static final FILTER_CALLBACK:Int;
static final FILTER_DEFAULT:Int;
static final FILTER_FLAG_ALLOW_FRACTION:Int;
static final FILTER_FLAG_ALLOW_HEX:Int;
static final FILTER_FLAG_ALLOW_OCTAL:Int;
static final FILTER_FLAG_ALLOW_SCIENTIFIC:Int;
static final FILTER_FLAG_ALLOW_THOUSAND:Int;
static final FILTER_FLAG_EMAIL_UNICODE:Int;
static final FILTER_FLAG_EMPTY_STRING_NULL:Int;
static final FILTER_FLAG_ENCODE_AMP:Int;
static final FILTER_FLAG_ENCODE_HIGH:Int;
static final FILTER_FLAG_ENCODE_LOW:Int;
static final FILTER_FLAG_HOST_REQUIRED:Int;
static final FILTER_FLAG_HOSTNAME:Int;
static final FILTER_FLAG_IPV4:Int;
static final FILTER_FLAG_IPV6:Int;
static final FILTER_FLAG_NO_ENCODE_QUOTES:Int;
static final FILTER_FLAG_NO_PRIV_RANGE:Int;
static final FILTER_FLAG_NO_RES_RANGE:Int;
static final FILTER_FLAG_NONE:Int;
static final FILTER_FLAG_PATH_REQUIRED:Int;
static final FILTER_FLAG_QUERY_REQUIRED:Int;
static final FILTER_FLAG_SCHEME_REQUIRED:Int;
static final FILTER_FLAG_STRIP_BACKTICK:Int;
static final FILTER_FLAG_STRIP_HIGH:Int;
static final FILTER_FLAG_STRIP_LOW:Int;
static final FILTER_FORCE_ARRAY:Int;
static final FILTER_NULL_ON_FAILURE:Int;
static final FILTER_REQUIRE_ARRAY:Int;
static final FILTER_REQUIRE_SCALAR:Int;
static final FILTER_SANITIZE_ADD_SLASHES:Int;
static final FILTER_SANITIZE_EMAIL:Int;
static final FILTER_SANITIZE_ENCODED:Int;
static final FILTER_SANITIZE_MAGIC_QUOTES:Int;
static final FILTER_SANITIZE_NUMBER_FLOAT:Int;
static final FILTER_SANITIZE_NUMBER_INT:Int;
static final FILTER_SANITIZE_SPECIAL_CHARS:Int;
static final FILTER_SANITIZE_STRING:Int;
static final FILTER_SANITIZE_STRIPPED:Int;
static final FILTER_SANITIZE_URL:Int;
static final FILTER_UNSAFE_RAW:Int;
static final FILTER_VALIDATE_BOOLEAN:Int;
static final FILTER_VALIDATE_DOMAIN:Int;
static final FILTER_VALIDATE_EMAIL:Int;
static final FILTER_VALIDATE_FLOAT:Int;
static final FILTER_VALIDATE_INT:Int;
static final FILTER_VALIDATE_IP:Int;
static final FILTER_VALIDATE_MAC:Int;
static final FILTER_VALIDATE_REGEXP:Int;
static final FILTER_VALIDATE_URL:Int;
static final INPUT_COOKIE:Int;
static final INPUT_ENV:Int;
static final INPUT_GET:Int;
static final INPUT_POST:Int;
static final INPUT_REQUEST:Int;
static final INPUT_SERVER:Int;
static final INPUT_SESSION:Int;
/**
@see http://php.net/manual/en/fileinfo.constants.php
**/
static final FILEINFO_COMPRESS: Int;
static final FILEINFO_CONTINUE: Int;
static final FILEINFO_DEVICES: Int;
static final FILEINFO_EXTENSION: Int;
static final FILEINFO_MIME: Int;
static final FILEINFO_MIME_ENCODING: Int;
static final FILEINFO_MIME_TYPE: Int;
static final FILEINFO_NONE: Int;
static final FILEINFO_PRESERVE_ATIME: Int;
static final FILEINFO_RAW: Int;
static final FILEINFO_SYMLINK: Int;
}

View File

@ -0,0 +1,31 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/class.countable.php
**/
@:native('Countable')
extern interface Countable {
function count():Int;
}

View File

@ -0,0 +1,45 @@
/*
* Copyright (C)2005-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.dateinterval.php
**/
@:native("DateInterval")
extern class DateInterval {
var y: Int;
var m: Int;
var d: Int;
var h: Int;
var i: Int;
var s: Int;
var f: Float;
var invert: Int;
var days: EitherType<Int, Bool>;
function new(duration: String);
static function createFromDateString(datetime: String): DateInterval;
function format(format: String): String;
}

View File

@ -0,0 +1,47 @@
/*
* Copyright (C)2005-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/class.dateperiod.php
**/
@:native("DatePeriod")
extern class DatePeriod {
@:phpClassConst static final EXCLUDE_START_DATE: Int;
var recurrences: Int;
var include_start_date: Bool;
var start: DateTimeInterface;
var current: DateTimeInterface;
var end: Null<DateTimeInterface>;
var interval: DateInterval;
@:overload(function(start: DateTimeInterface, interval: DateInterval, recurrences: Int, ?options: Int): Void {})
@:overload(function(start: DateTimeInterface, interval: DateInterval, end: DateTimeInterface, ?options: Int): Void {})
function new(isostr: String, ?options: Int);
function getDateInterval(): DateInterval;
function getEndDate(): Null<DateTimeInterface>;
function getRecurrences(): Int;
function getStartDate(): DateTimeInterface;
}

View File

@ -0,0 +1,65 @@
/*
* Copyright (C)2005-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.datetime.php
**/
@:native("DateTime")
extern class DateTime implements DateTimeInterface {
@:phpClassConst static final ATOM: Int;
@:phpClassConst static final COOKIE: Int;
@:phpClassConst static final ISO8601: Int;
@:phpClassConst static final RFC822: Int;
@:phpClassConst static final RFC850: Int;
@:phpClassConst static final RFC1036: Int;
@:phpClassConst static final RFC1123: Int;
@:phpClassConst static final RFC7231: Int;
@:phpClassConst static final RFC2822: Int;
@:phpClassConst static final RFC3339: Int;
@:phpClassConst static final RFC3339_EXTENDED: Int;
@:phpClassConst static final RSS: Int;
@:phpClassConst static final W3C: Int;
function new(datetime: String = "now", ?timezone: DateTimeZone);
function add(interval: DateInterval): EitherType<DateTime, Bool>;
static function createFromFormat(format : String, datetime: String, ?timezone: DateTimeZone): EitherType<DateTime, Bool>;
static function createFromImmutable(object: DateTimeImmutable): DateTime;
static function getLastErrors(): NativeAssocArray<Dynamic>;
function diff(targetObject: DateTimeInterface, absolute: Bool = false): EitherType<DateInterval, Bool>;
function format(format: String): EitherType<String, Bool>;
function getOffset(): EitherType<Int, Bool>;
function getTimestamp(): Int;
function getTimezone(): EitherType<DateTimeZone, Bool>;
function modify(modifier: String): EitherType<DateTime, Bool>;
function setDate(year: Int, month: Int, day: Int): EitherType<DateTime, Bool>;
function setISODate(year: Int, week: Int, dayOfWeek: Int = 1): EitherType<DateTime, Bool>;
function setTime(hour: Int, minute: Int, second: Int = 0, microsecond: Int = 0): EitherType<DateTime, Bool>;
function setTimestamp(timestamp: Int): EitherType<DateTime, Bool>;
function setTimezone(timezone: DateTimeZone): EitherType<DateTime, Bool>;
function sub(interval: DateInterval): EitherType<DateTime, Bool>;
@:phpMagic static function __set_state(array: NativeAssocArray<Any>): DateTime;
@:phpMagic function __wakeup(): Void;
}

View File

@ -0,0 +1,65 @@
/*
* Copyright (C)2005-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.datetimeimmutable.php
**/
@:native("DateTimeImmutable")
extern class DateTimeImmutable implements DateTimeInterface {
@:phpClassConst static final ATOM: Int;
@:phpClassConst static final COOKIE: Int;
@:phpClassConst static final ISO8601: Int;
@:phpClassConst static final RFC822: Int;
@:phpClassConst static final RFC850: Int;
@:phpClassConst static final RFC1036: Int;
@:phpClassConst static final RFC1123: Int;
@:phpClassConst static final RFC7231: Int;
@:phpClassConst static final RFC2822: Int;
@:phpClassConst static final RFC3339: Int;
@:phpClassConst static final RFC3339_EXTENDED: Int;
@:phpClassConst static final RSS: Int;
@:phpClassConst static final W3C: Int;
function new(datetime: String = "now", ?timezone: DateTimeZone);
function add(interval: DateInterval): EitherType<DateTimeImmutable, Bool>;
static function createFromFormat(format : String, datetime: String, ?timezone: DateTimeZone): EitherType<DateTimeImmutable, Bool>;
static function createFromMutable(object: DateTime): DateTimeImmutable;
static function getLastErrors(): NativeAssocArray<Dynamic>;
function diff(targetObject: DateTimeInterface, absolute: Bool = false): EitherType<DateInterval, Bool>;
function format(format: String): EitherType<String, Bool>;
function getOffset(): EitherType<Int, Bool>;
function getTimestamp(): Int;
function getTimezone(): EitherType<DateTimeZone, Bool>;
function modify(modifier: String): EitherType<DateTimeImmutable, Bool>;
function setDate(year: Int, month: Int, day: Int): EitherType<DateTimeImmutable, Bool>;
function setISODate(year: Int, week: Int, dayOfWeek: Int = 1): EitherType<DateTimeImmutable, Bool>;
function setTime(hour: Int, minute: Int, second: Int = 0, microsecond: Int = 0): EitherType<DateTimeImmutable, Bool>;
function setTimestamp(timestamp: Int): EitherType<DateTimeImmutable, Bool>;
function setTimezone(timezone: DateTimeZone): EitherType<DateTimeImmutable, Bool>;
function sub(interval: DateInterval): EitherType<DateTimeImmutable, Bool>;
@:phpMagic static function __set_state(array: NativeAssocArray<Any>): DateTimeImmutable;
@:phpMagic function __wakeup(): Void;
}

View File

@ -0,0 +1,52 @@
/*
* Copyright (C)2005-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.datetimeinterface.php
**/
@:native("DateTimeInterface")
extern interface DateTimeInterface {
@:phpClassConst static final ATOM: Int;
@:phpClassConst static final COOKIE: Int;
@:phpClassConst static final ISO8601: Int;
@:phpClassConst static final RFC822: Int;
@:phpClassConst static final RFC850: Int;
@:phpClassConst static final RFC1036: Int;
@:phpClassConst static final RFC1123: Int;
@:phpClassConst static final RFC7231: Int;
@:phpClassConst static final RFC2822: Int;
@:phpClassConst static final RFC3339: Int;
@:phpClassConst static final RFC3339_EXTENDED: Int;
@:phpClassConst static final RSS: Int;
@:phpClassConst static final W3C: Int;
function diff(targetObject: DateTimeInterface, absolute: Bool = false): EitherType<DateInterval, Bool>;
function format(format: String): EitherType<String, Bool>;
function getOffset(): EitherType<Int, Bool>;
function getTimestamp(): Int;
function getTimezone(): EitherType<DateTimeZone, Bool>;
@:phpMagic function __wakeup(): Void;
}

View File

@ -0,0 +1,54 @@
/*
* Copyright (C)2005-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.datetimezone.php
**/
@:native("DateTimeZone")
extern class DateTimeZone {
@:phpClassConst static final AFRICA: Int;
@:phpClassConst static final AMERICA: Int;
@:phpClassConst static final ANTARCTICA: Int;
@:phpClassConst static final ARCTIC: Int;
@:phpClassConst static final ASIA: Int;
@:phpClassConst static final ATLANTIC: Int;
@:phpClassConst static final AUSTRALIA: Int;
@:phpClassConst static final EUROPE: Int;
@:phpClassConst static final INDIAN: Int;
@:phpClassConst static final PACIFIC: Int;
@:phpClassConst static final UTC: Int;
@:phpClassConst static final ALL: Int;
@:phpClassConst static final ALL_WITH_BC: Int;
@:phpClassConst static final PER_COUNTRY: Int;
function new(timezone: String);
function getLocation(): EitherType<NativeAssocArray<Dynamic>, Bool>;
function getName(): String;
function getOffset(datetime: DateTimeInterface): EitherType<Int, Bool>;
function getTransitions(?timestampBegin: Int, ?timestampEnd: Int): EitherType<NativeIndexedArray<NativeAssocArray<Dynamic>>, Bool>;
static function listAbbreviations(): EitherType<NativeAssocArray<NativeIndexedArray<NativeAssocArray<Dynamic>>>, Bool>;
static function listIdentifiers(?timezoneGroup: Int, ?countryCode: String): EitherType<NativeIndexedArray<String>, Bool>;
}

View File

@ -0,0 +1,42 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
@:native('Error')
extern class Error implements Throwable {
function new(?message:String, ?code:Int, ?previous:Throwable):Void;
private var message:String;
private var code:Int;
private var file:String;
private var line:Int;
final function getPrevious():Throwable; // Returns previous Throwable
function getMessage():String; // message of the exception
function getCode():Int; // code of the exception
function getFile():String; // source filename
function getLine():Int; // source line
function getTrace():NativeIndexedArray<NativeAssocArray<Dynamic>>; // an array of the backtrace
function getTraceAsString():String; // formatted string of trace
@:phpMagic function __toString():String; // formatted string for display
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see http://php.net/manual/en/class.errorexception.php
**/
@:native('ErrorException')
extern class ErrorException implements Throwable {
function new(?message:String, ?code:Int, ?severety:Int, ?filename:String, ?lineno:Int, ?previous:Throwable):Void;
final function getSeverity():Int;
final function getPrevious():Throwable; // Returns previous Throwable
final function getMessage():String; // message of the exception
final function getCode():Int; // code of the exception
final function getFile():String; // source filename
final function getLine():Int; // source line
final function getTrace():NativeIndexedArray<NativeAssocArray<Dynamic>>; // an array of the backtrace
final function getTraceAsString():String; // formatted string of trace
@:phpMagic function __toString():String; // formatted string for display
}

View File

@ -0,0 +1,42 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
@:native('Exception')
extern class Exception implements Throwable {
public function new(?message:String, ?code:Int, ?previous:Throwable):Void;
private var message:String;
private var code:Int;
private var file:String;
private var line:Int;
final function getPrevious():Throwable; // Returns previous Throwable
function getMessage():String; // message of the exception
function getCode():Int; // code of the exception
function getFile():String; // source filename
function getLine():Int; // source line
function getTrace():NativeIndexedArray<NativeAssocArray<Dynamic>>; // an array of the backtrace
function getTraceAsString():String; // formatted string of trace
@:phpMagic function __toString():String; // formatted string for display
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (C)2005-2021 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.finfo.php
**/
@:native("finfo")
extern class Finfo {
function new(?flags: Int, magic_database: String = "");
function buffer(string: String, ?flags: Int, ?context:Resource): EitherType<String, Bool>;
function file(filename: String, ?flags: Int, ?context:Resource): EitherType<String, Bool>;
function set_flags(flags: Int): Bool;
}

View File

@ -0,0 +1,91 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
Generator is not a Haxe Iterable. It can be iterated one time only.
Unfortunately Haxe does not know that in PHP generators may have no `return` expression or `return value` with any type of `value`.
Use `return null` or untyped cast to workaround this issue:
```haxe
function generatorWithoutReturn():Generator {
php.Syntax.yield(1);
return null;
}
function generatorWithReturn():Generator {
php.Syntax.yield(1);
return cast "hello";
}
var g = generatorWithReturn();
for(i in g) {
trace(i);
}
trace(g.getReturn()); // "hello"
```
@see http://php.net/manual/en/class.generator.php
**/
@:native('Generator')
extern class Generator {
function current():Dynamic;
function getReturn():Dynamic;
function key():Dynamic;
function next():Void;
function rewind():Void;
function send(value:Dynamic):Dynamic;
@:native('throw')
function throwError(exception:Throwable):Dynamic;
function valid():Bool;
inline function iterator():GeneratorIterator {
return new GeneratorIterator(this);
}
}
private class GeneratorIterator {
var generator:Generator;
/**
This field is required to maintain execution order of .next()/.valid()/.current() methods.
@see http://php.net/manual/en/class.iterator.php
**/
var first:Bool = true;
public inline function new(generator:Generator) {
this.generator = generator;
}
public inline function hasNext():Bool {
if (first) {
first = false;
} else {
generator.next();
}
return generator.valid();
}
public inline function next():Dynamic {
return generator.current();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,120 @@
/*
* Copyright (C)2005-2021 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.intlcalendar.php
**/
@:native("IntlCalendar")
extern class IntlCalendar {
@:phpClassConst static final DOW_FRIDAY: Int;
@:phpClassConst static final DOW_MONDAY: Int;
@:phpClassConst static final DOW_SATURDAY: Int;
@:phpClassConst static final DOW_SUNDAY: Int;
@:phpClassConst static final DOW_THURSDAY: Int;
@:phpClassConst static final DOW_TUESDAY: Int;
@:phpClassConst static final DOW_TYPE_WEEKDAY: Int;
@:phpClassConst static final DOW_TYPE_WEEKEND_CEASE: Int;
@:phpClassConst static final DOW_TYPE_WEEKEND_OFFSET: Int;
@:phpClassConst static final DOW_TYPE_WEEKEND: Int;
@:phpClassConst static final DOW_WEDNESDAY: Int;
@:phpClassConst static final FIELD_AM_PM: Int;
@:phpClassConst static final FIELD_DATE: Int;
@:phpClassConst static final FIELD_DAY_OF_MONTH: Int;
@:phpClassConst static final FIELD_DAY_OF_WEEK_IN_MONTH: Int;
@:phpClassConst static final FIELD_DAY_OF_WEEK: Int;
@:phpClassConst static final FIELD_DAY_OF_YEAR: Int;
@:phpClassConst static final FIELD_DOW_LOCAL: Int;
@:phpClassConst static final FIELD_DST_OFFSET: Int;
@:phpClassConst static final FIELD_ERA: Int;
@:phpClassConst static final FIELD_EXTENDED_YEAR: Int;
@:phpClassConst static final FIELD_FIELD_COUNT: Int;
@:phpClassConst static final FIELD_HOUR_OF_DAY: Int;
@:phpClassConst static final FIELD_HOUR: Int;
@:phpClassConst static final FIELD_IS_LEAP_MONTH: Int;
@:phpClassConst static final FIELD_JULIAN_DAY: Int;
@:phpClassConst static final FIELD_MILLISECOND: Int;
@:phpClassConst static final FIELD_MILLISECONDS_IN_DAY: Int;
@:phpClassConst static final FIELD_MINUTE: Int;
@:phpClassConst static final FIELD_MONTH: Int;
@:phpClassConst static final FIELD_SECOND: Int;
@:phpClassConst static final FIELD_WEEK_OF_MONTH: Int;
@:phpClassConst static final FIELD_WEEK_OF_YEAR: Int;
@:phpClassConst static final FIELD_YEAR_WOY: Int;
@:phpClassConst static final FIELD_YEAR: Int;
@:phpClassConst static final FIELD_ZONE_OFFSET: Int;
@:phpClassConst static final WALLTIME_FIRST: Int;
@:phpClassConst static final WALLTIME_LAST: Int;
@:phpClassConst static final WALLTIME_NEXT_VALID: Int;
static function createInstance(timeZone: EitherType<Null<String>, EitherType<DateTimeZone, IntlTimeZone>> = null, locale: Null<String> = ""): Null<IntlCalendar>;
static function fromDateTime(dateTime: EitherType<DateTime, String>): Null<IntlCalendar>;
static function getAvailableLocales(): NativeIndexedArray<String>;
static function getKeywordValuesForLocale(key: String, locale: String, commonlyUsed: Bool): EitherType<NativeIterator<Int, String>, Bool>;
static function getNow(): Float;
function add(field: Int, amount: Int): Bool;
function after(other: IntlCalendar): Bool;
function before(other: IntlCalendar): Bool;
function clear(field: Null<Int> = null): Bool;
function equals(other: IntlCalendar): Bool;
function fieldDifference(when: Float, field: Int): EitherType<Int, Bool>;
function get(field: Int): Int;
function getActualMaximum(field: Int): EitherType<Int, Bool>;
function getActualMinimum(field: Int): EitherType<Int, Bool>;
function getDayOfWeekType(dayOfWeek: Int): EitherType<Int, Bool>;
function getErrorCode(): Int;
function getErrorMessage(): String;
function getFirstDayOfWeek(): EitherType<Int, Bool>;
function getGreatestMinimum(field: Int): EitherType<Int, Bool>;
function getLeastMaximum(field: Int): EitherType<Int, Bool>;
function getLocale(localeType: Int): EitherType<String, Bool>;
function getMaximum(field: Int): EitherType<Int, Bool>;
function getMinimalDaysInFirstWeek(): EitherType<Int, Bool>;
function getMinimum(field: Int): EitherType<Int, Bool>;
function getRepeatedWallTimeOption(): Int;
function getSkippedWallTimeOption(): Int;
function getTime(): Float;
function getTimeZone(): IntlTimeZone;
function getType(): String;
function getWeekendTransition(dayOfWeek: Int): EitherType<Int, Bool>;
function inDaylightTime(): Bool;
function isEquivalentTo(other: IntlCalendar): Bool;
function isLenient(): Bool;
function isSet(field: Int): Bool;
function isWeekend(date: Null<Float> = null): Bool;
function roll(field: Int, amountOrUpOrDown: EitherType<Bool, Int>): Bool;
function setFirstDayOfWeek(dayOfWeek: Int): Bool;
function setLenient(isLenient: Bool): Bool;
function setMinimalDaysInFirstWeek(minimalDays: Int): Bool;
function setRepeatedWallTimeOption(wallTimeOption: Int): Bool;
function setSkippedWallTimeOption(wallTimeOption: Int): Bool;
function setTime(date: Float): Bool;
function setTimeZone(timeZone: EitherType<Null<String>, EitherType<DateTimeZone, IntlTimeZone>>): Bool;
function toDateTime(): EitherType<DateTime, Bool>;
@:overload(function(year: Int, month: Int, dayOfMonth: Null<Int> = null, hour: Null<Int> = null, minute: Null<Int> = null, second: Null<Int> = null): Bool {})
function set(field: Int, value: Int): Bool;
}

View File

@ -0,0 +1,72 @@
/*
* Copyright (C)2005-2021 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.intldateformatter.php
**/
@:native("IntlDateFormatter")
extern class IntlDateFormatter {
@:phpClassConst static final FULL: Int;
@:phpClassConst static final GREGORIAN: Int;
@:phpClassConst static final LONG: Int;
@:phpClassConst static final MEDIUM: Int;
@:phpClassConst static final NONE: Int;
@:phpClassConst static final RELATIVE_FULL: Int;
@:phpClassConst static final RELATIVE_LONG: Int;
@:phpClassConst static final RELATIVE_MEDIUM: Int;
@:phpClassConst static final RELATIVE_SHORT: Int;
@:phpClassConst static final SHORT: Int;
@:phpClassConst static final TRADITIONAL: Int;
function new(locale: Null<String>, dateType: Int, timeType: Int, timezone: EitherType<String, EitherType<DateTimeZone, IntlTimeZone>> = null,
calendar: EitherType<Int, IntlCalendar> = null, pattern: String = "");
static function create(locale: Null<String>, dateType: Int, timeType: Int,
timezone: EitherType<String, EitherType<DateTimeZone, IntlTimeZone>> = null,
calendar: EitherType<Int, IntlCalendar> = null, pattern: String = ""): Null<IntlDateFormatter>;
static function formatObject(datetime: EitherType<IntlCalendar, DateTime>, format: EitherType<Int, EitherType<NativeIndexedArray<Int>, String>> = null,
locale: String = null): EitherType<String, Bool>;
function format(datetime: EitherType<Int, EitherType<Float, EitherType<String, EitherType<DateTimeInterface, EitherType<IntlCalendar, NativeAssocArray<Int>>>>>>): EitherType<String, Bool>;
function getCalendar(): EitherType<Int, Bool>;
function getCalendarObject(): EitherType<Null<IntlCalendar>, Bool>;
function getDateType(): EitherType<Int, Bool>;
function getErrorCode(): Int;
function getErrorMessage(): String;
function getLocale(?type: Int): EitherType<String, Bool>;
function getPattern(): EitherType<String, Bool>;
function getTimeType(): EitherType<Int, Bool>;
function getTimeZone(): EitherType<IntlTimeZone, Bool>;
function getTimeZoneId(): EitherType<String, Bool>;
function isLenient(): Bool;
function localtime(string: String, offset: Ref<Int> = null): EitherType<NativeAssocArray<Int>, Bool>;
function parse(string: String, offset: Ref<Int> = null): EitherType<Int, EitherType<Float, Bool>>;
function setCalendar(calendar: EitherType<Null<IntlCalendar>, Int>): Bool;
function setLenient(lenient: Bool): Bool;
function setPattern(pattern: String): Bool;
function setTimeZone(timezone: EitherType<Null<String>, EitherType<IntlTimeZone, DateTimeZone>>): Null<Bool>;
}

View File

@ -0,0 +1,35 @@
/*
* Copyright (C)2005-2021 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/class.intliterator.php
**/
@:native("IntlIterator")
extern class IntlIterator<K, V> implements NativeIterator<K, V> {
function current(): V;
function key(): K;
function next(): Void;
function rewind(): Void;
function valid(): Bool;
}

View File

@ -0,0 +1,60 @@
/*
* Copyright (C)2005-2021 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.intltimezone.php
**/
@:native("IntlTimeZone")
extern class IntlTimeZone {
@:phpClassConst static final DISPLAY_LONG: Int;
@:phpClassConst static final DISPLAY_SHORT: Int;
static function countEquivalentIDs(zoneId: String): Int;
static function createDefault(): IntlTimeZone;
static function createEnumeration(countryOrRawOffset: Any): IntlIterator<Int, String>;
static function createTimeZone(zoneId: String): IntlTimeZone;
static function createTimeZoneIDEnumeration(zoneType: Int, ?region: String, ?rawOffset: Int): EitherType<IntlIterator<Int, String>, Bool>;
static function fromDateTimeZone(zoneId: DateTimeZone): IntlTimeZone;
static function getCanonicalID(zoneId: String, isSystemID: Ref<Bool>): String;
static function getEquivalentID(zoneId: String, index: Int): String;
static function getGMT(): IntlTimeZone;
static function getIDForWindowsID(timezone: String, ?region: String): EitherType<String, Bool>;
static function getRegion(zoneId: String): EitherType<String, Bool>;
static function getTZDataVersion(): String;
static function getUnknown(): Null<IntlTimeZone>;
static function getWindowsID(timezone: String): EitherType<String, Bool>;
function getDisplayName(?isDaylight: Bool, ?style: Int, ?locale: String): String;
function getDSTSavings(): Int;
function getErrorCode(): Int;
function getErrorMessage(): String;
function getID(): String;
function getOffset(date: Float, local: Bool, rawOffset: Ref<Int>, dstOffset: Ref<Int>): Bool;
function getRawOffset(): Int;
function hasSameRules(otherTimeZone: IntlTimeZone): Bool;
function toDateTimeZone(): DateTimeZone;
function useDaylightTime(): Bool;
}

View File

@ -0,0 +1,31 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/class.iteratoraggregate.php
**/
@:native('IteratorAggregate')
extern interface IteratorAggregate<T> extends Traversable {
function getIterator():Traversable;
}

View File

@ -0,0 +1,31 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/class.jsonserializable.php
**/
@:native('JsonSerializable')
extern interface JsonSerializable<T> {
function jsonSerialize():T;
}

View File

@ -0,0 +1,189 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.ds.StringMap;
import php.*;
import php.reflection.ReflectionClass;
/**
Platform-specific PHP Library. Provides some platform-specific functions
for the PHP target, such as conversion from Haxe types to native types
and vice-versa.
**/
class Lib {
/**
Print the specified value on the default output.
**/
public static inline function print(v:Dynamic):Void {
Global.echo(Std.string(v));
}
/**
Print the specified value on the default output followed by
a newline character.
**/
public static function println(v:Dynamic):Void {
print(v);
print("\n");
}
/**
Displays structured information about one or more expressions
that includes its type and value. Arrays and objects are
explored recursively with values indented to show structure.
**/
public static inline function dump(v:Dynamic):Void {
Global.var_dump(v);
}
/**
Serialize using native PHP serialization. This will return a binary
`String` that can be stored for long term usage.
**/
public static inline function serialize(v:Dynamic):String {
return Global.serialize(v);
}
/**
Unserialize a `String` using native PHP serialization. See `php.Lib.serialize()`.
**/
public static inline function unserialize(s:String):Dynamic {
return Global.unserialize(s);
}
/**
Find out whether an extension is loaded.
**/
public static inline function extensionLoaded(name:String) {
return Global.extension_loaded(name);
}
public static inline function isCli():Bool {
return 0 == Global.strncasecmp(Const.PHP_SAPI, 'cli', 3);
}
/**
Output file content from the given file name.
**/
public static inline function printFile(file:String) {
return Global.fpassthru(Global.fopen(file, "r"));
}
public static inline function toPhpArray(a:Array<Dynamic>):NativeArray {
return @:privateAccess a.arr;
}
public static inline function toHaxeArray(a:NativeArray):Array<Dynamic> {
return @:privateAccess Array.wrap(a);
}
public static function hashOfAssociativeArray<T>(arr:NativeAssocArray<T>):Map<String, T> {
var result = new StringMap();
@:privateAccess result.data = arr;
return result;
}
public static inline function associativeArrayOfHash(hash:haxe.ds.StringMap<Dynamic>):NativeArray {
return @:privateAccess hash.data;
}
public static function objectOfAssociativeArray(arr:NativeArray):Dynamic {
Syntax.foreach(arr, function(key:Scalar, value:Dynamic) {
if (Global.is_array(value)) {
arr[key] = objectOfAssociativeArray(value);
}
});
return Boot.createAnon(arr);
}
public static inline function associativeArrayOfObject(ob:Dynamic):NativeArray {
return Syntax.array(ob);
}
/**
See the documentation for the equivalent PHP function for details on usage:
<http://php.net/manual/en/function.mail.php>
**/
public static inline function mail(to:String, subject:String, message:String, ?additionalHeaders:String, ?additionalParameters:String):Bool {
return Global.mail(to, subject, message, additionalHeaders, additionalParameters);
}
/**
Rethrows an exception.
If `e` is not a value caught in `try...catch` or if called outside of `catch` block, then `e` is thrown as
a new exception.
**/
extern public static inline function rethrow(e:Dynamic) {
if (Syntax.code("isset($__hx__caught_e, $__hx__real_e)") && e == Syntax.code("$__hx__real_e")) {
Syntax.code("throw $__hx__caught_e");
}
throw e;
}
/**
Tries to load all compiled php files and returns list of types.
**/
public static function getClasses():Dynamic {
if (!loaded) {
loaded = true;
var reflection = new ReflectionClass(Boot.getPhpName('php.Boot'));
loadLib(Global.dirname(reflection.getFileName(), 2));
}
var result:Dynamic = {};
Syntax.foreach(Boot.getRegisteredAliases(), function(phpName:String, haxeName:String) {
var parts = haxeName.split('.');
var obj = result;
while (parts.length > 1) {
var pack = parts.shift();
if (Syntax.field(obj, pack) == null) {
Syntax.setField(obj, pack, {});
}
obj = Syntax.field(obj, pack);
}
Syntax.setField(obj, parts[0], Boot.getClass(phpName));
});
return result;
}
static var loaded:Bool = false;
/**
Loads types defined in the specified directory.
**/
public static function loadLib(pathToLib:String):Void {
var absolutePath = Global.realpath(pathToLib);
if (absolutePath == false)
throw 'Failed to read path: $pathToLib';
Syntax.foreach(Global.glob('$absolutePath/*.php'), function(_, fileName) {
if (!Global.is_dir(fileName)) {
Global.require_once(fileName);
}
});
Syntax.foreach(Global.glob('$absolutePath/*', Const.GLOB_ONLYDIR), function(_, dirName) {
loadLib(dirName);
});
}
}

View File

@ -0,0 +1,59 @@
/*
* Copyright (C)2005-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/class.locale.php
**/
@:native("Locale")
extern class Locale {
@:phpClassConst static final ACTUAL_LOCALE: String;
@:phpClassConst static final DEFAULT_LOCALE: Null<String>;
@:phpClassConst static final EXTLANG_TAG: String;
@:phpClassConst static final GRANDFATHERED_LANG_TAG: String;
@:phpClassConst static final LANG_TAG: String;
@:phpClassConst static final PRIVATE_TAG: String;
@:phpClassConst static final REGION_TAG: String;
@:phpClassConst static final SCRIPT_TAG: String;
@:phpClassConst static final VALID_LOCALE: String;
@:phpClassConst static final VARIANT_TAG: String;
static function acceptFromHttp(header: String): String;
static function canonicalize(locale: String): String;
static function composeLocale(subtags: NativeAssocArray<String>): String;
static function filterMatches(langtag: String, locale: String, canonicalize: Bool = false): Bool;
static function getAllVariants(locale: String): Null<NativeIndexedArray<String>>;
static function getDefault(): String;
static function getDisplayLanguage(locale: String, ?in_locale: String): String;
static function getDisplayName(locale: String, ?in_locale: String): String;
static function getDisplayRegion(locale: String, ?in_locale: String): String;
static function getDisplayScript(locale: String, ?in_locale: String): String;
static function getDisplayVariant(locale: String, ?in_locale: String): String;
static function getKeywords(locale: String): NativeAssocArray<String>;
static function getPrimaryLanguage(locale: String): Null<String>;
static function getRegion(locale: String): Null<String>;
static function getScript(locale: String): Null<String>;
static function lookup(langtag: NativeIndexedArray<String>, locale: String, canonicalize: Bool = false, ?defaultLocale: String): String;
static function parseLocale(locale: String): Null<NativeAssocArray<String>>;
static function setDefault(locale: String): Bool;
}

View File

@ -0,0 +1,69 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
Exception that represents error in the program logic.
This kind of exception should lead directly to a fix in your code.
**/
@:native('LogicException')
extern class LogicException extends Exception {}
/**
Exception thrown if a callback refers to an undefined function
or if some arguments are missing.
**/
@:native('BadFunctionCallException')
extern class BadFunctionCallException extends LogicException {}
/**
Exception thrown if a callback refers to an undefined method
or if some arguments are missing.
**/
@:native('BadMethodCallException')
extern class BadMethodCallException extends BadFunctionCallException {}
/**
Exception thrown if a value does not adhere to a defined valid data domain.
**/
@:native('DomainException')
extern class DomainException extends LogicException {}
/**
Exception thrown if an argument is not of the expected type.
**/
@:native('InvalidArgumentException')
extern class InvalidArgumentException extends LogicException {}
/**
Exception thrown if a length is invalid.
**/
@:native('LengthException')
extern class LengthException extends LogicException {}
/**
Exception thrown when an illegal index was requested.
This represents errors that should be detected at compile time.
**/
@:native('OutOfRangeException')
extern class OutOfRangeException extends LogicException {}

View File

@ -0,0 +1,78 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
using php.Global;
/**
Native PHP array.
**/
@:coreType @:runtimeValue @:semantics(value) abstract NativeArray {
public inline function new()
this = Syntax.arrayDecl();
@:arrayAccess function getByInt(key:Int):Dynamic;
@:arrayAccess function setByInt(key:Int, val:Dynamic):Dynamic;
@:arrayAccess function getByFloat(key:Float):Dynamic;
@:arrayAccess function setByFloat(key:Float, val:Dynamic):Dynamic;
@:arrayAccess function getByString(key:String):Dynamic;
@:arrayAccess function setByString(key:String, val:Dynamic):Dynamic;
@:arrayAccess function getByBool(key:Bool):Dynamic;
@:arrayAccess function setByBool(key:Bool, val:Dynamic):Dynamic;
public inline function iterator()
return Global.array_values(this).iterator();
public inline function keyValueIterator():NativeArrayKeyValueIterator
return new NativeArrayKeyValueIterator(this);
}
private class NativeArrayKeyValueIterator {
var length:Int;
var current:Int = 0;
var keys:NativeIndexedArray<EitherType<String, Int>>;
var values:NativeIndexedArray<Dynamic>;
public inline function new(data:NativeArray) {
length = Global.count(data);
this.keys = Global.array_keys(data);
this.values = Global.array_values(data);
}
public inline function hasNext():Bool {
return current < length;
}
public inline function next():{key:EitherType<String, Int>, value:Dynamic} {
return {key: keys[current], value: values[current++]};
}
}

View File

@ -0,0 +1,65 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
@:forward
@:semantics(value)
abstract NativeAssocArray<T>(NativeArray) from NativeArray to NativeArray {
public inline function new()
this = Syntax.arrayDecl();
@:arrayAccess
inline function get(key:String):T
return this[key];
@:arrayAccess
inline function set(key:String, val:T):T
return this[key] = val;
public inline function iterator()
return (cast Global.array_values(this) : NativeIndexedArray<T>).iterator();
public inline function keyValueIterator():NativeAssocArrayKeyValueIterator<T>
return new NativeAssocArrayKeyValueIterator(this);
}
private class NativeAssocArrayKeyValueIterator<T> {
var length:Int;
var current:Int = 0;
var keys:NativeIndexedArray<String>;
var values:NativeIndexedArray<T>;
public inline function new(data:NativeIndexedArray<T>) {
length = Global.count(data);
this.keys = Global.array_keys(data);
this.values = cast Global.array_values(data);
}
public inline function hasNext():Bool {
return current < length;
}
public inline function next():{key:String, value:T} {
return {key: keys[current], value: values[current++]};
}
}

View File

@ -0,0 +1,97 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
@:forward
@:semantics(value)
abstract NativeIndexedArray<T>(NativeArray) from NativeArray to NativeArray {
public inline function new()
this = Syntax.arrayDecl();
@:arrayAccess
inline function get(idx:Int):T
return this[idx];
@:arrayAccess
inline function set(idx:Int, val:T):T
return this[idx] = val;
public inline function push(val:T)
Syntax.code('{0}[] = {1}', this, val);
public inline function iterator():NativeIndexedArrayIterator<T>
return new NativeIndexedArrayIterator(this);
public inline function keyValueIterator():NativeIndexedArrayKeyValueIterator<T>
return new NativeIndexedArrayKeyValueIterator(this);
@:to
inline function toHaxeArray():Array<T>
return @:privateAccess Array.wrap(this);
@:from
static inline function fromHaxeArray<T>(a:Array<T>):NativeIndexedArray<T>
return @:privateAccess a.arr;
public inline function toString():String {
return Boot.stringifyNativeIndexedArray(this);
}
}
private class NativeIndexedArrayIterator<T> {
var length:Int;
var current:Int = 0;
var data:NativeIndexedArray<T>;
public inline function new(data:NativeIndexedArray<T>) {
length = Global.count(data);
this.data = data;
}
public inline function hasNext():Bool {
return current < length;
}
public inline function next():T {
return data[current++];
}
}
private class NativeIndexedArrayKeyValueIterator<T> {
var length:Int;
var current:Int = 0;
var data:NativeIndexedArray<T>;
public inline function new(data:NativeIndexedArray<T>) {
length = Global.count(data);
this.data = data;
}
public inline function hasNext():Bool {
return current < length;
}
public inline function next():{key:Int, value:T} {
return {key: current, value: data[current++]};
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
Native PHP interface.
@see https://www.php.net/manual/en/class.iterator.php
**/
@:native('Iterator')
extern interface NativeIterator<K, V> extends Traversable {
function current():V;
function key():K;
function next():Void;
function rewind():Void;
function valid():Bool;
}

View File

@ -0,0 +1,74 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
Native PHP string.
**/
@:coreType @:runtimeValue abstract NativeString from String to String {
@:arrayAccess function get(key:Int):String;
@:arrayAccess function set(key:Int, val:String):String;
public inline function iterator() {
return new NativeStringIterator(this);
}
public inline function keyValueIterator() {
return new NativeStringKeyValueIterator(this);
}
}
class NativeStringIterator {
var s:NativeString;
var i:Int = 0;
public inline function new(s:NativeString) {
this.s = s;
}
public inline function hasNext():Bool {
return i < Global.strlen(s);
}
public inline function next():String {
return s[i++];
}
}
class NativeStringKeyValueIterator {
var s:NativeString;
var i:Int = 0;
public inline function new(s:NativeString) {
this.s = s;
}
public inline function hasNext():Bool {
return i < Global.strlen(s);
}
public inline function next():{key:Int, value:String} {
return {key: i, value: s[i++]};
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
This type can be used in places where externs use associative arrays as a list of configuration options.
This type is a special case for Haxe->Php generator: object declaration is generated as php array declaration whenever
that object declaration is passed directly to a variable or a function argument of this type.
**/
@:forward
abstract NativeStructArray<T:{}>(NativeArray) to NativeArray {
@:from @:pure(false)
static function __fromObject<T:{}>(obj:T):NativeStructArray<T> {
return cast Syntax.array(obj);
}
@:to
inline function __toObject():T {
return Boot.createAnon(this);
}
@:arrayAccess
inline function get<V>(key:String):V
return this[key];
@:arrayAccess
inline function set<V>(key:String, val:V):V
return this[key] = val;
}

View File

@ -0,0 +1,126 @@
/*
* Copyright (C)2005-2021 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.numberformatter.php
**/
@:native("NumberFormatter")
extern class NumberFormatter {
@:phpClassConst static final CURRENCY: Int;
@:phpClassConst static final CURRENCY_ACCOUNTING: Int;
@:phpClassConst static final CURRENCY_CODE: Int;
@:phpClassConst static final CURRENCY_SYMBOL: Int;
@:phpClassConst static final DECIMAL: Int;
@:phpClassConst static final DECIMAL_ALWAYS_SHOWN: Int;
@:phpClassConst static final DECIMAL_SEPARATOR_SYMBOL: Int;
@:phpClassConst static final DEFAULT_RULESET: Int;
@:phpClassConst static final DEFAULT_STYLE: Int;
@:phpClassConst static final DIGIT_SYMBOL: Int;
@:phpClassConst static final DURATION: Int;
@:phpClassConst static final EXPONENTIAL_SYMBOL: Int;
@:phpClassConst static final FORMAT_WIDTH: Int;
@:phpClassConst static final FRACTION_DIGITS: Int;
@:phpClassConst static final GROUPING_SEPARATOR_SYMBOL: Int;
@:phpClassConst static final GROUPING_SIZE: Int;
@:phpClassConst static final GROUPING_USED: Int;
@:phpClassConst static final IGNORE: Int;
@:phpClassConst static final INFINITY_SYMBOL: Int;
@:phpClassConst static final INTEGER_DIGITS: Int;
@:phpClassConst static final INTL_CURRENCY_SYMBOL: Int;
@:phpClassConst static final LENIENT_PARSE: Int;
@:phpClassConst static final MAX_FRACTION_DIGITS: Int;
@:phpClassConst static final MAX_INTEGER_DIGITS: Int;
@:phpClassConst static final MAX_SIGNIFICANT_DIGITS: Int;
@:phpClassConst static final MIN_FRACTION_DIGITS: Int;
@:phpClassConst static final MIN_INTEGER_DIGITS: Int;
@:phpClassConst static final MIN_SIGNIFICANT_DIGITS: Int;
@:phpClassConst static final MINUS_SIGN_SYMBOL: Int;
@:phpClassConst static final MONETARY_GROUPING_SEPARATOR_SYMBOL: Int;
@:phpClassConst static final MONETARY_SEPARATOR_SYMBOL: Int;
@:phpClassConst static final MULTIPLIER: Int;
@:phpClassConst static final NAN_SYMBOL: Int;
@:phpClassConst static final NEGATIVE_PREFIX: Int;
@:phpClassConst static final NEGATIVE_SUFFIX: Int;
@:phpClassConst static final ORDINAL: Int;
@:phpClassConst static final PAD_AFTER_PREFIX: Int;
@:phpClassConst static final PAD_AFTER_SUFFIX: Int;
@:phpClassConst static final PAD_BEFORE_PREFIX: Int;
@:phpClassConst static final PAD_BEFORE_SUFFIX: Int;
@:phpClassConst static final PAD_ESCAPE_SYMBOL: Int;
@:phpClassConst static final PADDING_CHARACTER: Int;
@:phpClassConst static final PADDING_POSITION: Int;
@:phpClassConst static final PARSE_INT_ONLY: Int;
@:phpClassConst static final PATTERN_DECIMAL: Int;
@:phpClassConst static final PATTERN_RULEBASED: Int;
@:phpClassConst static final PATTERN_SEPARATOR_SYMBOL: Int;
@:phpClassConst static final PERCENT: Int;
@:phpClassConst static final PERCENT_SYMBOL: Int;
@:phpClassConst static final PERMILL_SYMBOL: Int;
@:phpClassConst static final PLUS_SIGN_SYMBOL: Int;
@:phpClassConst static final POSITIVE_PREFIX: Int;
@:phpClassConst static final POSITIVE_SUFFIX: Int;
@:phpClassConst static final PUBLIC_RULESETS: Int;
@:phpClassConst static final ROUND_CEILING: Int;
@:phpClassConst static final ROUND_DOWN: Int;
@:phpClassConst static final ROUND_FLOOR: Int;
@:phpClassConst static final ROUND_HALFDOWN: Int;
@:phpClassConst static final ROUND_HALFEVEN: Int;
@:phpClassConst static final ROUND_HALFUP: Int;
@:phpClassConst static final ROUND_UP: Int;
@:phpClassConst static final ROUNDING_INCREMENT: Int;
@:phpClassConst static final ROUNDING_MODE: Int;
@:phpClassConst static final SCIENTIFIC: Int;
@:phpClassConst static final SECONDARY_GROUPING_SIZE: Int;
@:phpClassConst static final SIGNIFICANT_DIGIT_SYMBOL: Int;
@:phpClassConst static final SIGNIFICANT_DIGITS_USED: Int;
@:phpClassConst static final SPELLOUT: Int;
@:phpClassConst static final TYPE_CURRENCY: Int;
@:phpClassConst static final TYPE_DEFAULT: Int;
@:phpClassConst static final TYPE_DOUBLE: Int;
@:phpClassConst static final TYPE_INT32: Int;
@:phpClassConst static final TYPE_INT64: Int;
@:phpClassConst static final ZERO_DIGIT_SYMBOL: Int;
function new(locale: String, style: Int, ?pattern: String);
static function create(locale: String, style: Int, ?pattern: String): EitherType<NumberFormatter, Bool>;
function formatCurrency(value: Float, currency: String): EitherType<String, Bool>;
function format(value: EitherType<Int, Float>, ?type: Int): EitherType<String, Bool>;
function getAttribute(attr: Int): EitherType<Int, Bool>;
function getErrorCode(): Int;
function getErrorMessage(): String;
function getLocale(?type: Int): String;
function getPattern(): EitherType<String, Bool>;
function getSymbol(attr: Int): EitherType<String, Bool>;
function getTextAttribute(attr: Int): EitherType<String, Bool>;
function parseCurrency(value: String, currency: Ref<String>, ?position: Ref<Int>): EitherType<Float, Bool>;
function parse(value: String, ?type: Int, ?position: Ref<Int>): EitherType<Int, EitherType<Float, EitherType<String, Bool>>>;
function setAttribute(attr: Int, value: Int): Bool;
function setPattern(pattern: String): Bool;
function setSymbol(attr: Int, value: String): Bool;
function setTextAttribute(attr: Int, value: String): Bool;
}

View File

@ -0,0 +1,30 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
Special type which allows passing function arguments by reference.
This type should be used for externs only.
**/
@:semantics(reference)
typedef Ref<T> = T;

View File

@ -0,0 +1,29 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
PHP native `resource` type
@see http://php.net/manual/en/language.types.resource.php
**/
abstract Resource(Dynamic) {}

View File

@ -0,0 +1,65 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
Exception thrown if an error which can only be found on runtime occurs.
**/
@:native('RuntimeException')
extern class RuntimeException extends Exception {}
/**
Exception thrown if a value is not a valid key.
This represents errors that cannot be detected at compile time.
**/
@:native('OutOfBoundsException')
extern class OutOfBoundsException extends RuntimeException {}
/**
Exception thrown when adding an element to a full container.
**/
@:native('OverflowException')
extern class OverflowException extends RuntimeException {}
/**
Exception thrown to indicate range errors during program execution.
Normally this means there was an arithmetic error other than under/overflow.
**/
@:native('RangeException')
extern class RangeException extends RuntimeException {}
/**
Exception thrown when performing an invalid operation on an empty container,
such as removing an element.
**/
@:native('UnderflowException')
extern class UnderflowException extends RuntimeException {}
/**
Exception thrown if a value does not match with a set of values.
Typically this happens when a function calls another function and
expects the return value to be of a certain type or value not including
arithmetic or buffer related errors.
**/
@:native('UnexpectedValueException')
extern class UnexpectedValueException extends RuntimeException {}

View File

@ -0,0 +1,30 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
`Scalar` is a type that is compatible with any scalar value (int, float, bool, string)
**/
typedef Scalar = EitherType<Int, EitherType<String, EitherType<Float, Bool>>>;

View File

@ -0,0 +1,31 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/class.seekableiterator.php
**/
@:native('SeekableIterator')
extern interface SeekableIterator<K, V> extends NativeIterator<K, V> {
function seek(position:Int):Void;
}

View File

@ -0,0 +1,32 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see https://www.php.net/manual/en/class.serializable.php
**/
@:native('Serializable')
extern interface Serializable {
function serialize():String;
function unserialize(serialized:String):Void;
}

View File

@ -0,0 +1,188 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import php.Boot;
import php.Global.*;
import php.SuperGlobal.*;
/**
Session consists of a way to preserve certain data across
subsequent accesses.
*/
class Session {
public static function getCacheLimiter() {
switch (session_cache_limiter()) {
case "public":
return Public;
case "private":
return Private;
case "nocache":
return NoCache;
case "private_no_expire":
return PrivateNoExpire;
}
return null;
}
public static function setCacheLimiter(l:CacheLimiter) {
if (started)
throw "You can't set the cache limiter while the session is already in use";
switch (l) {
case Public:
session_cache_limiter("public");
case Private:
session_cache_limiter("private");
case NoCache:
session_cache_limiter("nocache");
case PrivateNoExpire:
session_cache_limiter("private_no_expire");
}
}
public static function getCacheExpire():Int {
return session_cache_expire();
}
public static function setCacheExpire(minutes:Int) {
if (started)
throw "You can't set the cache expire time while the session is already in use";
session_cache_expire(minutes);
}
public static function setName(name:String) {
if (started)
throw "You can't set the name while the session is already in use";
session_name(name);
}
public static function getName():String {
return session_name();
}
public static function getId():String {
return session_id();
}
public static function setId(id:String) {
if (started)
throw "You can't set the session id while the session is already in use";
session_id(id);
}
public static function getSavePath():String {
return session_save_path();
}
public static function setSavePath(path:String) {
if (started)
throw "You can't set the save path while the session is already in use";
session_save_path(path);
}
public static function getModule():String {
return session_module_name();
}
public static function setModule(module:String) {
if (started)
throw "You can't set the module while the session is already in use";
session_module_name(module);
}
public static function regenerateId(?deleteold:Bool):Bool {
return session_regenerate_id(deleteold);
}
public static function get(name:String):Dynamic {
start();
if (!isset(_SESSION[name]))
return null;
return _SESSION[name];
}
public static function set(name:String, value:Dynamic) {
start();
return _SESSION[name] = value;
}
public static function setCookieParams(?lifetime:Int, ?path:String, ?domain:String, ?secure:Bool, ?httponly:Bool) {
if (started)
throw "You can't set the cookie params while the session is already in use";
session_set_cookie_params(lifetime, path, domain, secure, httponly);
}
public static function getCookieParams():{
lifetime:Int,
path:String,
domain:String,
secure:Bool,
httponly:Bool
} {
return Boot.createAnon(session_get_cookie_params());
}
// TODO: completely untested
public static function setSaveHandler(open:String->String->Bool, close:Void->Bool, read:String->String, write:String->String->Bool, destroy, gc):Bool {
return session_set_save_handler(open, close, read, write, destroy, gc);
}
public static function exists(name:String) {
start();
return array_key_exists(name, _SESSION);
}
public static function remove(name:String) {
start();
unset(_SESSION[name]);
}
public static var started(default, null):Bool;
public static function start() {
if (started)
return;
started = true;
session_start();
}
public static function clear() {
session_unset();
}
public static function close() {
session_write_close();
started = false; // TODO: not sure this useful; test if a closed session can be re-opened (I doubt)
}
static function __init__() {
started = isset(_SESSION);
}
}
enum CacheLimiter {
Public;
Private;
NoCache;
PrivateNoExpire;
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see http://php.net/manual/en/class.sessionhandlerinterface.php
**/
@:native('SessionHandlerInterface')
extern interface SessionHandlerInterface {
function close():Bool;
function destroy(session_id:String):Bool;
function gc(maxlifetime:Int):Bool;
function open(save_path:String, session_name:String):Bool;
function read(session_id:String):String;
function write(session_id:String, session_data:String):Bool;
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
@:native('StdClass')
@:phpNoConstructor
extern class StdClass implements Dynamic {
@:pure(true) function new():Void;
}

View File

@ -0,0 +1,97 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
class SuperGlobal {
/**
@see http://php.net/manual/en/reserved.variables.globals.php
**/
public static var GLOBALS(get, never):NativeAssocArray<Dynamic>;
static inline function get_GLOBALS()
return Syntax.code("$GLOBALS");
/**
@see http://php.net/manual/en/reserved.variables.server.php
**/
public static var _SERVER(get, never):NativeAssocArray<Dynamic>;
static inline function get__SERVER()
return Syntax.code("$_SERVER");
/**
@see http://php.net/manual/en/reserved.variables.get.php
**/
public static var _GET(get, never):NativeAssocArray<Dynamic>;
static inline function get__GET()
return Syntax.code("$_GET");
/**
@see http://php.net/manual/en/reserved.variables.post.php
**/
public static var _POST(get, never):NativeAssocArray<Dynamic>;
static inline function get__POST()
return Syntax.code("$_POST");
/**
@see http://php.net/manual/en/reserved.variables.files.php
**/
public static var _FILES(get, never):NativeAssocArray<Dynamic>;
static inline function get__FILES()
return Syntax.code("$_FILES");
/**
@see http://php.net/manual/en/reserved.variables.cookie.php
**/
public static var _COOKIE(get, never):NativeAssocArray<Dynamic>;
static inline function get__COOKIE()
return Syntax.code("$_COOKIE");
/**
@see http://php.net/manual/en/reserved.variables.session.php
**/
public static var _SESSION(get, never):NativeAssocArray<Dynamic>;
static inline function get__SESSION()
return Syntax.code("$_SESSION");
/**
@see http://php.net/manual/en/reserved.variables.request.php
**/
public static var _REQUEST(get, never):NativeAssocArray<Dynamic>;
static inline function get__REQUEST()
return Syntax.code("$_REQUEST");
/**
@see http://php.net/manual/en/reserved.variables.env.php
**/
public static var _ENV(get, never):NativeAssocArray<Dynamic>;
static inline function get__ENV()
return Syntax.code("$_ENV");
}

View File

@ -0,0 +1,358 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.Rest;
import haxe.extern.AsVar;
import haxe.extern.EitherType;
/**
Special extern class to support PHP language specifics.
Don't use these functions unless you are really sure what you are doing.
**/
@:noClosure
extern class Syntax {
/**
Embeds plain php code.
`php` should be a string literal with php code.
It can contain placeholders like `{0}`, `{1}` which will be replaced with corresponding arguments from `args`.
E.g.:
```haxe
Syntax.code("var_dump({0}, {1})", a, b);
```
will generate
```haxe
var_dump($a, $b);
```
**/
static function code(code:String, args:Rest<Dynamic>):Dynamic;
/**
The same as `code()`, but adds dereferencing
when required to workaround "cannot use temporary expression in write context" php error.
**/
static function codeDeref(code:String, args:Rest<Dynamic>):Dynamic;
/**
Generates `$left <=> $right`
**/
static inline function spaceship(left:Dynamic, right:Dynamic):Int {
return code('({0} <=> {1})', left, right);
}
/**
Generates `$left ?? $right`
**/
static function coalesce<T>(left:T, right:T):T;
/**
Generates `$left . $right`
**/
static inline function concat(left:String, right:String):String {
return code('({0} . {1})', left, right);
}
/**
Generates `$left == $right`
**/
static inline function equal(left:Dynamic, right:Dynamic):Bool {
return code('({0} == {1})', left, right);
}
/**
Generates `$left === $right`
**/
static inline function strictEqual(left:Dynamic, right:Dynamic):Bool {
return code('({0} === {1})', left, right);
}
/**
Generates `$left != $right`
**/
static inline function notEqual(left:Dynamic, right:Dynamic):Bool {
return code('({0} != {1})', left, right);
}
/**
Generates `$left !== $right`
**/
static inline function strictNotEqual(left:Dynamic, right:Dynamic):Bool {
return code('({0} !== {1})', left, right);
}
/**
Generates `$left + $right` for numbers.
**/
static inline function add<T:Float>(left:T, right:T):T {
return code('({0} + {1})', left, right);
}
/**
Generates `$left + $right` for php arrays.
**/
static inline function union(left:NativeArray, right:NativeArray):NativeArray {
return codeDeref('({0} + {1})', left, right);
}
/**
Generates `$left ** $right`
**/
static inline function exp<T:Float>(left:T, right:T):T {
return code('({0} ** {1})', left, right);
}
/**
Generates `$left % $right`
**/
static inline function mod(left:Float, right:Float):Int {
return code('({0} % {1})', left, right);
}
/**
Generates `$left ?: $right`
**/
static inline function shortTernary<T>(left:T, right:T):T {
return codeDeref('({0} ?: {1})', left, right);
}
/**
Generates `$left xor $right`
**/
static inline function xor(left:Bool, right:Bool):Bool {
return code('({0} xor {1})', left, right);
}
/**
Generates `(int)$value`
**/
static inline function int(value:Dynamic):Int {
return code('(int)({0})', value);
}
/**
Generates `(float)$value`
**/
static inline function float(value:Dynamic):Float {
return code('(float)({0})', value);
}
/**
Generates `(string)$value`
**/
static inline function string(value:Dynamic):String {
return code('(string)({0})', value);
}
/**
Generates `(bool)$value`
**/
static inline function bool(value:Dynamic):Bool {
return code('(bool)({0})', value);
}
/**
Generates `(object)$value`
**/
static inline function object(value:Dynamic):StdClass {
return codeDeref('((object)({0}))', value);
}
/**
Generates `(array)$value`
**/
static inline function array(value:Dynamic):NativeArray {
return codeDeref('((array)({0}))', value);
}
/**
Generates `$value instanceof $phpClassName`.
Haxe generates `Std.isOfType(value, Type)` calls as `$value instanceof Type` automatically where possible.
So you may need this only if you have a `Class` stored in a variable.
**/
@:overload(function(value:AsVar<Dynamic>, phpClassName:AsVar<String>):Bool {})
static function instanceof<V, C>(value:AsVar<V>, type:AsVar<Class<C>>):Bool;
/**
Generates PHP class name for a provided Haxe class.
```haxe
trace(Syntax.nativeClassName(php.Web)); // outputs: php\Web
```
**/
static function nativeClassName<T>(cls:EitherType<Class<T>, Enum<T>>):String;
/**
```haxe
Syntax.foreach(collection, function(key, value) trace(key, value));
```
generates:
```haxe
foreach($collection as $key => $value) {
trace($key, $value);
}
```
**/
static inline function foreach<TCollection, TKey, TValue>(collection:TCollection, body:TKey->TValue->Void):Void {
while (Syntax.foreachCondition) {
Syntax.foreachCollection(collection);
var key:TKey = Syntax.foreachKey();
var value:TValue = Syntax.foreachValue();
Syntax.keepVar(key, value, key, value);
body(key, value);
}
}
static private var foreachCondition:Bool;
static private function foreachCollection<T>(collection:T):Void;
static private function foreachKey<T>():T;
static private function foreachValue<T>():T;
/**
Generates `new $className($arg1, ...$argN)`
**/
@:overload(function(className:AsVar<String>, args:Rest<Dynamic>):Dynamic {})
static function construct<T>(cls:AsVar<Class<T>>, args:Rest<Dynamic>):T;
/**
Generates instance field access for reading on `object`
**/
static function field<T>(object:AsVar<T>, fieldName:String):Dynamic;
/**
Generates instance field access for reading on `object`
**/
@:deprecated("php.Syntax.getField() is deprecated. Use php.Syntax.field() instead.")
static function getField<T>(object:AsVar<T>, fieldName:String):Dynamic;
/**
Generates instance field access for writing on `object`
**/
static function setField<T>(object:AsVar<T>, fieldName:String, value:Dynamic):Void;
/**
Generates static field access for reading on `className`
**/
static function getStaticField(className:AsVar<EitherType<Class<Dynamic>, String>>, fieldName:String):Dynamic;
/**
Generates static field access for writing on `object`
**/
static function setStaticField(object:AsVar<EitherType<Class<Dynamic>, String>>, fieldName:String, value:Dynamic):Void;
/**
Generates a call to instance method: `$object->{$methodName}(<args>)`
**/
static function call<T>(object:AsVar<T>, methodName:String, args:Rest<Dynamic>):Dynamic;
/**
Generates a call to static method: `$className::{$methodName}(<args>)`
**/
static function staticCall(className:AsVar<EitherType<Class<Dynamic>, String>>, methodName:String, args:Rest<Dynamic>):Dynamic;
/**
```haxe
Syntax.arrayDecl(arg1, arg2, arg3);
```
Generates native array declaration:
```haxe
[$arg1, $arg2, $arg3]
```
**/
@:pure
static function arrayDecl<T>(args:Rest<T>):NativeIndexedArray<T>;
/**
```haxe
Syntax.customArrayDecl([v1 => v2, v3 => v4]);
```
Generates native array declaration:
```haxe
[$v1 => $v2, $v3 => $v4]
```
**/
macro static function customArrayDecl<T>(decl:haxe.macro.Expr):haxe.macro.Expr.ExprOf<php.NativeArray>;
/**
```haxe
Syntax.assocDecl({field1:'first', field2:2}});
```
Generates native associative array declaration:
```haxe
["field1" => "first", "field2" => 2];
```
This method is not recursive.
Accepts object declarations only.
That means you can't pass an object stored in a variable to this method like `Syntax.assocDecl(someVar)`.
Use `php.Lib.associativeArrayOfObject(someVar)` instead.
**/
@:pure
static function assocDecl<T:{}>(?arg:T):NativeAssocArray<Dynamic>;
/**
Don't let compiler to optimize away local var passed to this method.
**/
static function keepVar(localVar:Rest<Dynamic>):Void;
/**
Adds `...` operator before `args`
**/
static inline function splat(args:EitherType<NativeArray, Traversable>):Rest<Dynamic> {
return code('...{0}', args);
}
/**
Add errors suppression operator `@` before `expression`
**/
static function suppress<T>(expression:T):T;
/**
Generates `clone $value`.
@see http://php.net/manual/en/language.oop5.cloning.php
**/
static inline function clone<T>(value:T):T {
return Syntax.code('(clone {0})', value);
}
/**
Generates `yield $value`.
@see http://php.net/manual/en/language.generators.syntax.php
**/
static inline function yield(value:Dynamic):Dynamic {
return Syntax.code('yield {0}', value);
}
/**
Generates `yield $key => $value`.
@see http://php.net/manual/en/language.generators.syntax.php
**/
static inline function yieldPair(key:Dynamic, value:Dynamic):Dynamic {
return Syntax.code('yield {0} => {1}', key, value);
}
/**
Generates `yield for $value`.
@see http://php.net/manual/en/language.generators.syntax.php
**/
static inline function yieldFrom(value:Dynamic):Dynamic {
return Syntax.code('yield from {0}', value);
}
}

View File

@ -0,0 +1,70 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.macro.Expr;
import haxe.macro.Context;
/**
Special extern class to support PHP language specifics.
Don't use these functions unless you are really sure what you are doing.
**/
@:noClosure
@:noPackageRestrict
class Syntax {
/**
```haxe
Syntax.customArrayDecl([v1 => v2, v3 => v4]);
```
Generates native array declaration:
```haxe
[$v1 => $v2, $v3 => $v4]
```
**/
macro static function customArrayDecl<T>(decl:Expr):ExprOf<php.NativeArray> {
function invalidExpr(pos:Position) {
Context.error('Invalid expression passed to php.Syntax.customArrayDecl()', pos);
return macro @:pos(decl.pos) new php.NativeArray();
}
switch decl.expr {
case EArrayDecl(items):
var placeholders = [];
var args = [];
for(i => e in items) {
switch e {
case macro $index => $value:
placeholders.push('{${i * 2}} => {${i * 2 + 1}}');
args.push(index);
args.push(value);
case _:
return invalidExpr(e.pos);
}
}
var code = '[${placeholders.join(', ')}]';
args.unshift(macro @:pos(decl.pos) $v{code});
return macro @:pos(decl.pos) (php.Syntax.codeDeref($a{args}):php.NativeArray);
case _:
return invalidExpr(decl.pos);
}
}
}

View File

@ -0,0 +1,38 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see http://php.net/manual/en/class.throwable.php
**/
@:native('Throwable')
extern interface Throwable {
function getPrevious():Throwable; // Returns previous Throwable
function getMessage():String; // message of the exception
function getCode():Int; // code of the exception
function getFile():String; // source filename
function getLine():Int; // source line
function getTrace():NativeIndexedArray<NativeAssocArray<Dynamic>>; // an array of the backtrace
function getTraceAsString():String; // formatted string of trace
@:phpMagic function __toString():String; // formatted string for display
}

View File

@ -0,0 +1,45 @@
/*
* Copyright (C)2005-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.extern.EitherType;
/**
@see https://www.php.net/manual/en/class.transliterator.php
**/
@:native("Transliterator")
extern class Transliterator {
@:phpClassConst static final FORWARD: Int;
@:phpClassConst static final REVERSE: Int;
var id: String;
static function create(id: String, ?direction: Int): Null<Transliterator>;
static function createFromRules(rules: String, ?direction: Int): Null<Transliterator>;
static function listIDs(): EitherType<Array<String>, Bool>;
function createInverse(): Null<Transliterator>;
function getErrorCode(): EitherType<Int, Bool>;
function getErrorMessage(): EitherType<String, Bool>;
function transliterate(subject: String, ?start: Int, ?end: Int): EitherType<String, Bool>;
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
/**
@see http://php.net/manual/en/class.traversable.php
**/
@:native('Traversable')
extern interface Traversable {}

View File

@ -0,0 +1,482 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package php;
import haxe.io.Bytes;
import haxe.ds.Map;
import php.Syntax.*;
import php.Global.*;
import php.SuperGlobal.*;
/**
This class is used for accessing the local Web server and the current
client request and information.
**/
@:deprecated('php.Web is deprecated and will be removed from standard library. See php.SuperGlobal and php.Global for alternatives.')
class Web {
/**
Returns the GET and POST parameters.
**/
public static function getParams():Map<String, String> {
#if force_std_separator
var h = Lib.hashOfAssociativeArray(_POST);
var params = getParamsString();
if (params == "")
return h;
for (p in ~/[;&]/g.split(params)) {
var a = p.split("=");
var n = a.shift();
h.set(StringTools.urlDecode(n), StringTools.urlDecode(a.join("=")));
}
return h;
#else
return Lib.hashOfAssociativeArray(array_merge(_GET, _POST));
#end
}
/**
Returns an Array of Strings built using GET / POST values.
If you have in your URL the parameters `a[]=foo;a[]=hello;a[5]=bar;a[3]=baz` then
`php.Web.getParamValues("a")` will return `["foo","hello",null,"baz",null,"bar"]`.
**/
public static function getParamValues(param:String):Array<String> {
var reg = new EReg("^" + param + "(\\[|%5B)([0-9]*?)(\\]|%5D)=(.*?)$", "");
var res = new Array<String>();
var explore = function(data:String) {
if (data == null || Global.strlen(data) == 0)
return;
for (part in data.split("&")) {
if (reg.match(part)) {
var idx = reg.matched(2);
var val = StringTools.urlDecode(reg.matched(4));
if (idx == "")
res.push(val);
else
res[Std.parseInt(idx)] = val;
}
}
}
explore(StringTools.replace(getParamsString(), ";", "&"));
explore(getPostData());
if (res.length == 0) {
var post:haxe.ds.StringMap<Dynamic> = Lib.hashOfAssociativeArray(_POST);
var data = post.get(param);
if (is_array(data)) {
foreach(data, function(key:Int, value:String) {
res[key] = value;
});
}
}
if (res.length == 0)
return null;
return res;
}
/**
Returns the local server host name.
**/
public static inline function getHostName():String {
return _SERVER['SERVER_NAME'];
}
/**
Surprisingly returns the client IP address.
**/
public static inline function getClientIP():String {
return _SERVER['REMOTE_ADDR'];
}
/**
Returns the original request URL (before any server internal redirections).
**/
public static function getURI():String {
var s:String = _SERVER['REQUEST_URI'];
return s.split("?")[0];
}
/**
Tell the client to redirect to the given url ("Location" header).
**/
public static function redirect(url:String) {
header("Location: " + url);
}
/**
Set an output header value. If some data have been printed, the headers have
already been sent so this will raise an exception.
**/
public static inline function setHeader(h:String, v:String) {
header('$h: $v');
}
/**
Set the HTTP return code. Same remark as `php.Web.setHeader()`.
See status code explanation here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
**/
public static function setReturnCode(r:Int) {
var code:String;
switch (r) {
case 100:
code = "100 Continue";
case 101:
code = "101 Switching Protocols";
case 200:
code = "200 OK";
case 201:
code = "201 Created";
case 202:
code = "202 Accepted";
case 203:
code = "203 Non-Authoritative Information";
case 204:
code = "204 No Content";
case 205:
code = "205 Reset Content";
case 206:
code = "206 Partial Content";
case 300:
code = "300 Multiple Choices";
case 301:
code = "301 Moved Permanently";
case 302:
code = "302 Found";
case 303:
code = "303 See Other";
case 304:
code = "304 Not Modified";
case 305:
code = "305 Use Proxy";
case 307:
code = "307 Temporary Redirect";
case 400:
code = "400 Bad Request";
case 401:
code = "401 Unauthorized";
case 402:
code = "402 Payment Required";
case 403:
code = "403 Forbidden";
case 404:
code = "404 Not Found";
case 405:
code = "405 Method Not Allowed";
case 406:
code = "406 Not Acceptable";
case 407:
code = "407 Proxy Authentication Required";
case 408:
code = "408 Request Timeout";
case 409:
code = "409 Conflict";
case 410:
code = "410 Gone";
case 411:
code = "411 Length Required";
case 412:
code = "412 Precondition Failed";
case 413:
code = "413 Request Entity Too Large";
case 414:
code = "414 Request-URI Too Long";
case 415:
code = "415 Unsupported Media Type";
case 416:
code = "416 Requested Range Not Satisfiable";
case 417:
code = "417 Expectation Failed";
case 500:
code = "500 Internal Server Error";
case 501:
code = "501 Not Implemented";
case 502:
code = "502 Bad Gateway";
case 503:
code = "503 Service Unavailable";
case 504:
code = "504 Gateway Timeout";
case 505:
code = "505 HTTP Version Not Supported";
default:
code = Std.string(r);
}
header("HTTP/1.1 " + code, true, r);
}
/**
Retrieve a client header value sent with the request.
**/
public static function getClientHeader(k:String):String {
return loadClientHeaders().get(str_replace('-', '_', strtoupper(k)));
}
private static var _clientHeaders:Map<String, String>;
/**
Based on https://github.com/ralouphie/getallheaders
**/
static function loadClientHeaders():Map<String, String> {
if (_clientHeaders != null)
return _clientHeaders;
_clientHeaders = new Map();
if (function_exists('getallheaders')) {
foreach(getallheaders(), function(key:String, value:Dynamic) {
_clientHeaders.set(str_replace('-', '_', strtoupper(key)), Std.string(value));
});
return _clientHeaders;
}
var copyServer = Syntax.assocDecl({
CONTENT_TYPE: 'Content-Type',
CONTENT_LENGTH: 'Content-Length',
CONTENT_MD5: 'Content-Md5'
});
foreach(_SERVER, function(key:String, value:Dynamic) {
if ((substr(key, 0, 5) : String) == 'HTTP_') {
key = substr(key, 5);
if (!isset(copyServer[key]) || !isset(_SERVER[key])) {
_clientHeaders[key] = Std.string(value);
}
} else if (isset(copyServer[key])) {
_clientHeaders[key] = Std.string(value);
}
});
if (!_clientHeaders.exists('AUTHORIZATION')) {
if (isset(_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
_clientHeaders['AUTHORIZATION'] = Std.string(_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
} else if (isset(_SERVER['PHP_AUTH_USER'])) {
var basic_pass = isset(_SERVER['PHP_AUTH_PW']) ? Std.string(_SERVER['PHP_AUTH_PW']) : '';
_clientHeaders['AUTHORIZATION'] = 'Basic ' + base64_encode(_SERVER['PHP_AUTH_USER'] + ':' + basic_pass);
} else if (isset(_SERVER['PHP_AUTH_DIGEST'])) {
_clientHeaders['AUTHORIZATION'] = Std.string(_SERVER['PHP_AUTH_DIGEST']);
}
}
return _clientHeaders;
}
/**
Retrieve all the client headers.
**/
public static function getClientHeaders():List<{value:String, header:String}> {
var headers = loadClientHeaders();
var result = new List();
for (key in headers.keys()) {
result.push({value: headers.get(key), header: key});
}
return result;
}
/**
Retrieve all the client headers as `haxe.ds.Map`.
**/
public static function getClientHeadersMap():Map<String, String> {
return loadClientHeaders().copy();
}
/**
Returns all the GET parameters `String`
**/
public static function getParamsString():String {
if (isset(_SERVER['QUERY_STRING']))
return _SERVER['QUERY_STRING'];
else
return "";
}
/**
Returns all the POST data. POST Data is always parsed as
being application/x-www-form-urlencoded and is stored into
the getParams hashtable. POST Data is maximimized to 256K
unless the content type is multipart/form-data. In that
case, you will have to use `php.Web.getMultipart()` or
`php.Web.parseMultipart()` methods.
**/
public static function getPostData():Null<String> {
var h = fopen("php://input", "r");
var bsize = 8192;
var max = 32;
var data:String = null;
var counter = 0;
while (!feof(h) && counter < max) {
data = Syntax.concat(data, fread(h, bsize));
counter++;
}
fclose(h);
return data;
}
/**
Returns an hashtable of all Cookies sent by the client.
Modifying the hashtable will not modify the cookie, use `php.Web.setCookie()`
instead.
**/
public static function getCookies():Map<String, String> {
return Lib.hashOfAssociativeArray(_COOKIE);
}
/**
Set a Cookie value in the HTTP headers. Same remark as `php.Web.setHeader()`.
**/
public static function setCookie(key:String, value:String, ?expire:Date, ?domain:String, ?path:String, ?secure:Bool, ?httpOnly:Bool) {
var t = expire == null ? 0 : Std.int(expire.getTime() / 1000.0);
if (path == null)
path = '/';
if (domain == null)
domain = '';
if (secure == null)
secure = false;
if (httpOnly == null)
httpOnly = false;
setcookie(key, value, t, path, domain, secure, httpOnly);
}
/**
Returns an object with the authorization sent by the client (Basic scheme only).
**/
public static function getAuthorization():{user:String, pass:String} {
if (!isset(_SERVER['PHP_AUTH_USER']))
return null;
return {user: _SERVER['PHP_AUTH_USER'], pass: _SERVER['PHP_AUTH_PW']};
}
/**
Get the current script directory in the local filesystem.
**/
public static inline function getCwd():String {
return dirname(_SERVER['SCRIPT_FILENAME']) + "/";
}
/**
Get the multipart parameters as an hashtable. The data
cannot exceed the maximum size specified.
**/
public static function getMultipart(maxSize:Int):Map<String, String> {
var h = new haxe.ds.StringMap();
var buf:StringBuf = null;
var curname = null;
parseMultipart(function(p, _) {
if (curname != null)
h.set(curname, buf.toString());
curname = p;
buf = new StringBuf();
maxSize -= Global.strlen(p);
if (maxSize < 0)
throw "Maximum size reached";
}, function(str, pos, len) {
maxSize -= len;
if (maxSize < 0)
throw "Maximum size reached";
buf.addSub(str.toString(), pos, len);
});
if (curname != null)
h.set(curname, buf.toString());
return h;
}
/**
Parse the multipart data. Call `onPart` when a new part is found
with the part name and the filename if present
and `onData` when some part data is readed. You can this way
directly save the data on hard drive in the case of a file upload.
**/
public static function parseMultipart(onPart:String->String->Void, onData:Bytes->Int->Int->Void):Void {
Syntax.foreach(_POST, function(key:String, value:Dynamic) {
onPart(key, "");
onData(Bytes.ofString(value), 0, strlen(value));
});
if (!isset(_FILES))
return;
Syntax.foreach(_FILES, function(part:String, data:NativeAssocArray<Dynamic>) {
function handleFile(tmp:String, file:String, err:Int) {
var fileUploaded = true;
if (err > 0) {
switch (err) {
case 1:
throw "The uploaded file exceeds the max size of " + ini_get('upload_max_filesize');
case 2:
throw "The uploaded file exceeds the max file size directive specified in the HTML form (max is" + ini_get('post_max_size') + ")";
case 3:
throw "The uploaded file was only partially uploaded";
case 4:
fileUploaded = false; // No file was uploaded
case 6:
throw "Missing a temporary folder";
case 7:
throw "Failed to write file to disk";
case 8:
throw "File upload stopped by extension";
}
}
if (fileUploaded) {
onPart(part, file);
if ("" != file) {
var h = fopen(tmp, "r");
var bsize = 8192;
while (!feof(h)) {
var buf:String = fread(h, bsize);
var size:Int = strlen(buf);
onData(Bytes.ofString(buf), 0, size);
}
fclose(h);
}
}
}
if (is_array(data['name'])) {
for (index in array_keys(data['name'])) {
handleFile(data['tmp_name'][index], data['name'][index], data['error'][index]);
};
} else {
handleFile(data['tmp_name'], data['name'], data['error']);
}
});
}
/**
Flush the data sent to the client. By default on Apache, outgoing data is buffered so
this can be useful for displaying some long operation progress.
**/
public static inline function flush():Void {
Global.flush();
}
/**
Get the HTTP method used by the client.
**/
public static function getMethod():String {
if (isset(_SERVER['REQUEST_METHOD']))
return _SERVER['REQUEST_METHOD'];
else
return null;
}
public static var isModNeko(default, null):Bool;
static function __init__() {
isModNeko = !Lib.isCli();
}
}

View File

@ -0,0 +1,63 @@
<?php
/**
* Polyfills for some functions, which are required by Haxe-generated code, but not available in PHP 7.0.
* No Haxe-generated code is available at this point.
* No code should be executed from this file.
* Symbols declarations are the only code allowed here.
*/
namespace { //Namespace declaration is required because this file is included under non-root namespace.
/**
* @see http://php.net/manual/en/function.mb-chr.php
*/
if(!function_exists('mb_chr')) {
function mb_chr($code, $encoding = null) {
if($encoding && $encoding !== 'UTF-8') {
throw new Exception("$encoding is not supported in mb_chr() polyfill.");
}
if (0x80 > $code %= 0x200000) {
$s = chr($code);
} elseif (0x800 > $code) {
$s = chr(0xC0 | $code >> 6) . chr(0x80 | $code & 0x3F);
} elseif (0x10000 > $code) {
$s = chr(0xE0 | $code >> 12) . chr(0x80 | $code >> 6 & 0x3F) . chr(0x80 | $code & 0x3F);
} else {
$s = chr(0xF0 | $code >> 18) . chr(0x80 | $code >> 12 & 0x3F) . chr(0x80 | $code >> 6 & 0x3F) . chr(0x80 | $code & 0x3F);
}
return $s;
}
}
/**
* @see http://php.net/manual/en/function.mb-ord.php
*/
if(!function_exists('mb_ord')) {
function mb_ord($s, $encoding = null) {
if($encoding && $encoding !== 'UTF-8') {
throw new Exception("$encoding is not supported in mb_ord() polyfill.");
}
$code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0;
if (0xF0 <= $code) {
return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80;
}
if (0xE0 <= $code) {
return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80;
}
if (0xC0 <= $code) {
return (($code - 0xC0) << 6) + $s[2] - 0x80;
}
return $code;
}
}
/**
* @see http://php.net/manual/en/function.mb-scrub.php
*/
if(!function_exists('mb_scrub')) {
function mb_scrub($s, $encoding = null) {
$encoding = null === $encoding ? mb_internal_encoding() : $encoding;
return mb_convert_encoding($s, $encoding, $encoding);
}
}
}

View File

@ -0,0 +1,300 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.*;
import php.ArrayIterator as NativeArrayIterator;
import haxe.iterators.ArrayKeyValueIterator;
using php.Global;
@:coreApi
final class Array<T> implements ArrayAccess<Int, T> implements IteratorAggregate<T> implements Countable implements JsonSerializable<NativeIndexedArray<T>> {
public var length(default, null):Int;
var arr:NativeIndexedArray<T>;
public function new() {
arr = new NativeIndexedArray<T>();
length = 0;
}
public function concat(a:Array<T>):Array<T> {
return wrap(Global.array_merge(arr, a.arr));
}
public inline function copy():Array<T> {
return Syntax.clone(this);
}
public inline function filter(f:T->Bool):Array<T> {
var result = Syntax.arrayDecl();
for(item in arr) {
if (f(item)) {
result.push(item);
}
}
return wrap(result);
}
public inline function contains(x:T):Bool {
return indexOf(x) != -1;
}
public function indexOf(x:T, ?fromIndex:Int):Int {
if (fromIndex == null && !Boot.isHxClosure(x) && !Boot.isNumber(x)) {
var index = Global.array_search(x, arr, true);
if (index == false) {
return -1;
} else {
return index;
}
}
if (fromIndex == null) {
fromIndex = 0;
} else {
if (fromIndex < 0)
fromIndex += length;
if (fromIndex < 0)
fromIndex = 0;
}
while (fromIndex < length) {
if (arr[fromIndex] == x)
return fromIndex;
fromIndex++;
}
return -1;
}
public function insert(pos:Int, x:T):Void {
length++;
Global.array_splice(arr, pos, 0, Syntax.arrayDecl(x));
}
@:ifFeature("dynamic_read.iterator", "anon_optional_read.iterator", "anon_read.iterator")
public inline function iterator():haxe.iterators.ArrayIterator<T> {
return new haxe.iterators.ArrayIterator(this);
}
@:keep
public inline function keyValueIterator():ArrayKeyValueIterator<T> {
return new ArrayKeyValueIterator(this);
}
public function join(sep:String):String {
return Global.implode(sep, Global.array_map(Syntax.nativeClassName(Boot) + '::stringify', arr));
}
public function lastIndexOf(x:T, ?fromIndex:Int):Int {
if (fromIndex == null || fromIndex >= length)
fromIndex = length - 1;
if (fromIndex < 0)
fromIndex += length;
while (fromIndex >= 0) {
if (arr[fromIndex] == x)
return fromIndex;
fromIndex--;
}
return -1;
}
public inline function map<S>(f:T->S):Array<S> {
var result = Syntax.arrayDecl();
for(item in arr) {
result.push(f(item));
}
return wrap(result);
}
public inline function pop():Null<T> {
if (length > 0)
length--;
return Global.array_pop(arr);
}
public inline function push(x:T):Int {
arr[length++] = x;
return length;
}
public function remove(x:T):Bool {
var result = false;
for(index in 0...length) {
if (arr[index] == x) {
Global.array_splice(arr, index, 1);
length--;
result = true;
break;
}
}
return result;
}
public inline function reverse():Void {
arr = Global.array_reverse(arr);
}
public inline function shift():Null<T> {
if (length > 0)
length--;
return Global.array_shift(arr);
}
public function slice(pos:Int, ?end:Int):Array<T> {
if (pos < 0)
pos += length;
if (pos < 0)
pos = 0;
if (end == null) {
return wrap(Global.array_slice(arr, pos));
} else {
if (end < 0)
end += length;
if (end <= pos) {
return [];
} else {
return wrap(Global.array_slice(arr, pos, end - pos));
}
}
}
public inline function sort(f:T->T->Int):Void {
arr.usort(f);
}
public function splice(pos:Int, len:Int):Array<T> {
if (len < 0)
return [];
var result = wrap(Global.array_splice(arr, pos, len));
length -= result.length;
return result;
}
public inline function unshift(x:T):Void {
length = Global.array_unshift(arr, x);
}
public function toString():String {
return inline Boot.stringifyNativeIndexedArray(arr);
}
public function resize(len:Int):Void {
if (length < len) {
arr = Global.array_pad(arr, len, null);
} else if (length > len) {
Global.array_splice(arr, len, length - len);
}
length = len;
}
@:noCompletion @:keep
@:php.attribute('\\ReturnTypeWillChange')
function offsetExists(offset:Int):Bool {
return offset < length;
}
@:noCompletion @:keep
@:php.attribute('\\ReturnTypeWillChange')
function offsetGet(offset:Int):Ref<T> {
try {
return arr[offset];
} catch (e:Dynamic) {
return null;
}
}
@:noCompletion @:keep
@:php.attribute('\\ReturnTypeWillChange')
function offsetSet(offset:Int, value:T):Void {
if (length <= offset) {
for(i in length...offset + 1) {
arr[i] = null;
}
length = offset + 1;
}
arr[offset] = value;
Syntax.code("return {0}", value);
}
@:noCompletion @:keep
@:php.attribute('\\ReturnTypeWillChange')
function offsetUnset(offset:Int):Void {
if (offset >= 0 && offset < length) {
Global.array_splice(arr, offset, 1);
--length;
}
}
@:noCompletion @:keep
@:php.attribute('\\ReturnTypeWillChange')
private function getIterator():Traversable {
return new NativeArrayIterator(arr);
}
@:noCompletion @:keep
@:native('count') //to not interfere with `Lambda.count`
@:php.attribute('\\ReturnTypeWillChange')
private function _hx_count():Int {
return length;
}
@:noCompletion @:keep
@:php.attribute('\\ReturnTypeWillChange')
function jsonSerialize():NativeIndexedArray<T> {
return arr;
}
static function wrap<T>(arr:NativeIndexedArray<T>):Array<T> {
var a = new Array();
a.arr = arr;
a.length = Global.count(arr);
return a;
}
}
/**
Following interfaces are required to make `Array` mimic native arrays for usage
from a 3rd party PHP code.
**/
@:native('ArrayAccess')
private extern interface ArrayAccess<K, V> {
private function offsetExists(offset:K):Bool;
private function offsetGet(offset:K):V;
private function offsetSet(offset:K, value:V):Void;
private function offsetUnset(offset:K):Void;
}
@:native('JsonSerializable')
private extern interface JsonSerializable<T> {
private function jsonSerialize():T;
}
@:native('IteratorAggregate')
private extern interface IteratorAggregate<T> extends Traversable {
private function getIterator():Traversable;
}
@:native('Countable')
private extern interface Countable {
@:native('count') //to not interfere with `Lambda.count`
private function _hx_count():Int;
}

View File

@ -0,0 +1,140 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.Global.*;
import php.Syntax.*;
@:coreApi final class Date {
private var __t:Float;
public function new(year:Int, month:Int, day:Int, hour:Int, min:Int, sec:Int):Void {
__t = mktime(hour, min, sec, month + 1, day, year);
}
public function getTime():Float {
return __t * 1000.0;
}
private function getPhpTime():Float {
return __t;
}
public function getFullYear():Int {
return int(date("Y", int(__t)));
}
public function getMonth():Int {
var m:Int = int(date("n", int(__t)));
return -1 + m;
}
public function getDate():Int {
return int(date("j", int(__t)));
}
public function getHours():Int {
return int(date("G", int(__t)));
}
public function getMinutes():Int {
return int(date("i", int(__t)));
}
public function getSeconds():Int {
return int(date("s", int(__t)));
}
public function getDay():Int {
return int(date("w", int(__t)));
}
public function getUTCFullYear():Int {
return int(gmdate("Y", int(__t)));
}
public function getUTCMonth():Int {
var m:Int = int(gmdate("n", int(__t)));
return -1 + m;
}
public function getUTCDate():Int {
return int(gmdate("j", int(__t)));
}
public function getUTCHours():Int {
return int(gmdate("G", int(__t)));
}
public function getUTCMinutes():Int {
return int(gmdate("i", int(__t)));
}
public function getUTCSeconds():Int {
return int(gmdate("s", int(__t)));
}
public function getUTCDay():Int {
return int(gmdate("w", int(__t)));
}
public function getTimezoneOffset():Int {
return -Std.int(int(date("Z", int(__t))) / 60);
}
public function toString():String {
return date("Y-m-d H:i:s", int(__t));
}
public static function now():Date {
return fromPhpTime(round(microtime(true), 3));
}
static function fromPhpTime(t:Float):Date {
var d = new Date(2000, 1, 1, 0, 0, 0);
d.__t = t;
return d;
}
public static function fromTime(t:Float):Date {
var d = new Date(2000, 1, 1, 0, 0, 0);
d.__t = t / 1000;
return d;
}
public static function fromString(s:String):Date {
switch (s.length) {
case 8: // hh:mm:ss
var k = s.split(":");
return Date.fromTime(Std.parseInt(k[0]) * 3600000. + Std.parseInt(k[1]) * 60000. + Std.parseInt(k[2]) * 1000.);
case 10: // YYYY-MM-DD
var k = s.split("-");
return new Date(Std.parseInt(k[0]), Std.parseInt(k[1]) - 1, Std.parseInt(k[2]), 0, 0, 0);
case 19: // YYYY-MM-DD hh:mm:ss
var k = s.split(" ");
var y = k[0].split("-");
var t = k[1].split(":");
return new Date(Std.parseInt(y[0]), Std.parseInt(y[1]) - 1, Std.parseInt(y[2]), Std.parseInt(t[0]), Std.parseInt(t[1]), Std.parseInt(t[2]));
default:
throw "Invalid date format : " + s;
}
}
}

View File

@ -0,0 +1,179 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import haxe.extern.EitherType;
import php.*;
@:coreApi final class EReg {
var r:Dynamic;
var last:String;
var global:Bool;
var pattern:String;
var options:String;
var re:String;
var reUnicode(get, never):String;
var matches:NativeIndexedArray<NativeIndexedArray<EitherType<Int, String>>>;
public function new(r:String, opt:String):Void {
this.pattern = r;
options = Global.str_replace('g', '', opt);
global = options != opt;
options = Global.str_replace('u', '', options);
this.re = '"' + Global.str_replace('"', '\\"', r) + '"' + options;
}
public function match(s:String):Bool {
return matchFromByte(s, 0);
}
inline function matchFromByte(s:String, bytesOffset:Int):Bool {
var p = Global.preg_match(reUnicode, s, matches, Const.PREG_OFFSET_CAPTURE, bytesOffset);
if (p == false) {
handlePregError();
p = Global.preg_match(re, s, matches, Const.PREG_OFFSET_CAPTURE);
}
if ((p : Int) > 0) {
last = s;
} else {
last = null;
}
return (p : Int) > 0;
}
function handlePregError():Void {
var e = Global.preg_last_error();
if (e == Const.PREG_INTERNAL_ERROR) {
throw 'EReg: internal PCRE error';
} else if (e == Const.PREG_BACKTRACK_LIMIT_ERROR) {
throw 'EReg: backtrack limit';
} else if (e == Const.PREG_RECURSION_LIMIT_ERROR) {
throw 'EReg: recursion limit';
} else if (e == Const.PREG_JIT_STACKLIMIT_ERROR) {
throw 'failed due to limited JIT stack space';
}
// else if(e == Const.PREG_BAD_UTF8_ERROR) {
// throw 'EReg: malformed UTF8';
// } else if(e == Const.PREG_BAD_UTF8_OFFSET_ERROR) {
// throw 'EReg: the offset didn\'t correspond to the begin of a valid UTF-8 code point';
// }
}
public function matched(n:Int):String {
if (matches == null || n < 0)
throw "EReg::matched";
// we can't differentiate between optional groups at the end of a match
// that have not been matched and invalid groups
if (n >= Global.count(matches))
return null;
if ((matches[n][1] : Int) < 0)
return null;
return matches[n][0];
}
public function matchedLeft():String {
if (Global.count(matches) == 0)
throw "No string matched";
return Global.substr(last, 0, matches[0][1]);
}
public function matchedRight():String {
if (Global.count(matches) == 0)
throw "No string matched";
var x:Int = (matches[0][1] : Int) + Global.strlen(matches[0][0]);
return Global.substr(last, x);
}
public function matchedPos():{pos:Int, len:Int} {
return {
pos: Global.mb_strlen(Global.substr(last, 0, matches[0][1])),
len: Global.mb_strlen(matches[0][0])
};
}
public function matchSub(s:String, pos:Int, len:Int = -1):Bool {
var subject = len < 0 ? s : s.substr(0, pos + len);
var p = Global.preg_match(reUnicode, subject, matches, Const.PREG_OFFSET_CAPTURE, pos);
if (p == false) {
handlePregError();
p = Global.preg_match(re, subject, matches, Const.PREG_OFFSET_CAPTURE, pos);
}
if ((p : Int) > 0) {
last = s;
} else {
last = null;
}
return (p : Int) > 0;
}
public function split(s:String):Array<String> {
var parts:EitherType<Bool, NativeArray> = Global.preg_split(reUnicode, s, (global ? -1 : 2));
if (parts == false) {
handlePregError();
parts = Global.preg_split(re, s, (global ? -1 : 2));
}
return @:privateAccess Array.wrap(cast parts);
}
public function replace(s:String, by:String):String {
by = Global.str_replace("\\$", "\\\\$", by);
by = Global.str_replace("$$", "\\$", by);
if (!Global.preg_match('/\\\\([^?].*?\\\\)/', re)) {
by = Global.preg_replace('/\\$(\\d+)/', '\\$\\1', by);
}
var result = Global.preg_replace(reUnicode, by, s, global ? -1 : 1);
if (result == null) {
handlePregError();
result = Global.preg_replace(re, by, s, global ? -1 : 1);
}
return result;
}
public function map(s:String, f:EReg->String):String {
if(!matchFromByte(s, 0)) {
return s;
}
var result = '';
var bytesOffset = 0;
var bytesTotal = Global.strlen(s);
do {
result += Global.substr(s, bytesOffset, matches[0][1] - bytesOffset);
result += f(this);
bytesOffset = matches[0][1];
if(matches[0][0] == '') {
result += Global.mb_substr(Global.substr(s, bytesOffset), 0, 1);
bytesOffset++;
} else {
bytesOffset += Global.strlen(matches[0][0]);
}
} while(global && bytesOffset < bytesTotal && matchFromByte(s, bytesOffset));
result += Global.substr(s, bytesOffset);
return result;
}
public static inline function escape(s:String):String {
return Global.preg_quote(s);
}
inline function get_reUnicode():String {
return Syntax.concat(re, 'u');
}
}

View File

@ -0,0 +1,101 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.Global;
import php.Const;
import php.Syntax;
@:coreApi class Math {
public static var PI(default, null):Float = Const.M_PI;
public static var NaN(default, null):Float = Const.NAN;
public static var POSITIVE_INFINITY(default, null):Float = Const.INF;
public static var NEGATIVE_INFINITY(default, null):Float = -Const.INF;
public static inline function abs(v:Float):Float
return Global.abs(v);
public static inline function min(a:Float, b:Float):Float
return isNaN(a) || isNaN(b) ? NaN : Global.min(a, b);
public static inline function max(a:Float, b:Float):Float
return isNaN(a) || isNaN(b) ? NaN : Global.max(a, b);
public static inline function sin(v:Float):Float
return Global.sin(v);
public static inline function cos(v:Float):Float
return Global.cos(v);
public static inline function atan2(y:Float, x:Float):Float
return Global.atan2(y, x);
public static inline function tan(v:Float):Float
return Global.tan(v);
public static inline function exp(v:Float):Float
return Global.exp(v);
public static inline function log(v:Float):Float
return Global.log(v);
public static inline function sqrt(v:Float):Float
return Global.sqrt(v);
public static inline function round(v:Float):Int
return Syntax.int(Global.floor(v + 0.5));
public static inline function floor(v:Float):Int
return Syntax.int(Global.floor(v));
public static inline function ceil(v:Float):Int
return Syntax.int(Global.ceil(v));
public static inline function atan(v:Float):Float
return Global.atan(v);
public static inline function asin(v:Float):Float
return Global.asin(v);
public static inline function acos(v:Float):Float
return Global.acos(v);
public static inline function pow(v:Float, exp:Float):Float
return Syntax.exp(v, exp);
public static inline function random():Float
return Global.mt_rand() / Global.mt_getrandmax();
public static inline function isNaN(f:Float):Bool
return Global.is_nan(f);
public static inline function isFinite(f:Float):Bool
return Global.is_finite(f);
public static inline function fround(v:Float):Float
return Global.floor(v + 0.5);
public static inline function ffloor(v:Float):Float
return Global.floor(v);
public static inline function fceil(v:Float):Float
return Global.ceil(v);
}

View File

@ -0,0 +1,180 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.Boot;
import php.Syntax;
import php.Closure;
import php.Const;
import php.NativeAssocArray;
import haxe.Constraints;
using php.Global;
@:coreApi class Reflect {
public static function hasField(o:Dynamic, field:String):Bool {
if (!o.is_object())
return false;
if (o.property_exists(field))
return true;
if (Boot.isClass(o)) {
var phpClassName = Boot.castClass(o).phpClassName;
return Global.property_exists(phpClassName, field)
|| Global.method_exists(phpClassName, field)
|| Global.defined('$phpClassName::$field');
}
return false;
}
public static function field(o:Dynamic, field:String):Dynamic {
if (o.is_string()) {
return Syntax.field(Boot.dynamicString(o), field);
}
if (!o.is_object())
return null;
if (field == '' && Const.PHP_VERSION_ID < 70100) {
return Syntax.coalesce(Syntax.array(o)[field], null);
}
if (o.property_exists(field)) {
return Syntax.field(o, field);
}
if (o.method_exists(field)) {
return Boot.getInstanceClosure(o, field);
}
if (Boot.isClass(o)) {
var phpClassName = Boot.castClass(o).phpClassName;
if (Global.defined('$phpClassName::$field')) {
return Global.constant('$phpClassName::$field');
}
if (Global.property_exists(phpClassName, field)) {
return Syntax.field(o, field);
}
if (Global.method_exists(phpClassName, field)) {
return Boot.getStaticClosure(phpClassName, field);
}
}
return null;
}
public static function setField(o:Dynamic, field:String, value:Dynamic):Void {
Syntax.setField(o, field, value);
}
public static function getProperty(o:Dynamic, field:String):Dynamic {
if (o.is_object()) {
if (Boot.isClass(o)) {
var phpClassName = Boot.castClass(o).phpClassName;
if (Boot.hasGetter(phpClassName, field)) {
return Syntax.staticCall(phpClassName, 'get_$field');
}
} else if (Boot.hasGetter(Global.get_class(o), field)) {
return Syntax.call(o, 'get_$field');
}
}
return Reflect.field(o, field);
}
public static function setProperty(o:Dynamic, field:String, value:Dynamic):Void {
if (o.is_object()) {
if (Boot.hasSetter(Global.get_class(o), field)) {
Syntax.call(o, 'set_$field', value);
} else {
Syntax.setField(o, field, value);
}
}
}
public static function callMethod(o:Dynamic, func:Function, args:Array<Dynamic>):Dynamic {
return Global.call_user_func_array(func, @:privateAccess args.arr);
}
public static function fields(o:Dynamic):Array<String> {
if (Global.is_object(o)) {
return @:privateAccess Array.wrap(Global.get_object_vars(o).array_keys());
}
return [];
}
public static inline function isFunction(f:Dynamic):Bool {
return Boot.isFunction(f);
}
public static function compare<T>(a:T, b:T):Int {
if (a == b)
return 0;
if (Global.is_string(a)) {
return Global.strcmp(cast a, cast b);
} else {
return ((cast a) > (cast b) ? 1 : -1);
}
}
public static function compareMethods(f1:Dynamic, f2:Dynamic):Bool {
if (Boot.isHxClosure(f1) && Boot.isHxClosure(f2)) {
return f1.equals(f2);
} else {
return f1 == f2;
}
}
public static function isObject(v:Dynamic):Bool {
if (Boot.isEnumValue(v)) {
return false;
} else {
return v.is_object() || v.is_string();
}
}
public static inline function isEnumValue(v:Dynamic):Bool {
return Boot.isEnumValue(v);
}
public static function deleteField(o:Dynamic, field:String):Bool {
if (hasField(o, field)) {
Global.unset(Syntax.field(o, field));
return true;
} else {
return false;
}
}
public static function copy<T>(o:Null<T>):Null<T> {
if (Boot.isAnon(o)) {
return Syntax.clone(o);
} else {
return null;
}
}
@:overload(function(f:Array<Dynamic>->Void):Dynamic {})
public static function makeVarArgs(f:Array<Dynamic>->Dynamic):Dynamic {
return function() {
return Global.call_user_func(f, @:privateAccess Array.wrap(Global.func_get_args()));
}
}
}

View File

@ -0,0 +1,100 @@
import php.Boot;
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.Global;
import php.Const;
import php.Syntax;
@:coreApi class Std {
@:deprecated('Std.is is deprecated. Use Std.isOfType instead.')
public static inline function is(v:Dynamic, t:Dynamic):Bool {
return isOfType(v, t);
}
public static inline function isOfType(v:Dynamic, t:Dynamic):Bool {
return Boot.isOfType(v, t);
}
public static inline function downcast<T:{}, S:T>(value:T, c:Class<S>):S {
return Boot.isOfType(value, cast c) ? cast value : null;
}
@:deprecated('Std.instance() is deprecated. Use Std.downcast() instead.')
public static inline function instance<T:{}, S:T>(value:T, c:Class<S>):S {
return Boot.isOfType(value, cast c) ? cast value : null;
}
public static function string(s:Dynamic):String {
return Boot.stringify(s);
}
public static inline function int(x:Float):Int {
return Syntax.int(x);
}
public static function parseInt(x:String):Null<Int> {
if (Global.is_numeric(x)) {
return Global.intval(x, 10);
} else {
x = Global.ltrim(x);
var firstCharIndex = (x.charAt(0) == '-' ? 1 : 0);
var firstCharCode = x.charCodeAt(firstCharIndex);
if (!isDigitCode(firstCharCode)) {
return null;
}
var secondChar = x.charAt(firstCharIndex + 1);
if (secondChar == 'x' || secondChar == 'X') {
return Global.intval(x, 0);
} else {
return Global.intval(x, 10);
}
}
}
public static function parseFloat(x:String):Float {
var result = Global.floatval(x);
if (result != 0)
return result;
x = Global.ltrim(x);
var firstCharIndex = (x.charAt(0) == '-' ? 1 : 0);
var charCode = x.charCodeAt(firstCharIndex);
if (charCode == '.'.code) {
charCode = x.charCodeAt(firstCharIndex + 1);
}
if (isDigitCode(charCode)) {
return 0.0;
} else {
return Const.NAN;
}
}
public static inline function random(x:Int):Int {
return x <= 1 ? 0 : Global.mt_rand(0, x - 1);
}
static inline function isDigitCode(charCode:Null<Int>):Bool {
return charCode != null && charCode >= '0'.code && charCode <= '9'.code;
}
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.*;
@:coreApi extern class String {
var length(default, null):Int;
@:pure function new(string:String):Void;
@:pure @:runtime inline function toUpperCase():String {
return Global.mb_strtoupper(this);
}
@:pure @:runtime inline function toLowerCase():String {
return Global.mb_strtolower(this);
}
@:pure @:runtime inline function charAt(index:Int):String {
return index < 0 ? '' : Global.mb_substr(this, index, 1);
}
@:pure function charCodeAt(index:Int):Null<Int>;
@:pure function indexOf(str:String, ?startIndex:Int):Int;
@:pure function lastIndexOf(str:String, ?startIndex:Int):Int;
@:pure function split(delimiter:String):Array<String>;
@:pure @:runtime inline function substr(pos:Int, ?len:Int):String {
return Global.mb_substr(this, pos, len);
}
@:pure function substring(startIndex:Int, ?endIndex:Int):String;
@:pure @:runtime inline function toString():String {
return this;
}
@:pure @:runtime static inline function fromCharCode(code:Int):String {
return Global.mb_chr(code);
}
}

View File

@ -0,0 +1,62 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.Global;
import php.Syntax;
@:coreApi class StringBuf {
private var b:String;
public var length(get, never):Int;
public function new():Void {
b = "";
}
inline function get_length():Int {
return b.length;
}
public function add<T>(x:T):Void {
if (x == null) {
b = Syntax.concat(b, 'null');
} else if (Global.is_bool(x)) {
b = Syntax.concat(b, ((x : Dynamic) ? 'true' : 'false'));
} else if (Global.is_string(x)) {
b = Syntax.concat(b, cast x);
} else {
b += x;
}
}
public inline function addSub(s:String, pos:Int, ?len:Int):Void {
b += s.substr(pos, len);
}
public inline function addChar(c:Int):Void {
b += String.fromCharCode(c);
}
public inline function toString():String {
return b;
}
}

View File

@ -0,0 +1,159 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.*;
import haxe.iterators.StringIterator;
import haxe.iterators.StringKeyValueIterator;
@:coreApi class StringTools {
public inline static function urlEncode(s:String):String {
return Global.rawurlencode(s);
}
public inline static function urlDecode(s:String):String {
return Global.urldecode(s);
}
public inline static function htmlEscape(s:String, ?quotes:Bool):String {
return Global.htmlspecialchars(s, (quotes ? Const.ENT_QUOTES | Const.ENT_HTML401 : Const.ENT_NOQUOTES));
}
public inline static function htmlUnescape(s:String):String {
return Global.htmlspecialchars_decode(s, Const.ENT_QUOTES);
}
public inline static function contains(s:String, value:String):Bool {
return s.indexOf(value) != -1;
}
public static function startsWith(s:String, start:String):Bool {
return start == '' || Global.substr(s, 0, Global.strlen(start)) == start;
}
public static function endsWith(s:String, end:String):Bool {
return end == '' || Global.substr(s, -Global.strlen(end)) == end;
}
public static function isSpace(s:String, pos:Int):Bool {
var c = s.charCodeAt(pos);
return (c >= 9 && c <= 13) || c == 32;
}
public inline static function ltrim(s:String):String {
return Global.ltrim(s);
}
public inline static function rtrim(s:String):String {
return Global.rtrim(s);
}
public inline static function trim(s:String):String {
return Global.trim(s);
}
public static function rpad(s:String, c:String, l:Int):String {
var cLength = c.length;
var sLength = s.length;
if (cLength == 0 || sLength >= l)
return s;
var padLength = l - sLength;
var padCount = Syntax.int(padLength / cLength);
if (padCount > 0) {
var result = Global.str_pad(s, Global.strlen(s) + padCount * Global.strlen(c), c, Const.STR_PAD_RIGHT);
return (padCount * cLength >= padLength) ? result : Syntax.concat(result, c);
} else {
return Syntax.concat(s, c);
}
}
public static function lpad(s:String, c:String, l:Int):String {
var cLength = c.length;
var sLength = s.length;
if (cLength == 0 || sLength >= l)
return s;
var padLength = l - sLength;
var padCount = Syntax.int(padLength / cLength);
if (padCount > 0) {
var result = Global.str_pad(s, Global.strlen(s) + padCount * Global.strlen(c), c, Const.STR_PAD_LEFT);
return (padCount * cLength >= padLength) ? result : Syntax.concat(c, result);
} else {
return Syntax.concat(c, s);
}
}
public static function replace(s:String, sub:String, by:String):String {
if (sub == '') {
return Global.implode(by, Global.preg_split('//u', s, -1, Const.PREG_SPLIT_NO_EMPTY));
}
return Global.str_replace(sub, by, s);
}
public static function hex(n:Int, ?digits:Int):String {
var s = Global.dechex(n);
var len = 8;
if (Global.strlen(s) > (null == digits ? len : (len = digits > len ? digits : len)))
s = s.substr(-len);
else if (digits != null)
s = lpad(s, '0', digits);
return s.toUpperCase();
}
public static function fastCodeAt(s:String, index:Int):Int {
var char:NativeString = (index == 0 ? s : Global.mb_substr(s, index, 1));
if (char == '')
return 0;
return Boot.unsafeOrd(char);
}
public static function unsafeCodeAt(s:String, index:Int):Int {
var char:NativeString = (index == 0 ? s : Global.mb_substr(s, index, 1));
return Boot.unsafeOrd(char);
}
public static inline function iterator(s:String):StringIterator {
return new StringIterator(s);
}
public static inline function keyValueIterator(s:String):StringKeyValueIterator {
return new StringKeyValueIterator(s);
}
@:noUsing public static inline function isEof(c:Int):Bool {
return c == 0;
}
@:noCompletion
@:deprecated('StringTools.quoteUnixArg() is deprecated. Use haxe.SysTools.quoteUnixArg() instead.')
public static function quoteUnixArg(argument:String):String {
return inline haxe.SysTools.quoteUnixArg(argument);
}
@:noCompletion
@:deprecated('StringTools.winMetaCharacters is deprecated. Use haxe.SysTools.winMetaCharacters instead.')
public static var winMetaCharacters:Array<Int> = cast haxe.SysTools.winMetaCharacters;
@:noCompletion
@:deprecated('StringTools.quoteWinArg() is deprecated. Use haxe.SysTools.quoteWinArg() instead.')
public static function quoteWinArg(argument:String, escapeMetaCharacters:Bool):String {
return inline haxe.SysTools.quoteWinArg(argument, escapeMetaCharacters);
}
}

View File

@ -0,0 +1,157 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.*;
import sys.io.FileOutput;
import sys.io.FileInput;
import haxe.SysTools;
@:coreApi class Sys {
/** Environment variables set by `Sys.putEnv()` */
static var customEnvVars = new NativeAssocArray<String>();
public static inline function print(v:Dynamic):Void {
Global.echo(Std.string(v));
}
public static inline function println(v:Dynamic):Void {
Global.echo(Std.string(v) + Const.PHP_EOL);
}
public static function args():Array<String> {
if (Global.array_key_exists('argv', SuperGlobal._SERVER)) {
return @:privateAccess Array.wrap(Global.array_slice(SuperGlobal._SERVER['argv'], 1));
} else {
return [];
}
}
public static function getEnv(s:String):String {
var value = Global.getenv(s);
return value == false ? null : value;
}
public static function putEnv(s:String, v:String):Void {
customEnvVars[s] = '$v'; // in case of `null` it should become `"null"`
Global.putenv('$s=$v');
}
public static inline function sleep(seconds:Float):Void {
return Global.usleep(Std.int(seconds * 1000000));
}
public static inline function setTimeLocale(loc:String):Bool {
return Global.setlocale(Const.LC_TIME, loc) != false;
}
public static function getCwd():String {
var cwd = Global.getcwd();
if (cwd == false)
return null;
var l = (cwd : String).substr(-1);
return (cwd : String) + (l == '/' || l == '\\' ? '' : '/');
}
public static inline function setCwd(s:String):Void {
Global.chdir(s);
}
public static function systemName():String {
var s = Global.php_uname('s');
var p = s.indexOf(" ");
return (p >= 0 ? s.substr(0, p) : s);
}
public static function command(cmd:String, ?args:Array<String>):Int {
if (args != null) {
switch (systemName()) {
case "Windows":
cmd = [
for (a in [StringTools.replace(cmd, "/", "\\")].concat(args))
SysTools.quoteWinArg(a, true)
].join(" ");
case _:
cmd = [cmd].concat(args).map(SysTools.quoteUnixArg).join(" ");
}
}
var result = Boot.deref(0);
Global.system(cmd, result);
return result;
}
public static inline function exit(code:Int):Void {
Global.exit(code);
}
public static inline function time():Float {
return Global.microtime(true);
}
public static function cpuTime():Float {
return time() - SuperGlobal._SERVER['REQUEST_TIME'];
}
@:deprecated("Use programPath instead") public static inline function executablePath():String {
return SuperGlobal._SERVER['SCRIPT_FILENAME'];
}
// It has to be initialized before any call to Sys.setCwd()...
static var _programPath = sys.FileSystem.fullPath(SuperGlobal._SERVER['SCRIPT_FILENAME']);
public static function programPath():String {
return _programPath;
}
public static function environment():Map<String, String> {
var env = SuperGlobal._SERVER;
Syntax.foreach(customEnvVars, function(name:String, value:String) {
env[name] = value;
});
return php.Lib.hashOfAssociativeArray(env);
}
public static function stdin():haxe.io.Input {
var p = Global.defined('STDIN') ? Const.STDIN : Global.fopen('php://stdin', 'r');
return @:privateAccess new FileInput(p);
}
public static function stdout():haxe.io.Output {
var p = Global.defined('STDOUT') ? Const.STDOUT : Global.fopen('php://stdout', 'w');
return @:privateAccess new FileOutput(p);
}
public static function stderr():haxe.io.Output {
var p = Global.defined('STDERR') ? Const.STDERR : Global.fopen('php://stderr', 'w');
return @:privateAccess new FileOutput(p);
}
public static function getChar(echo:Bool):Int {
var c = Global.fgetc(Const.STDIN);
if (c == false) {
return 0;
} else {
if (echo)
Global.echo(c);
return Global.ord(c);
}
}
}

View File

@ -0,0 +1,364 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import php.*;
import php.reflection.*;
import haxe.extern.EitherType;
using php.Global;
enum ValueType {
TNull;
TInt;
TFloat;
TBool;
TObject;
TFunction;
TClass(c:Class<Dynamic>);
TEnum(e:Enum<Dynamic>);
TUnknown;
}
@:coreApi class Type {
public static function getClass<T>(o:T):Class<T> {
if (Global.is_object(o) && !Boot.isClass(o) && !Boot.isEnumValue(o)) {
var cls = Boot.getClass(Global.get_class(cast o));
return (Boot.isAnon(o) ? null : cast cls);
} else if (Global.is_string(o)) {
return cast String;
} else {
return null;
}
}
public static function getEnum(o:EnumValue):Enum<Dynamic> {
if (o == null)
return null;
return cast Boot.getClass(Global.get_class(cast o));
}
public static function getSuperClass(c:Class<Dynamic>):Class<Dynamic> {
if (c == null)
return null;
var parentClass = try {
Global.get_parent_class((cast c).phpClassName);
} catch(e) {
return null;
}
if (!parentClass)
return null;
return cast Boot.getClass(parentClass);
}
public static function getClassName(c:Class<Dynamic>):String {
if (c == null)
return null;
return Boot.getHaxeName(cast c);
}
public static function getEnumName(e:Enum<Dynamic>):String {
return getClassName(cast e);
}
public static function resolveClass(name:String):Class<Dynamic> {
if (name == null)
return null;
switch (name) {
case 'Dynamic':
return cast Dynamic;
case 'Int':
return cast Int;
case 'Float':
return cast Float;
case 'Bool':
return cast Bool;
case 'String':
return String;
case 'Class':
return cast Class;
case 'Enum':
return cast Enum;
}
var phpClass = Boot.getPhpName(name);
if (!Global.class_exists(phpClass) && !Global.interface_exists(phpClass))
return null;
var hxClass = Boot.getClass(phpClass);
return cast hxClass;
}
public static function resolveEnum(name:String):Enum<Dynamic> {
if (name == null)
return null;
if (name == 'Bool')
return cast Bool;
var phpClass = Boot.getPhpName(name);
if (!Global.class_exists(phpClass))
return null;
var hxClass = Boot.getClass(phpClass);
return cast hxClass;
}
public static function createInstance<T>(cl:Class<T>, args:Array<Dynamic>):T {
if (String == cast cl)
return args[0];
var nativeArgs:NativeArray = @:privateAccess args.arr;
return Syntax.construct(Syntax.nativeClassName(cl), Syntax.splat(nativeArgs));
}
public static function createEmptyInstance<T>(cl:Class<T>):T {
if (String == cast cl)
return cast '';
if (Array == cast cl)
return cast [];
var reflection = new ReflectionClass(Syntax.nativeClassName(cl));
return reflection.newInstanceWithoutConstructor();
}
public static function createEnum<T>(e:Enum<T>, constr:String, ?params:Array<Dynamic>):T {
if (e == null || constr == null)
return null;
var phpName = Syntax.nativeClassName(e);
if (!Global.in_array(constr, Syntax.staticCall(phpName, "__hx__list"))) {
throw 'No such constructor $constr';
}
var paramsCounts:NativeAssocArray<Int> = Syntax.staticCall(phpName, "__hx__paramsCount");
if ((params == null && paramsCounts[constr] != 0) || (params != null && params.length != paramsCounts[constr])) {
throw 'Provided parameters count does not match expected parameters count';
}
if (params == null) {
return Syntax.staticCall(phpName, constr);
} else {
var nativeArgs:NativeArray = @:privateAccess params.arr;
return Syntax.staticCall(phpName, constr, Syntax.splat(nativeArgs));
}
}
public static function createEnumIndex<T>(e:Enum<T>, index:Int, ?params:Array<Dynamic>):T {
if (e == null || index == null)
return null;
var phpName = Syntax.nativeClassName(e);
var constructors:NativeIndexedArray<String> = Syntax.staticCall(phpName, "__hx__list");
if (index < 0 || index >= Global.count(constructors)) {
throw '$index is not a valid enum constructor index';
}
var constr = constructors[index];
var paramsCounts:NativeAssocArray<Int> = Syntax.staticCall(phpName, "__hx__paramsCount");
if ((params == null && paramsCounts[constr] != 0) || (params != null && params.length != paramsCounts[constr])) {
throw 'Provided parameters count does not match expected parameters count';
}
if (params == null) {
return Syntax.staticCall(phpName, constr);
} else {
var nativeArgs:NativeArray = @:privateAccess params.arr;
return Syntax.staticCall(phpName, constr, Syntax.splat(nativeArgs));
}
}
public static function getInstanceFields(c:Class<Dynamic>):Array<String> {
if (c == null)
return null;
if (c == String) {
return [
'substr', 'charAt', 'charCodeAt', 'indexOf', 'lastIndexOf', 'split', 'toLowerCase', 'toUpperCase', 'toString', 'length'
];
}
var reflection = new ReflectionClass(Syntax.nativeClassName(c));
var methods = new NativeArray();
for (method in reflection.getMethods()) {
if (!method.isStatic()) {
var name = method.getName();
if (!isServiceFieldName(name)) {
methods.array_push(name);
}
}
}
var properties = new NativeArray();
for (property in reflection.getProperties()) {
if (!property.isStatic()) {
var name = property.getName();
if (!isServiceFieldName(name)) {
properties.array_push(name);
}
}
}
properties = Global.array_diff(properties, methods);
var fields = Global.array_merge(properties, methods);
return @:privateAccess Array.wrap(fields);
}
public static function getClassFields(c:Class<Dynamic>):Array<String> {
if (c == null)
return null;
if (c == String)
return ['fromCharCode'];
var phpName = Syntax.nativeClassName(c);
var reflection = new ReflectionClass(phpName);
var methods = new NativeArray();
for (m in reflection.getMethods(ReflectionMethod.IS_STATIC)) {
var name = m.getName();
if (!isServiceFieldName(name) && phpName == m.getDeclaringClass().getName()) {
methods.array_push(name);
}
}
var properties = new NativeArray();
for (p in reflection.getProperties(ReflectionProperty.IS_STATIC)) {
var name = p.getName();
if (!isServiceFieldName(name) && phpName == p.getDeclaringClass().getName()) {
properties.array_push(name);
}
}
properties = Global.array_diff(properties, methods);
var fields = Global.array_merge(properties, methods);
return @:privateAccess Array.wrap(fields);
}
public static function getEnumConstructs(e:Enum<Dynamic>):Array<String> {
if (e == null)
return null;
return @:privateAccess Array.wrap(Syntax.call(e, '__hx__list'));
}
public static function typeof(v:Dynamic):ValueType {
if (v == null)
return TNull;
if (v.is_object()) {
if (Reflect.isFunction(v))
return TFunction;
if (Std.isOfType(v, StdClass))
return TObject;
if (Boot.isClass(v))
return TObject;
var hxClass = Boot.getClass(Global.get_class(v));
if (Boot.isEnumValue(v))
return TEnum(cast hxClass);
return TClass(cast hxClass);
}
if (v.is_bool())
return TBool;
if (v.is_int())
return TInt;
if (v.is_float())
return TFloat;
if (v.is_string())
return TClass(String);
return TUnknown;
}
public static function enumEq<T:EnumValue>(a:T, b:T):Bool {
if (Syntax.strictEqual(a, b))
return true;
if (a == null || b == null)
return false;
try {
if (!Syntax.instanceof(a, (Global.get_class(cast b):String)))
return false;
if (enumIndex(a) != enumIndex(b))
return false;
var aParams:NativeIndexedArray<Dynamic> = Boot.castEnumValue(a).params;
var bParams:NativeIndexedArray<Dynamic> = Boot.castEnumValue(b).params;
for (i in 0...Global.count(aParams)) {
// enums
if (Boot.isEnumValue(aParams[i])) {
if (!enumEq(aParams[i], bParams[i])) {
return false;
}
// everything else
} else if (!inline Boot.equal(aParams[i], bParams[i])) {
return false;
}
}
return true;
} catch (e:Dynamic) {
return false;
}
}
public inline static function enumConstructor(e:EnumValue):String {
return Boot.castEnumValue(e).tag;
}
public inline static function enumParameters(e:EnumValue):Array<Dynamic> {
return @:privateAccess Array.wrap(Boot.castEnumValue(e).params);
}
public inline static function enumIndex(e:EnumValue):Int {
return Boot.castEnumValue(e).index;
}
public static function allEnums<T>(e:Enum<T>):Array<T> {
if (e == null)
return null;
var phpName = Syntax.nativeClassName(e);
var result = [];
for (name in getEnumConstructs(e)) {
var reflection = new ReflectionMethod(phpName, name);
if (reflection.getNumberOfParameters() == 0) {
result.push(reflection.invoke(null));
}
}
return result;
}
/**
check if specified `name` is a special field name generated by compiler.
**/
static inline function isServiceFieldName(name:String):Bool {
return (name == '__construct' || name.indexOf('__hx_') == 0);
}
}

View File

@ -0,0 +1,103 @@
package haxe;
import php.Throwable;
import php.NativeAssocArray;
import php.NativeIndexedArray;
@:coreApi
class Exception extends NativeException {
public var message(get,never):String;
public var stack(get,never):CallStack;
public var previous(get,never):Null<Exception>;
public var native(get,never):Any;
@:noCompletion var __exceptionStack:Null<CallStack>;
@:noCompletion var __nativeException:Throwable;
@:noCompletion var __skipStack:Int = 0;
@:noCompletion var __previousException:Null<Exception>;
static function caught(value:Any):Exception {
if(Std.isOfType(value, Exception)) {
return value;
} else if(Std.isOfType(value, Throwable)) {
return new Exception((value:Throwable).getMessage(), null, value);
} else {
return new ValueException(value, null, value);
}
}
static function thrown(value:Any):Any {
if(Std.isOfType(value, Exception)) {
return (value:Exception).native;
} else if(Std.isOfType(value, Throwable)) {
return value;
} else {
var e = new ValueException(value);
e.__skipStack = 1;
return e;
}
}
public function new(message:String, ?previous:Exception, ?native:Any) {
super(message, 0, previous);
this.__previousException = previous;
if(native != null && Std.isOfType(native, Throwable)) {
__nativeException = native;
} else {
__nativeException = cast this;
}
}
function unwrap():Any {
return __nativeException;
}
public function toString():String {
return message;
}
public function details():String {
return inline CallStack.exceptionToString(this);
}
function get_message():String {
return this.getMessage();
}
function get_previous():Null<Exception> {
return __previousException;
}
final function get_native():Any {
return __nativeException;
}
function get_stack():CallStack {
return switch __exceptionStack {
case null:
var nativeTrace = NativeStackTrace.complementTrace(__nativeException.getTrace(), native);
__exceptionStack = NativeStackTrace.toHaxe(nativeTrace, __skipStack);
case s: s;
}
}
}
@:dox(hide)
@:noCompletion
@:native('Exception')
private extern class NativeException {
@:noCompletion private function new(?message:String, ?code:Int, ?previous:NativeException):Void;
@:noCompletion private var code:Int;
@:noCompletion private var file:String;
@:noCompletion private var line:Int;
@:noCompletion final private function getPrevious():Throwable;
@:noCompletion private function getMessage():String;
@:noCompletion private function getCode():Int;
@:noCompletion private function getFile():String;
@:noCompletion private function getLine():Int;
@:noCompletion private function getTrace():NativeIndexedArray<NativeAssocArray<Dynamic>>;
@:noCompletion private function getTraceAsString():String;
@:noCompletion @:phpMagic private function __toString():String;
}

View File

@ -0,0 +1,114 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe;
import php.*;
import haxe.format.JsonPrinter;
@:coreApi
class Json {
public static inline function parse(text:String):Dynamic {
#if haxeJSON
return haxe.format.JsonParser.parse(text);
#else
return phpJsonDecode(text);
#end
}
public static inline function stringify(value:Dynamic, ?replacer:(key:Dynamic, value:Dynamic) -> Dynamic, ?space:String):String {
#if haxeJSON
return JsonPrinter.print(value, replacer, space);
#else
return phpJsonEncode(value, replacer, space);
#end
}
static function phpJsonDecode(json:String):Dynamic {
var value = Global.json_decode(json);
if (value == null && Global.json_last_error() != Const.JSON_ERROR_NONE) {
throw Global.json_last_error_msg();
}
return convertAfterDecode(value);
}
static function convertAfterDecode(value:Dynamic):Dynamic {
if (Global.is_object(value)) {
var result = new NativeAssocArray();
var data = Syntax.array(value);
Syntax.foreach(data, function(fieldName:String, fieldValue:Dynamic) {
result[fieldName] = convertAfterDecode(fieldValue);
});
return Boot.createAnon(result);
}
if (Global.is_array(value)) {
var result = new NativeIndexedArray();
Syntax.foreach(value, function(index:Int, item:Dynamic) {
result[index] = convertAfterDecode(item);
});
return @:privateAccess Array.wrap(result);
}
return value;
}
static function phpJsonEncode(value:Dynamic, ?replacer:(key:Dynamic, value:Dynamic) -> Dynamic, ?space:String):String {
if (null != replacer || null != space) {
return JsonPrinter.print(value, replacer, space);
}
var json = Global.json_encode(convertBeforeEncode(value));
if (Global.json_last_error() != Const.JSON_ERROR_NONE) {
return throw Global.json_last_error_msg();
}
return json;
}
static function convertBeforeEncode(value:Dynamic):Dynamic {
if (Std.isOfType(value, Array)) {
var result = new NativeIndexedArray();
Syntax.foreach(value.arr, function(index:Int, item:Dynamic) {
result[index] = convertBeforeEncode(item);
});
return result;
}
if (Global.is_object(value)) {
var result = {};
Syntax.foreach(value, function(fieldName:String, fieldValue:Dynamic) {
Syntax.setField(result, fieldName, convertBeforeEncode(fieldValue));
});
return result;
}
if (Global.is_float(value) && !Global.is_finite(value)) {
return null;
}
return value;
}
}

View File

@ -0,0 +1,115 @@
package haxe;
import php.*;
import haxe.CallStack.StackItem;
private typedef NativeTrace = NativeIndexedArray<NativeAssocArray<Dynamic>>;
/**
Do not use manually.
**/
@:dox(hide)
@:noCompletion
@:allow(haxe.Exception)
class NativeStackTrace {
/**
If defined this function will be used to transform call stack entries.
@param String - generated php file name.
@param Int - Line number in generated file.
**/
static public var mapPosition:String->Int->Null<{?source:String, ?originalLine:Int}>;
static var lastExceptionTrace:Null<NativeTrace>;
@:ifFeature('haxe.NativeStackTrace.exceptionStack')
static public function saveStack(e:Throwable) {
var nativeTrace = e.getTrace();
// Reduce exception stack to the place where exception was caught
var currentTrace = Global.debug_backtrace(Const.DEBUG_BACKTRACE_IGNORE_ARGS);
var count = Global.count(currentTrace);
for (i in -(count - 1)...1) {
var exceptionEntry:NativeAssocArray<Dynamic> = Global.end(nativeTrace);
if (!Global.isset(exceptionEntry['file']) || !Global.isset(currentTrace[-i]['file'])) {
Global.array_pop(nativeTrace);
} else if (currentTrace[-i]['file'] == exceptionEntry['file'] && currentTrace[-i]['line'] == exceptionEntry['line']) {
Global.array_pop(nativeTrace);
} else {
break;
}
}
// Remove arguments from trace to avoid blocking some objects from GC
var count = Global.count(nativeTrace);
for (i in 0...count) {
nativeTrace[i]['args'] = new NativeArray();
}
lastExceptionTrace = complementTrace(nativeTrace, e);
}
static public inline function callStack():NativeTrace {
return Global.debug_backtrace(Const.DEBUG_BACKTRACE_IGNORE_ARGS);
}
static public function exceptionStack():NativeTrace {
return lastExceptionTrace == null ? new NativeIndexedArray() : lastExceptionTrace;
}
static public function toHaxe(native:NativeTrace, skip:Int = 0):Array<StackItem> {
var result = [];
var count = Global.count(native);
for (i in 0...count) {
if(skip > i) {
continue;
}
var entry = native[i];
var item = null;
if (i + 1 < count) {
var next = native[i + 1];
if (!Global.isset(next['function']))
next['function'] = '';
if (!Global.isset(next['class']))
next['class'] = '';
if ((next['function'] : String).indexOf('{closure}') >= 0) {
item = LocalFunction();
} else if (Global.strlen(next['class']) > 0 && Global.strlen(next['function']) > 0) {
var cls = Boot.getClassName(next['class']);
item = Method(cls, next['function']);
}
}
if (Global.isset(entry['file'])) {
if (mapPosition != null) {
var pos = mapPosition(entry['file'], entry['line']);
if (pos != null && pos.source != null && pos.originalLine != null) {
entry['file'] = pos.source;
entry['line'] = pos.originalLine;
}
}
result.push(FilePos(item, entry['file'], entry['line']));
} else if (item != null) {
result.push(item);
}
}
return result;
}
static function complementTrace(nativeTrace:NativeTrace, e:Throwable):NativeTrace {
var thrownAt = new NativeAssocArray<Dynamic>();
thrownAt['function'] = '';
thrownAt['line'] = e.getLine();
thrownAt['file'] = e.getFile();
thrownAt['class'] = '';
thrownAt['args'] = new NativeArray();
Global.array_unshift(nativeTrace, thrownAt);
return nativeTrace;
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe;
import php.*;
import haxe.io.Bytes;
import haxe.crypto.Base64;
@:coreApi
class Resource {
static function cleanName(name:String):String {
return ~/[\\\/:?"*<>|]/.replace(name, '_');
}
static function getDir():String {
var pathToRoot = '/../..';
#if php_prefix
pathToRoot += '/..';
for (i in 0...Global.substr_count(Boot.getPrefix(), '\\')) {
pathToRoot += '/..';
}
#end
return Global.dirname(Const.__FILE__) + pathToRoot + "/res";
}
@:access(haxe.io.Path.escape)
static function getPath(name:String):String {
return getDir() + '/' + haxe.io.Path.escape(name);
}
@:access(haxe.io.Path.unescape)
public static function listNames():Array<String> {
var a = sys.FileSystem.readDirectory(getDir());
if (a[0] == '.')
a.shift();
if (a[0] == '..')
a.shift();
return a.map(function(s) return haxe.io.Path.unescape(s));
}
public static function getString(name:String):String {
var path = getPath(name);
return if (!sys.FileSystem.exists(path))
null;
else
sys.io.File.getContent(path);
}
public static function getBytes(name:String):haxe.io.Bytes {
var path = getPath(name);
return if (!sys.FileSystem.exists(path))
null;
else
sys.io.File.getBytes(path);
}
}

View File

@ -0,0 +1,50 @@
package haxe;
import php.*;
import haxe.iterators.RestIterator;
import haxe.iterators.RestKeyValueIterator;
private typedef NativeRest<T> = NativeIndexedArray<T>;
@:coreApi
@:semantics(value)
abstract Rest<T>(NativeRest<T>) {
public var length(get,never):Int;
inline function get_length():Int
return Global.count(this);
@:from
static public inline function of<T>(array:Array<T>):Rest<T>
return new Rest(@:privateAccess array.arr);
inline function new(a:NativeIndexedArray<T>):Void
this = a;
@:arrayAccess inline function get(index:Int):T
return this[index];
@:to public inline function toArray():Array<T>
return @:privateAccess Array.wrap(this);
public inline function iterator():RestIterator<T>
return new RestIterator<T>(this);
public inline function keyValueIterator():RestKeyValueIterator<T>
return new RestKeyValueIterator<T>(this);
public inline function append(item:T):Rest<T> {
var result = this;
result.push(item);
return new Rest(result);
}
public inline function prepend(item:T):Rest<T> {
var result = this;
Global.array_unshift(result, item);
return new Rest(result);
}
public function toString():String {
return inline Boot.stringifyNativeIndexedArray(this);
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe;
import php.Global;
@:coreApi
@:deprecated('haxe.Utf8 is deprecated. Use UnicodeString instead.')
class Utf8 {
var __b:String;
public function new(?size:Int):Void {
__b = '';
}
public function addChar(c:Int):Void {
__b += uchr(c);
}
public function toString():String {
return __b;
}
public static function encode(s:String):String {
return Global.utf8_encode(s);
}
public static function decode(s:String):String {
return Global.utf8_decode(s);
}
public static function iter(s:String, chars:Int->Void):Void {
var len = length(s);
for (i in 0...len) {
chars(charCodeAt(s, i));
}
}
public static function charCodeAt(s:String, index:Int):Int {
return uord(sub(s, index, 1));
}
static function uchr(i:Int):String {
return Global.mb_convert_encoding(Global.pack('N', i), 'UTF-8', 'UCS-4BE');
}
static function uord(s:String):Int {
var c = Global.unpack('N', Global.mb_convert_encoding(s, 'UCS-4BE', 'UTF-8'));
return c[1];
}
public static function validate(s:String):Bool {
return Global.mb_check_encoding(s, enc);
}
public static function length(s:String):Int {
return Global.mb_strlen(s, enc);
}
public static function compare(a:String, b:String):Int {
return Global.strcmp(a, b);
}
public static function sub(s:String, pos:Int, len:Int):String {
return Global.mb_substr(s, pos, len, enc);
}
private static inline var enc = "UTF-8";
}

View File

@ -0,0 +1,75 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.crypto;
import php.Global.*;
import php.Syntax;
import php.NativeArray;
import haxe.io.Bytes;
class Base64 {
public static var CHARS(default, null) = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
public static var BYTES(default, null) = haxe.io.Bytes.ofString(CHARS);
public static var URL_CHARS(default, null) = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
public static var URL_BYTES(default, null) = haxe.io.Bytes.ofString(URL_CHARS);
static final NORMAL_62_63:NativeArray = Syntax.arrayDecl('+', '/');
static final URL_62_63:NativeArray = Syntax.arrayDecl('-', '_');
public static inline function encode(bytes:Bytes, complement = true):String {
var result = base64_encode(bytes.toString());
return (complement ? result : rtrim(result, "="));
}
public static inline function decode(str:String, complement = true):Bytes {
if (!complement) {
switch (strlen(str) % 3) {
case 1:
str += "==";
case 2:
str += "=";
default:
}
}
return Bytes.ofString(base64_decode(str, true));
}
public static inline function urlEncode(bytes:Bytes, complement = false):String {
var result = str_replace(NORMAL_62_63, URL_62_63, base64_encode(bytes.toString()));
return (complement ? result : rtrim(result, "="));
}
public static inline function urlDecode(str:String, complement = false):Bytes {
if (complement) {
switch (strlen(str) % 3) {
case 1:
str += "==";
case 2:
str += "=";
default:
}
}
return Bytes.ofString(base64_decode(str_replace(URL_62_63, NORMAL_62_63, str), true));
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.crypto;
import php.Global;
import haxe.io.Bytes;
class Md5 {
public static inline function encode(s:String):String {
return Global.md5(s);
}
public static inline function make(b:haxe.io.Bytes):haxe.io.Bytes {
return Bytes.ofData(Global.md5(b.getData(), true));
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.crypto;
import php.Global;
import haxe.io.Bytes;
class Sha1 {
public static inline function encode(s:String):String {
return Global.sha1(s);
}
public static inline function make(b:haxe.io.Bytes):haxe.io.Bytes {
return Bytes.ofData(Global.sha1(b.getData(), true));
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.crypto;
import php.Global;
import haxe.io.Bytes;
class Sha224 {
public static inline function encode(s:String):String {
return Global.hash('sha224', s);
}
public static function make(b:haxe.io.Bytes):haxe.io.Bytes {
return Bytes.ofData(Global.hash('sha224', b.getData(), true));
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.crypto;
import php.Global;
import haxe.io.Bytes;
class Sha256 {
public static inline function encode(s:String):String {
return Global.hash('sha256', s);
}
public static function make(b:haxe.io.Bytes):haxe.io.Bytes {
return Bytes.ofData(Global.hash('sha256', b.getData(), true));
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.ds;
import php.Syntax;
import php.Global;
import php.NativeArray;
import php.NativeIndexedArray;
@:coreApi class IntMap<T> implements haxe.Constraints.IMap<Int, T> {
var data:NativeIndexedArray<T>;
public function new():Void {
data = new NativeIndexedArray();
}
public inline function set(key:Int, value:T):Void {
data[key] = value;
}
public inline function get(key:Int):Null<T> {
return Syntax.coalesce(data[key], null);
}
public inline function exists(key:Int):Bool {
return Global.array_key_exists(key, data);
}
public function remove(key:Int):Bool {
if (Global.array_key_exists(key, data)) {
Global.unset(data[key]);
return true;
}
return false;
}
public inline function keys():Iterator<Int> {
return Global.array_keys(data).iterator();
}
@:ifFeature("dynamic_read.iterator", "anon_optional_read.iterator", "anon_read.iterator")
public inline function iterator():Iterator<T> {
return Global.array_values(data).iterator();
}
@:ifFeature("dynamic_read.keyValueIterator", "anon_optional_read.keyValueIterator", "anon_read.keyValueIterator")
public inline function keyValueIterator():KeyValueIterator<Int, T> {
return new haxe.iterators.MapKeyValueIterator(this);
}
public inline function copy():IntMap<T> {
return Syntax.clone(this);
}
public function toString():String {
var parts = new NativeArray();
Syntax.foreach(data, function(key:Int, value:T) {
Global.array_push(parts, '$key => ' + Std.string(value));
});
return '{' + Global.implode(', ', parts) + '}';
}
public inline function clear():Void {
data = new NativeIndexedArray();
}
}

View File

@ -0,0 +1,97 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.ds;
import php.*;
@:coreApi
class ObjectMap<K:{}, V> implements haxe.Constraints.IMap<K, V> {
var _keys:NativeAssocArray<K>;
var _values:NativeAssocArray<V>;
public function new():Void {
_keys = new NativeAssocArray();
_values = new NativeAssocArray();
}
public function set(key:K, value:V):Void {
var id = Global.spl_object_hash(key);
_keys[id] = key;
_values[id] = value;
}
public function get(key:K):Null<V> {
var id = Global.spl_object_hash(key);
return Global.isset(_values[id]) ? _values[id] : null;
}
public function exists(key:K):Bool {
return Global.array_key_exists(Global.spl_object_hash(key), _values);
}
public function remove(key:K):Bool {
var id = Global.spl_object_hash(key);
if (Global.array_key_exists(id, _values)) {
Global.unset(_keys[id], _values[id]);
return true;
} else {
return false;
}
}
public inline function keys():Iterator<K> {
return _keys.iterator();
}
@:ifFeature("dynamic_read.iterator", "anon_optional_read.iterator", "anon_read.iterator")
public inline function iterator():Iterator<V> {
return _values.iterator();
}
@:ifFeature("dynamic_read.keyValueIterator", "anon_optional_read.keyValueIterator", "anon_read.keyValueIterator")
public inline function keyValueIterator():KeyValueIterator<K, V> {
return new haxe.iterators.MapKeyValueIterator(this);
}
public inline function copy():ObjectMap<K, V> {
return Syntax.clone(this);
}
public function toString():String {
var s = "{";
var it = keys();
for (i in it) {
s += Std.string(i);
s += " => ";
s += Std.string(get(i));
if (it.hasNext())
s += ", ";
}
return s + "}";
}
public inline function clear():Void {
_keys = new NativeAssocArray();
_values = new NativeAssocArray();
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.ds;
import php.Syntax;
import php.Global;
import php.NativeArray;
import php.NativeAssocArray;
import haxe.Constraints;
@:coreApi class StringMap<T> implements IMap<String, T> {
private var data:NativeAssocArray<T>;
public inline function new():Void {
data = new NativeAssocArray();
}
public inline function set(key:String, value:T):Void {
data[key] = value;
}
public inline function get(key:String):Null<T> {
return Syntax.coalesce(data[key], null);
}
public inline function exists(key:String):Bool {
return Global.array_key_exists(key, data);
}
public function remove(key:String):Bool {
if (Global.array_key_exists(key, data)) {
Global.unset(data[key]);
return true;
} else {
return false;
}
}
public inline function keys():Iterator<String> {
return Global.array_map('strval', Global.array_keys(data)).iterator();
}
@:ifFeature("dynamic_read.iterator", "anon_optional_read.iterator", "anon_read.iterator")
public inline function iterator():Iterator<T> {
return data.iterator();
}
@:ifFeature("dynamic_read.keyValueIterator", "anon_optional_read.keyValueIterator", "anon_read.keyValueIterator")
public inline function keyValueIterator():KeyValueIterator<String, T> {
return new haxe.iterators.MapKeyValueIterator(this);
}
public inline function copy():StringMap<T> {
return Syntax.clone(this);
}
public function toString():String {
var parts = new NativeArray();
Syntax.foreach(data, function(key:String, value:T) {
Global.array_push(parts, '$key => ' + Std.string(value));
});
return '{' + Global.implode(', ', parts) + '}';
}
public inline function clear():Void {
data = new NativeAssocArray();
}
}

View File

@ -0,0 +1,133 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.ds;
import php.*;
private class PhpVectorData<T> {
public var length:Int;
public var data:NativeIndexedArray<T>;
public inline function new(length:Int) {
this.length = length;
data = new NativeIndexedArray();
}
}
private typedef VectorData<T> = PhpVectorData<T>;
abstract Vector<T>(VectorData<T>) {
public var length(get, never):Int;
public inline function new(length:Int) {
this = new VectorData(length);
}
@:op([]) public inline function get(index:Int):T {
return Syntax.coalesce(this.data[index], null);
}
@:op([]) public inline function set(index:Int, val:T):T {
return this.data[index] = val;
}
inline function get_length():Int {
return this.length;
}
public static function blit<T>(src:Vector<T>, srcPos:Int, dest:Vector<T>, destPos:Int, len:Int):Void {
if (src == dest) {
if (srcPos < destPos) {
var i = srcPos + len;
var j = destPos + len;
for (k in 0...len) {
i--;
j--;
src[j] = src[i];
}
} else if (srcPos > destPos) {
var i = srcPos;
var j = destPos;
for (k in 0...len) {
src[j] = src[i];
i++;
j++;
}
}
} else {
for (i in 0...len) {
dest[destPos + i] = src[srcPos + i];
}
}
}
public function toArray():Array<T> {
var result = [];
@:privateAccess result.length = length;
for (i in 0...length) {
@:privateAccess result.arr.push(get(i));
}
return result;
}
public inline function toData():VectorData<T> {
return this;
}
static public inline function fromData<T>(data:VectorData<T>):Vector<T> {
return cast data;
}
static public inline function fromArrayCopy<T>(array:Array<T>):Vector<T> {
var vectorData = new VectorData(array.length);
vectorData.data = @:privateAccess array.arr;
return cast vectorData;
}
public inline function copy<T>():Vector<T> {
return cast Syntax.clone(this);
}
public function join<T>(sep:String):String {
if (this.length == 0) {
return '';
}
var result = Std.string(get(0));
for (i in 1...this.length) {
result = Syntax.concat(result, Syntax.concat(sep, Std.string(get(i))));
}
return result;
}
public inline function map<S>(f:T->S):Vector<S> {
var result = new Vector(this.length);
Syntax.foreach(this.data, function(key:Int, value:T) {
result[key] = f(value);
});
return result;
}
public inline function sort<T>(f:T->T->Int):Void {
Global.usort(this.data, f);
}
}

View File

@ -0,0 +1,273 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.format;
import php.Syntax;
import php.Global;
import php.NativeString;
using haxe.format.JsonParser;
class JsonParser {
static public inline function parse(str:String):Dynamic {
return new JsonParser(str).doParse();
}
var str:NativeString;
var pos:Int;
function new(str:String) {
this.str = str;
this.pos = 0;
}
function doParse():Dynamic {
var result = parseRec();
var c;
while (!StringTools.isEof(c = nextChar())) {
switch (c) {
case ' '.code, '\r'.code, '\n'.code, '\t'.code:
// allow trailing whitespace
default:
invalidChar();
}
}
return result;
}
function parseRec():Dynamic {
while (true) {
var c = nextChar();
switch (c) {
case ' '.code, '\r'.code, '\n'.code, '\t'.code:
// loop
case '{'.code:
var obj = {}, field = null, comma:Null<Bool> = null;
while (true) {
var c = nextChar();
switch (c) {
case ' '.code, '\r'.code, '\n'.code, '\t'.code:
// loop
case '}'.code:
if (field != null || comma == false)
invalidChar();
return obj;
case ':'.code:
if (field == null)
invalidChar();
Reflect.setField(obj, field, parseRec());
field = null;
comma = true;
case ','.code:
if (comma) comma = false else invalidChar();
case '"'.code:
if (field != null || comma) invalidChar();
field = parseString();
default:
invalidChar();
}
}
case '['.code:
var arr = [], comma:Null<Bool> = null;
while (true) {
var c = nextChar();
switch (c) {
case ' '.code, '\r'.code, '\n'.code, '\t'.code:
// loop
case ']'.code:
if (comma == false) invalidChar();
return arr;
case ','.code:
if (comma) comma = false else invalidChar();
default:
if (comma) invalidChar();
pos--;
arr.push(parseRec());
comma = true;
}
}
case 't'.code:
var save = pos;
if (nextChar() != 'r'.code || nextChar() != 'u'.code || nextChar() != 'e'.code) {
pos = save;
invalidChar();
}
return true;
case 'f'.code:
var save = pos;
if (nextChar() != 'a'.code || nextChar() != 'l'.code || nextChar() != 's'.code || nextChar() != 'e'.code) {
pos = save;
invalidChar();
}
return false;
case 'n'.code:
var save = pos;
if (nextChar() != 'u'.code || nextChar() != 'l'.code || nextChar() != 'l'.code) {
pos = save;
invalidChar();
}
return null;
case '"'.code:
return parseString();
case '0'.code, '1'.code, '2'.code, '3'.code, '4'.code, '5'.code, '6'.code, '7'.code, '8'.code, '9'.code, '-'.code:
return parseNumber(c);
default:
invalidChar();
}
}
}
function parseString() {
var start = pos;
var buf:NativeString = null;
while (true) {
var c = nextChar();
if (c == '"'.code)
break;
if (c == '\\'.code) {
if (buf == null) {
buf = '';
}
buf = buf.addSub(str, start, pos - start - 1);
c = nextChar();
switch (c) {
case "r".code:
buf = Syntax.concat(buf, "\r");
case "n".code:
buf = Syntax.concat(buf, "\n");
case "t".code:
buf = Syntax.concat(buf, "\t");
case "b".code:
buf = Syntax.concat(buf, Global.chr(8));
case "f".code:
buf = Syntax.concat(buf, Global.chr(12));
case "/".code, '\\'.code, '"'.code:
buf = Syntax.concat(buf, Global.mb_chr(c));
case 'u'.code:
var uc = Std.parseInt("0x" + str.substr(pos, 4));
pos += 4;
buf = Syntax.concat(buf, Global.mb_chr(uc));
default:
throw "Invalid escape sequence \\" + String.fromCharCode(c) + " at position " + (pos - 1);
}
start = pos;
}
// ensure utf8 chars are not cut
else if (c >= 0x80) {
pos++;
if (c >= 0xFC)
pos += 4;
else if (c >= 0xF8)
pos += 3;
else if (c >= 0xF0)
pos += 2;
else if (c >= 0xE0)
pos++;
} else if (StringTools.isEof(c))
throw "Unclosed string";
}
if (buf == null) {
return str.substr(start, pos - start - 1);
} else {
return buf.addSub(str, start, pos - start - 1);
}
}
inline function parseNumber(c:Int):Dynamic {
var start = pos - 1;
var minus = c == '-'.code, digit = !minus, zero = c == '0'.code;
var point = false, e = false, pm = false, end = false;
while (true) {
c = nextChar();
switch (c) {
case '0'.code:
if (zero && !point)
invalidNumber(start);
if (minus) {
minus = false;
zero = true;
}
digit = true;
case '1'.code, '2'.code, '3'.code, '4'.code, '5'.code, '6'.code, '7'.code, '8'.code, '9'.code:
if (zero && !point)
invalidNumber(start);
if (minus)
minus = false;
digit = true;
zero = false;
case '.'.code:
if (minus || point || e)
invalidNumber(start);
digit = false;
point = true;
case 'e'.code, 'E'.code:
if (minus || zero || e)
invalidNumber(start);
digit = false;
e = true;
case '+'.code, '-'.code:
if (!e || pm)
invalidNumber(start);
digit = false;
pm = true;
default:
if (!digit)
invalidNumber(start);
pos--;
end = true;
}
if (end)
break;
}
var f = Std.parseFloat(str.substr(start, pos - start));
var i = Std.int(f);
return if (i == f) i else f;
}
inline function nextChar() {
return fastCodeAt(str, pos++);
}
function invalidChar() {
pos--; // rewind
throw "Invalid char " + fastCodeAt(str, pos) + " at position " + pos;
}
function invalidNumber(start:Int) {
throw "Invalid number at position " + start + ": " + str.substr(start, pos - start);
}
// TODO: rewrite the parser using a buffer instead of a string as the data source
static inline function fastCodeAt(s:NativeString, pos:Int):Int {
return pos >= Global.strlen(s) ? 0 : Global.ord(s[pos]);
}
static inline function substr(s:NativeString, pos:Int, ?length:Int):NativeString {
return Global.substr(s, pos, length);
}
static inline function addSub(buf:NativeString, s:NativeString, pos:Int, length:Int):NativeString {
return Syntax.concat(buf, Global.substr(s, pos, length));
}
}

View File

@ -0,0 +1,169 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.io;
import php.Global;
import php.Syntax;
class Bytes {
public var length(default, null):Int;
var b:BytesData;
function new(length:Int, b:BytesData):Void {
this.length = length;
this.b = b;
}
public inline function get(pos:Int):Int {
return b.get(pos);
}
public inline function set(pos:Int, v:Int):Void {
b.set(pos, v);
}
public inline function blit(pos:Int, src:Bytes, srcpos:Int, len:Int):Void {
if (pos < 0 || srcpos < 0 || len < 0 || pos + len > length || srcpos + len > src.length) {
throw Error.OutsideBounds;
} else {
b.blit(pos, src.b, srcpos, len);
}
}
public inline function fill(pos:Int, len:Int, value:Int):Void {
b.fill(pos, len, value);
}
public inline function sub(pos:Int, len:Int):Bytes {
if (pos < 0 || len < 0 || pos + len > length) {
throw Error.OutsideBounds;
} else {
return new Bytes(len, b.sub(pos, len));
}
}
public inline function compare(other:Bytes):Int {
return b.compare(other.b);
}
public function getDouble(pos:Int):Float {
return FPHelper.i64ToDouble(getInt32(pos), getInt32(pos + 4));
}
public function getFloat(pos:Int):Float {
var b = new haxe.io.BytesInput(this, pos, 4);
return b.readFloat();
}
public function setDouble(pos:Int, v:Float):Void {
var i = FPHelper.doubleToI64(v);
setInt32(pos, i.low);
setInt32(pos + 4, i.high);
}
public function setFloat(pos:Int, v:Float):Void {
setInt32(pos, FPHelper.floatToI32(v));
}
public inline function getUInt16(pos:Int):Int {
return get(pos) | (get(pos + 1) << 8);
}
public inline function setUInt16(pos:Int, v:Int):Void {
set(pos, v);
set(pos + 1, v >> 8);
}
public inline function getInt32(pos:Int):Int {
var v = get(pos) | (get(pos + 1) << 8) | (get(pos + 2) << 16) | (get(pos + 3) << 24);
return if (v & 0x80000000 != 0) v | 0x80000000 else v;
}
public inline function getInt64(pos:Int):haxe.Int64 {
return haxe.Int64.make(getInt32(pos + 4), getInt32(pos));
}
public inline function setInt32(pos:Int, v:Int):Void {
set(pos, v);
set(pos + 1, v >> 8);
set(pos + 2, v >> 16);
set(pos + 3, v >>> 24);
}
public inline function setInt64(pos:Int, v:haxe.Int64):Void {
setInt32(pos, v.low);
setInt32(pos + 4, v.high);
}
public inline function getString(pos:Int, len:Int, ?encoding:Encoding):String {
if (pos < 0 || len < 0 || pos + len > length) {
throw Error.OutsideBounds;
} else {
// no need to handle encoding, because PHP strings are binary safe.
return b.getString(pos, len);
}
}
@:deprecated("readString is deprecated, use getString instead")
@:noCompletion
public inline function readString(pos:Int, len:Int):String {
return getString(pos, len);
}
public function toString():String {
return b;
}
public inline function toHex():String {
return php.Global.bin2hex(b.toString());
}
public inline function getData():BytesData {
return b;
}
public static function alloc(length:Int):Bytes {
return new Bytes(length, BytesData.alloc(length));
}
public static inline function ofString(s:String, ?encoding:Encoding):Bytes {
return new Bytes(php.Global.strlen(s), s);
}
public static inline function ofData(b:BytesData):Bytes {
return new Bytes(b.length, b);
}
public static function ofHex(s:String):Bytes {
var len = Global.strlen(s);
if ((len & 1) != 0)
throw "Not a hex string (odd number of digits)";
var b:String = php.Global.hex2bin(s);
return new Bytes(Global.strlen(b), b);
}
public inline static function fastGet(b:BytesData, pos:Int):Int {
return b.get(pos);
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.io;
import php.*;
import haxe.io.Error;
class BytesBuffer {
var b:NativeString;
public var length(get, never):Int;
public function new() {
b = "";
}
public inline function addByte(byte:Int) {
b = Syntax.concat(b, Global.chr(byte));
}
public inline function add(src:Bytes) {
b = Syntax.concat(b, src.getData().toNativeString());
}
public inline function addString(v:String, ?encoding:Encoding) {
b = Syntax.concat(b, v);
}
public function addInt32(v:Int) {
addByte(v & 0xFF);
addByte((v >> 8) & 0xFF);
addByte((v >> 16) & 0xFF);
addByte(v >>> 24);
}
public function addInt64(v:haxe.Int64) {
addInt32(v.low);
addInt32(v.high);
}
public inline function addFloat(v:Float) {
addInt32(FPHelper.floatToI32(v));
}
public inline function addDouble(v:Float) {
addInt64(FPHelper.doubleToI64(v));
}
public inline function addBytes(src:Bytes, pos:Int, len:Int) {
if (pos < 0 || len < 0 || pos + len > src.length) {
throw Error.OutsideBounds;
} else {
b = Syntax.concat(b, src.getData().sub(pos, len).toString());
}
}
public function getBytes():Bytes {
var bytes = @:privateAccess new Bytes(length, b);
b = null;
return bytes;
}
inline function get_length():Int {
return Global.strlen(b);
}
}

View File

@ -0,0 +1,98 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.io;
import php.*;
using php.Syntax;
typedef BytesData = BytesDataAbstract;
private class Container {
public var s:NativeString;
public inline function new(s:NativeString)
this.s = s;
}
private abstract BytesDataAbstract(Container) from Container to Container {
public var length(get, never):Int;
public static inline function alloc(length:Int):BytesDataAbstract {
return Global.str_repeat(Global.chr(0), length);
}
@:arrayAccess
public inline function get(pos:Int):Int {
return Global.ord(this.s[pos]);
}
@:arrayAccess
public inline function set(index:Int, val:Int):Void {
this.s[index] = Global.chr(val);
}
public inline function compare(other:BytesDataAbstract):Int {
return Syntax.spaceship(this.s, (other : Container).s);
}
public inline function getString(pos:Int, len:Int):String {
return Global.substr(this.s, pos, len);
}
public inline function sub(pos:Int, len:Int):BytesDataAbstract {
return (Global.substr(this.s, pos, len) : String);
}
public inline function blit(pos:Int, src:BytesDataAbstract, srcpos:Int, len:Int):Void {
this.s = Global.substr(this.s, 0, pos).concat(Global.substr(src, srcpos, len)).concat(Global.substr(this.s, pos + len));
}
public inline function fill(pos:Int, len:Int, value:Int):Void {
this.s = Global.substr(this.s, 0, pos).concat(Global.str_repeat(Global.chr(value), len)).concat(Global.substr(this.s, pos + len));
}
inline function get_length():Int {
return Global.strlen(this.s);
}
@:from
static inline function fromNativeString(s:NativeString):BytesDataAbstract {
return new Container(s);
}
@:to
public inline function toNativeString():NativeString {
return this.s;
}
@:from
static inline function fromString(s:String):BytesDataAbstract {
return new Container(s);
}
@:to
public inline function toString():String {
return this.s;
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.io;
class BytesInput extends Input {
var b:BytesData;
var pos:Int;
var len:Int;
var totlen:Int;
public var position(get, set):Int;
public var length(get, never):Int;
public function new(b:Bytes, ?pos:Int, ?len:Int) {
if (pos == null)
pos = 0;
if (len == null)
len = b.length - pos;
if (pos < 0 || len < 0 || pos + len > b.length)
throw Error.OutsideBounds;
this.b = b.getData();
this.pos = pos;
this.len = len;
this.totlen = len;
}
inline function get_position():Int {
return pos;
}
inline function get_length():Int {
return totlen;
}
function set_position(p:Int):Int {
if (p < 0)
p = 0;
else if (p > length)
p = length;
len = totlen - p;
return pos = p;
}
public override function readByte():Int {
if (len == 0)
throw new Eof();
--len;
return b[pos++];
}
public override function readBytes(buf:Bytes, pos, len):Int {
if (pos < 0 || len < 0 || pos + len > buf.length)
throw Error.OutsideBounds;
if (this.len == 0 && len > 0)
throw new Eof();
if (this.len < len)
len = this.len;
buf.getData().blit(pos, b, this.pos, len);
this.pos += len;
this.len -= len;
return len;
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.io;
class BytesOutput extends Output {
var b:BytesBuffer;
public var length(get, never):Int;
public function new() {
b = new BytesBuffer();
}
override function writeByte(c) {
b.addByte(c);
}
override function writeBytes(buf:Bytes, pos, len):Int {
b.addBytes(buf, pos, len);
return len;
}
public function getBytes():Bytes {
return b.getBytes();
}
inline function get_length():Int {
return b.length;
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.io;
import php.*;
class FPHelper {
static var isLittleEndian:Bool = Global.unpack('S', '\x01\x00')[1] == 1;
static var i64tmp = Int64.ofInt(0);
public static inline function i32ToFloat(i:Int):Float {
return Global.unpack('f', Global.pack('l', i))[1];
}
public static inline function floatToI32(f:Float):Int {
return Global.unpack('l', Global.pack('f', f))[1];
}
public static inline function i64ToDouble(low:Int, high:Int):Float {
return Global.unpack('d', Global.pack('ii', isLittleEndian ? low : high, isLittleEndian ? high : low))[1];
}
public static function doubleToI64(v:Float):Int64 {
var a = Global.unpack(isLittleEndian ? 'V2' : 'N2', Global.pack('d', v));
var i64 = i64tmp;
@:privateAccess i64.set_low(a[isLittleEndian ? 1 : 2]);
@:privateAccess i64.set_high(a[isLittleEndian ? 2 : 1]);
return i64;
}
}

View File

@ -0,0 +1,66 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.iterators;
import php.Global.*;
import php.NativeString;
class StringIteratorUnicode {
var byteOffset:Int = 0;
var totalBytes:Int;
var s:NativeString;
public inline function new(s:String) {
this.s = s;
totalBytes = strlen(s);
}
public inline function hasNext() {
return byteOffset < totalBytes;
}
public inline function next() {
var code = ord(s[byteOffset]);
if (code < 0xC0) {
byteOffset++;
} else if (code < 0xE0) {
code = ((code - 0xC0) << 6) + ord(s[byteOffset + 1]) - 0x80;
byteOffset += 2;
} else if (code < 0xF0) {
code = ((code - 0xE0) << 12) + ((ord(s[byteOffset + 1]) - 0x80) << 6) + ord(s[byteOffset + 2]) - 0x80;
byteOffset += 3;
} else {
code = ((code - 0xF0) << 18)
+ ((ord(s[byteOffset + 1]) - 0x80) << 12)
+ ((ord(s[byteOffset + 2]) - 0x80) << 6)
+ ord(s[byteOffset + 3])
- 0x80;
byteOffset += 4;
}
return code;
}
static public inline function unicodeIterator(s:String) {
return new StringIteratorUnicode(s);
}
}

View File

@ -0,0 +1,67 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.iterators;
import php.Global.*;
import php.NativeString;
class StringKeyValueIteratorUnicode {
var charOffset:Int = 0;
var byteOffset:Int = 0;
var totalBytes:Int;
var s:NativeString;
public inline function new(s:String) {
this.s = s;
totalBytes = strlen(s);
}
public inline function hasNext() {
return byteOffset < totalBytes;
}
public inline function next() {
var code = ord(s[byteOffset]);
if (code < 0xC0) {
byteOffset++;
} else if (code < 0xE0) {
code = ((code - 0xC0) << 6) + ord(s[byteOffset + 1]) - 0x80;
byteOffset += 2;
} else if (code < 0xF0) {
code = ((code - 0xE0) << 12) + ((ord(s[byteOffset + 1]) - 0x80) << 6) + ord(s[byteOffset + 2]) - 0x80;
byteOffset += 3;
} else {
code = ((code - 0xF0) << 18)
+ ((ord(s[byteOffset + 1]) - 0x80) << 12)
+ ((ord(s[byteOffset + 2]) - 0x80) << 6)
+ ord(s[byteOffset + 3])
- 0x80;
byteOffset += 4;
}
return {key: charOffset++, value: code};
}
static public inline function unicodeKeyValueIterator(s:String) {
return new StringKeyValueIteratorUnicode(s);
}
}

View File

@ -0,0 +1,401 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.xml;
import php.Global;
import php.Syntax;
import php.NativeString;
using haxe.xml.Parser;
private enum abstract S(Int) {
var IGNORE_SPACES;
var BEGIN;
var BEGIN_NODE;
var TAG_NAME;
var BODY;
var ATTRIB_NAME;
var EQUALS;
var ATTVAL_BEGIN;
var ATTRIB_VAL;
var CHILDS;
var CLOSE;
var WAIT_END;
var WAIT_END_RET;
var PCDATA;
var HEADER;
var COMMENT;
var DOCTYPE;
var CDATA;
var ESCAPE;
}
class XmlParserException {
public var message:String;
public var lineNumber:Int;
public var positionAtLine:Int;
public var position:Int;
public var xml:String;
public function new(message:String, xml:String, position:Int) {
this.xml = xml;
this.message = message;
this.position = position;
lineNumber = 1;
positionAtLine = 0;
for (i in 0...position) {
var c = (xml : NativeString).fastCodeAt(i);
if (c == '\n'.code) {
lineNumber++;
positionAtLine = 0;
} else {
if (c != '\r'.code)
positionAtLine++;
}
}
}
public function toString():String {
return Type.getClassName(Type.getClass(this)) + ": " + message + " at line " + lineNumber + " char " + positionAtLine;
}
}
class Parser {
static var escapes = {
var h = new haxe.ds.StringMap();
h.set("lt", "<");
h.set("gt", ">");
h.set("amp", "&");
h.set("quot", '"');
h.set("apos", "'");
h;
}
static public function parse(str:String, strict = false) {
var doc = Xml.createDocument();
doParse(str, strict, 0, doc);
return doc;
}
static function doParse(str:NativeString, strict:Bool, p:Int = 0, ?parent:Xml):Int {
var xml:Xml = null;
var state = S.BEGIN;
var next = S.BEGIN;
var aname = null;
var start = 0;
var nsubs = 0;
var nbrackets = 0;
var c = str.fastCodeAt(p);
var buf:NativeString = '';
// need extra state because next is in use
var escapeNext = S.BEGIN;
var attrValQuote = -1;
inline function addChild(xml:Xml) {
parent.addChild(xml);
nsubs++;
}
while (!StringTools.isEof(c)) {
switch (state) {
case S.IGNORE_SPACES:
switch (c) {
case '\n'.code, '\r'.code, '\t'.code, ' '.code:
default:
state = next;
continue;
}
case S.BEGIN:
switch (c) {
case '<'.code:
state = S.IGNORE_SPACES;
next = S.BEGIN_NODE;
default:
start = p;
state = S.PCDATA;
continue;
}
case S.PCDATA:
if (c == '<'.code) {
buf = buf.addSub(str, start, p - start);
var child = Xml.createPCData(buf);
buf = '';
addChild(child);
state = S.IGNORE_SPACES;
next = S.BEGIN_NODE;
} else if (c == '&'.code) {
buf = buf.addSub(str, start, p - start);
state = S.ESCAPE;
escapeNext = S.PCDATA;
start = p + 1;
}
case S.CDATA:
if (c == ']'.code && str.fastCodeAt(p + 1) == ']'.code && str.fastCodeAt(p + 2) == '>'.code) {
var child = Xml.createCData(str.substr(start, p - start));
addChild(child);
p += 2;
state = S.BEGIN;
}
case S.BEGIN_NODE:
switch (c) {
case '!'.code:
if (str.fastCodeAt(p + 1) == '['.code) {
p += 2;
if (Global.strtoupper(str.substr(p, 6)) != "CDATA[")
throw new XmlParserException("Expected <![CDATA[", str, p);
p += 5;
state = S.CDATA;
start = p + 1;
} else if (str.fastCodeAt(p + 1) == 'D'.code || str.fastCodeAt(p + 1) == 'd'.code) {
if (Global.strtoupper(str.substr(p + 2, 6)) != "OCTYPE")
throw new XmlParserException("Expected <!DOCTYPE", str, p);
p += 8;
state = S.DOCTYPE;
start = p + 1;
} else if (str.fastCodeAt(p + 1) != '-'.code || str.fastCodeAt(p + 2) != '-'.code)
throw new XmlParserException("Expected <!--", str, p);
else {
p += 2;
state = S.COMMENT;
start = p + 1;
}
case '?'.code:
state = S.HEADER;
start = p;
case '/'.code:
if (parent == null)
throw new XmlParserException("Expected node name", str, p);
start = p + 1;
state = S.IGNORE_SPACES;
next = S.CLOSE;
default:
state = S.TAG_NAME;
start = p;
continue;
}
case S.TAG_NAME:
if (!isValidChar(c)) {
if (p == start)
throw new XmlParserException("Expected node name", str, p);
xml = Xml.createElement(str.substr(start, p - start));
addChild(xml);
state = S.IGNORE_SPACES;
next = S.BODY;
continue;
}
case S.BODY:
switch (c) {
case '/'.code:
state = S.WAIT_END;
case '>'.code:
state = S.CHILDS;
default:
state = S.ATTRIB_NAME;
start = p;
continue;
}
case S.ATTRIB_NAME:
if (!isValidChar(c)) {
var tmp;
if (start == p)
throw new XmlParserException("Expected attribute name", str, p);
tmp = str.substr(start, p - start);
aname = tmp;
if (xml.exists(aname))
throw new XmlParserException("Duplicate attribute [" + aname + "]", str, p);
state = S.IGNORE_SPACES;
next = S.EQUALS;
continue;
}
case S.EQUALS:
switch (c) {
case '='.code:
state = S.IGNORE_SPACES;
next = S.ATTVAL_BEGIN;
default:
throw new XmlParserException("Expected =", str, p);
}
case S.ATTVAL_BEGIN:
switch (c) {
case '"'.code | '\''.code:
buf = '';
state = S.ATTRIB_VAL;
start = p + 1;
attrValQuote = c;
default:
throw new XmlParserException("Expected \"", str, p);
}
case S.ATTRIB_VAL:
switch (c) {
case '&'.code:
buf = buf.addSub(str, start, p - start);
state = S.ESCAPE;
escapeNext = S.ATTRIB_VAL;
start = p + 1;
case '>'.code | '<'.code if (strict):
// HTML allows these in attributes values
throw new XmlParserException("Invalid unescaped " + String.fromCharCode(c) + " in attribute value", str, p);
case _ if (c == attrValQuote):
buf = buf.addSub(str, start, p - start);
var val = buf;
buf = '';
xml.set(aname, val);
state = S.IGNORE_SPACES;
next = S.BODY;
}
case S.CHILDS:
p = doParse(str, strict, p, xml);
start = p;
state = S.BEGIN;
case S.WAIT_END:
switch (c) {
case '>'.code:
state = S.BEGIN;
default:
throw new XmlParserException("Expected >", str, p);
}
case S.WAIT_END_RET:
switch (c) {
case '>'.code:
if (nsubs == 0)
parent.addChild(Xml.createPCData(""));
return p;
default:
throw new XmlParserException("Expected >", str, p);
}
case S.CLOSE:
if (!isValidChar(c)) {
if (start == p)
throw new XmlParserException("Expected node name", str, p);
var v = str.substr(start, p - start);
if (parent == null || parent.nodeType != Element) {
throw new XmlParserException('Unexpected </$v>, tag is not open', str, p);
}
if (v != parent.nodeName)
throw new XmlParserException("Expected </" + parent.nodeName + ">", str, p);
state = S.IGNORE_SPACES;
next = S.WAIT_END_RET;
continue;
}
case S.COMMENT:
if (c == '-'.code && str.fastCodeAt(p + 1) == '-'.code && str.fastCodeAt(p + 2) == '>'.code) {
addChild(Xml.createComment(str.substr(start, p - start)));
p += 2;
state = S.BEGIN;
}
case S.DOCTYPE:
if (c == '['.code)
nbrackets++;
else if (c == ']'.code)
nbrackets--;
else if (c == '>'.code && nbrackets == 0) {
addChild(Xml.createDocType(str.substr(start, p - start)));
state = S.BEGIN;
}
case S.HEADER:
if (c == '?'.code && str.fastCodeAt(p + 1) == '>'.code) {
p++;
var str = str.substr(start + 1, p - start - 2);
addChild(Xml.createProcessingInstruction(str));
state = S.BEGIN;
}
case S.ESCAPE:
if (c == ';'.code) {
var s = str.substr(start, p - start);
if (s.fastCodeAt(0) == '#'.code) {
var c = s.fastCodeAt(1) == 'x'.code ? Std.parseInt("0" + s.substr(1,
Global.strlen(s) - 1)) : Std.parseInt(s.substr(1, Global.strlen(s) - 1));
buf = Syntax.concat(buf, Global.mb_chr(c));
} else if (!escapes.exists(s)) {
if (strict)
throw new XmlParserException("Undefined entity: " + s, str, p);
buf = Syntax.concat(buf, '&$s;');
} else {
buf = Syntax.concat(buf, escapes.get(s));
}
start = p + 1;
state = escapeNext;
} else if (!isValidChar(c) && c != "#".code) {
if (strict)
throw new XmlParserException("Invalid character in entity: " + String.fromCharCode(c), str, p);
buf = Syntax.concat(buf, "&");
buf = buf.addSub(str, start, p - start);
p--;
start = p + 1;
state = escapeNext;
}
}
c = str.fastCodeAt(++p);
}
if (state == S.BEGIN) {
start = p;
state = S.PCDATA;
}
if (state == S.PCDATA) {
if (parent.nodeType == Element) {
throw new XmlParserException("Unclosed node <" + parent.nodeName + ">", str, p);
}
if (p != start || nsubs == 0) {
buf = buf.addSub(str, start, p - start);
addChild(Xml.createPCData(buf));
}
return p;
}
if (!strict && state == S.ESCAPE && escapeNext == S.PCDATA) {
buf = Syntax.concat(buf, "&");
buf = buf.addSub(str, start, p - start);
addChild(Xml.createPCData(buf));
return p;
}
throw new XmlParserException("Unexpected end", str, p);
}
static inline function isValidChar(c) {
return (c >= 'a'.code && c <= 'z'.code) || (c >= 'A'.code && c <= 'Z'.code) || (c >= '0'.code && c <= '9'.code) || c == ':'.code || c == '.'.code
|| c == '_'.code || c == '-'.code;
}
// TODO: rewrite the parser using a buffer instead of a string as the data source
@:allow(haxe.xml.XmlParserException)
static inline function fastCodeAt(s:NativeString, pos:Int):Int {
return pos >= Global.strlen(s) ? 0 : Global.ord(s[pos]);
}
static inline function substr(s:NativeString, pos:Int, ?length:Int):NativeString {
return Global.substr(s, pos, length);
}
static inline function addSub(buf:NativeString, s:NativeString, pos:Int, length:Int):NativeString {
return Syntax.concat(buf, Global.substr(s, pos, length));
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.zip;
@:coreApi
class Compress {
private var level:Int;
public function new(level:Int):Void {
this.level = level;
}
public function execute(src:haxe.io.Bytes, srcPos:Int, dst:haxe.io.Bytes, dstPos:Int):{done:Bool, read:Int, write:Int} {
var input = src.sub(srcPos, src.length - srcPos);
var data = run(input, level);
dst.blit(dstPos, data, 0, data.length);
return {
done: true,
read: input.length,
write: data.length
};
}
public function setFlushMode(f:FlushMode):Void {}
public function close():Void {}
public static function run(s:haxe.io.Bytes, level:Int):haxe.io.Bytes {
var c = php.Global.gzcompress(s.toString(), level);
return haxe.io.Bytes.ofString(c);
}
}

View File

@ -0,0 +1,48 @@
/*
* Copyright (C)2005-2012 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.zip;
class Uncompress {
public function new(?windowBits:Int) {}
public function execute(src:haxe.io.Bytes, srcPos:Int, dst:haxe.io.Bytes, dstPos:Int):{done:Bool, read:Int, write:Int} {
var input = src.sub(srcPos, src.length - srcPos);
var data = run(input);
dst.blit(dstPos, data, 0, data.length);
return {
done: true,
read: input.length,
write: data.length
};
}
public function setFlushMode(f:FlushMode) {}
public function close() {}
public static function run(src:haxe.io.Bytes, ?bufsize:Int):haxe.io.Bytes {
var c = php.Global.gzuncompress(src.toString());
return haxe.io.Bytes.ofString(c);
}
}

View File

@ -0,0 +1,124 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package sys;
import php.*;
import haxe.io.Path;
private enum FileKind {
kdir;
kfile;
kother(k:String);
}
@:coreApi
class FileSystem {
public static inline function exists(path:String):Bool {
Global.clearstatcache(true, path);
return Global.file_exists(path);
}
public static inline function rename(path:String, newPath:String):Void {
Global.rename(path, newPath);
}
public static function stat(path:String):FileStat {
Global.clearstatcache(true, path);
var info = Global.stat(path);
if (info == false)
throw 'Unable to stat $path';
var info:NativeArray = info;
return {
gid: info['gid'],
uid: info['uid'],
atime: Date.fromTime(info['atime'] * 1000),
mtime: Date.fromTime(info['mtime'] * 1000),
ctime: Date.fromTime(info['ctime'] * 1000),
dev: info['dev'],
ino: info['ino'],
nlink: info['nlink'],
rdev: info['rdev'],
size: info['size'],
mode: info['mode']
};
}
public static inline function fullPath(relPath:String):String {
return Syntax.shortTernary(Global.realpath(relPath), null);
}
public static function absolutePath(relPath:String):String {
if (Path.isAbsolute(relPath))
return relPath;
return Path.join([Sys.getCwd(), relPath]);
}
static function kind(path:String):FileKind {
Global.clearstatcache(true, path);
var kind = Global.filetype(path);
if (kind == false)
throw 'Failed to check file type $path';
switch (kind) {
case "file":
return kfile;
case "dir":
return kdir;
default:
return kother(kind);
}
}
public static function isDirectory(path:String):Bool {
Global.clearstatcache(true, path);
return Global.is_dir(path);
}
public static function createDirectory(path:String):Void {
Global.clearstatcache(true, path);
if (!Global.is_dir(path))
Global.mkdir(path, 493, true);
}
public static inline function deleteFile(path:String):Void {
Global.unlink(path);
}
public static inline function deleteDirectory(path:String):Void {
Global.rmdir(path);
}
public static function readDirectory(path:String):Array<String> {
var list = [];
var dir = Global.opendir(path);
var file;
while ((file = Global.readdir(dir)) != false) {
if (file != '.' && file != '..') {
list.push(file);
}
}
Global.closedir(dir);
return list;
}
}

View File

@ -0,0 +1,268 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package sys.db;
import php.*;
import sys.db.*;
import php.db.*;
import php.db.Mysqli_result;
@:coreApi class Mysql {
public static function connect(params:{
host:String,
?port:Int,
user:String,
pass:String,
?socket:String,
?database:String
}):Connection {
return new MysqlConnection(params);
}
}
private class MysqlConnection implements Connection {
var db:Mysqli;
public function new(params:{
host:String,
?port:Int,
user:String,
pass:String,
?socket:String,
?database:String
}):Void {
if (params.port == null)
params.port = Std.parseInt(Global.ini_get('mysqli.default_port'));
if (params.socket == null)
params.socket = Global.ini_get('mysqli.default_socket');
if (params.database == null)
params.database = "";
db = new Mysqli(params.host, params.user, params.pass, params.database, params.port, params.socket);
}
public function request(s:String):ResultSet {
var result = db.query(s);
if (result == false)
throw 'Failed to perform db query: ' + db.error;
if (result == true) {
return new WriteMysqlResultSet(db.affected_rows);
}
return new MysqlResultSet(result);
}
public function close():Void {
db.close();
}
public function escape(s:String):String {
return db.escape_string(s);
}
public function quote(s:String):String {
if (s.indexOf("\000") >= 0)
return "x'" + Global.bin2hex(s) + "'";
return "'" + db.escape_string(s) + "'";
}
public function addValue(s:StringBuf, v:Dynamic):Void {
if (Global.is_int(v) || Global.is_null(v)) {
s.add(v);
} else if (Global.is_bool(v)) {
s.add(v ? 1 : 0);
} else {
s.add(quote(Std.string(v)));
}
}
public function lastInsertId():Int {
return db.insert_id;
}
public function dbName():String {
return 'MySQL';
}
public function startTransaction():Void {
var success = db.begin_transaction();
if (!success)
throw 'Failed to start transaction: ' + db.error;
}
public function commit():Void {
var success = db.commit();
if (!success)
throw 'Failed to commit transaction: ' + db.error;
}
public function rollback():Void {
var success = db.rollback();
if (!success)
throw 'Failed to rollback transaction: ' + db.error;
}
}
private class MysqlResultSet implements ResultSet {
static var hxAnonClassName = Boot.getHxAnon().phpClassName;
public var length(get, null):Int;
public var nfields(get, null):Int;
var result:Mysqli_result;
var fetchedRow:NativeAssocArray<Scalar>;
var fieldsInfo:NativeAssocArray<MysqliFieldInfo>;
public function new(result:Mysqli_result) {
this.result = result;
}
public function hasNext():Bool {
if (fetchedRow == null)
fetchNext();
return fetchedRow != null;
}
public function next():Dynamic {
if (fetchedRow == null)
fetchNext();
return withdrawFetched();
}
public function results():List<Dynamic> {
var list = new List();
result.data_seek(0);
var row = result.fetch_object(hxAnonClassName);
while (row != null) {
row = correctObjectTypes(row);
list.add(row);
row = result.fetch_object(hxAnonClassName);
}
return list;
}
public function getResult(n:Int):String {
if (fetchedRow == null)
fetchNext();
return Global.array_values(fetchedRow)[n];
}
public function getIntResult(n:Int):Int {
return Syntax.int(getResult(n));
}
public function getFloatResult(n:Int):Float {
return Syntax.float(getResult(n));
}
public function getFieldsNames():Null<Array<String>> {
var fields = result.fetch_fields();
return [for (field in fields) field.name];
}
function fetchNext() {
var row = result.fetch_assoc();
if (row != null)
fetchedRow = correctArrayTypes(row);
}
function withdrawFetched():Dynamic {
if (fetchedRow == null)
return null;
var row = fetchedRow;
fetchedRow = null;
return Boot.createAnon(row);
}
function correctArrayTypes(row:NativeAssocArray<String>):NativeAssocArray<Scalar> {
var fieldsInfo = getFieldsInfo();
Syntax.foreach(row, function(field:String, value:String) {
row[field] = correctType(value, fieldsInfo[field].type);
});
return cast row;
}
function correctObjectTypes(row:{}):{} {
var fieldsInfo = getFieldsInfo();
Syntax.foreach(row, function(field:String, value:String) {
value = correctType(value, fieldsInfo[field].type);
Syntax.setField(row, field, value);
});
return row;
}
inline function getFieldsInfo():NativeAssocArray<MysqliFieldInfo> {
if (fieldsInfo == null) {
fieldsInfo = cast Syntax.arrayDecl();
Syntax.foreach(result.fetch_fields(), function(_, info) {
fieldsInfo[info.name] = info;
});
}
return fieldsInfo;
}
function correctType(value:String, type:Int):Scalar {
if (value == null)
return null;
if (type == Const.MYSQLI_TYPE_BIT || type == Const.MYSQLI_TYPE_TINY || type == Const.MYSQLI_TYPE_SHORT || type == Const.MYSQLI_TYPE_LONG
|| type == Const.MYSQLI_TYPE_INT24 || type == Const.MYSQLI_TYPE_CHAR) {
return Syntax.int(value);
}
if (type == Const.MYSQLI_TYPE_DECIMAL
|| type == Const.MYSQLI_TYPE_NEWDECIMAL
|| type == Const.MYSQLI_TYPE_FLOAT
|| type == Const.MYSQLI_TYPE_DOUBLE) {
return Syntax.float(value);
}
return value;
}
function get_length()
return result.num_rows;
function get_nfields()
return result.field_count;
}
private class WriteMysqlResultSet extends MysqlResultSet {
var affectedRows:Int = 0;
public function new(affectedRows:Int) {
super(null);
this.affectedRows = affectedRows;
}
override public function hasNext():Bool {
return false;
}
override function fetchNext() {}
override function get_length()
return affectedRows;
override function get_nfields()
return 0;
}

View File

@ -0,0 +1,218 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package sys.db;
import php.*;
import php.Global.*;
import php.db.*;
import sys.db.*;
@:coreApi class Sqlite {
public static function open(file:String):Connection {
return new SQLiteConnection(file);
}
}
private class SQLiteConnection implements Connection {
var db:SQLite3;
public function new(file:String) {
db = new SQLite3(file);
db.enableExceptions(true);
}
public function request(s:String):ResultSet {
var result = db.query(s);
return new SQLiteResultSet(result);
}
public function close():Void {
db.close();
}
public function escape(s:String):String {
return SQLite3.escapeString(s);
}
public function quote(s:String):String {
if (s.indexOf("\000") >= 0)
return "x'" + Global.bin2hex(s) + "'";
return "'" + SQLite3.escapeString(s) + "'";
}
public function addValue(s:StringBuf, v:Dynamic):Void {
if (Global.is_int(v) || Global.is_null(v)) {
s.add(v);
} else if (Global.is_bool(v)) {
s.add(v ? 1 : 0);
} else {
s.add(quote(Std.string(v)));
}
}
public function lastInsertId():Int {
return Syntax.int(db.lastInsertRowID());
}
public function dbName():String {
return 'SQLite';
}
public function startTransaction():Void {
db.query('BEGIN TRANSACTION');
}
public function commit():Void {
db.query('COMMIT');
}
public function rollback():Void {
db.query('ROLLBACK');
}
}
private class SQLiteResultSet implements ResultSet {
public var length(get, null):Int;
public var nfields(get, null):Int;
var cache = new NativeIndexedArray<{}>();
var result:SQLite3Result;
var resultIsDepleted = false;
var fieldsInfo:NativeAssocArray<Int>;
public function new(result:SQLite3Result) {
this.result = result;
}
public function hasNext():Bool {
return switch next() {
case null: false;
case row:
array_unshift(cache, row);
row;
}
}
public function next():Dynamic {
return switch array_shift(cache) {
case null: fetchNext();
case row: row;
}
}
function fetchNext():Null<{}> {
return resultIsDepleted ? null : switch result.fetchArray(Const.SQLITE3_ASSOC) {
case false:
resultIsDepleted = true;
result.finalize();
null;
case row:
Boot.createAnon(correctArrayTypes(row));
}
}
public function cacheAll():NativeIndexedArray<{}> {
var row = fetchNext();
while(row != null) {
cache.push(row);
row = fetchNext();
}
return cache;
}
public function results():List<Dynamic> {
var list = new List();
for(row in cacheAll()) {
list.add(row);
}
return list;
}
function getColumn(n:Int):Any {
return array_values(Syntax.array(current()))[n];
}
public function getResult(n:Int):String {
return Syntax.string(getColumn(n));
}
public function getIntResult(n:Int):Int {
return Syntax.int(getColumn(n));
}
public function getFloatResult(n:Int):Float {
return Syntax.float(getColumn(n));
}
public function getFieldsNames():Null<Array<String>> {
var fieldsInfo = getFieldsInfo();
return Global.array_keys(fieldsInfo);
}
function current():Null<{}> {
return switch reset(cache) {
case false:
switch next() {
case null: null;
case row:
cache.push(row);
row;
}
case row: row;
}
}
function correctArrayTypes(row:NativeAssocArray<String>):NativeAssocArray<Scalar> {
var fieldsInfo = getFieldsInfo();
Syntax.foreach(row, function(field:String, value:String) {
row[field] = correctType(value, fieldsInfo[field]);
});
return cast row;
}
inline function getFieldsInfo():NativeAssocArray<Int> {
if (fieldsInfo == null) {
fieldsInfo = cast Syntax.arrayDecl();
for (i in 0...nfields) {
fieldsInfo[result.columnName(i)] = result.columnType(i);
}
}
return fieldsInfo;
}
function correctType(value:String, type:Int):Scalar {
if (value == null)
return null;
if (type == Const.SQLITE3_INTEGER)
return Syntax.int(value);
if (type == Const.SQLITE3_FLOAT)
return Syntax.float(value);
return value;
}
function get_length():Int
return count(cacheAll());
function get_nfields():Int
return result.numColumns();
}

View File

@ -0,0 +1,69 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package sys.io;
import php.Global.*;
import php.Global;
@:coreApi class File {
public static function getContent(path:String):String {
return file_get_contents(path);
}
public static function getBytes(path:String):haxe.io.Bytes {
return haxe.io.Bytes.ofString(file_get_contents(path));
}
public static function saveContent(path:String, content:String):Void {
file_put_contents(path, content);
}
public static function saveBytes(path:String, bytes:haxe.io.Bytes):Void {
var f = write(path);
f.write(bytes);
f.close();
}
public static function read(path:String, binary:Bool = true):FileInput {
return @:privateAccess new FileInput(fopen(path, binary ? "rb" : "r"));
}
public static function write(path:String, binary:Bool = true):FileOutput {
return untyped new FileOutput(fopen(path, binary ? "wb" : "w"));
}
public static function append(path:String, binary:Bool = true):FileOutput {
return untyped new FileOutput(fopen(path, binary ? "ab" : "a"));
}
public static function update(path:String, binary:Bool = true):FileOutput {
if (!FileSystem.exists(path)) {
write(path).close();
}
return untyped new FileOutput(fopen(path, binary ? "rb+" : "r+"));
}
public static function copy(srcPath:String, dstPath:String):Void {
Global.copy(srcPath, dstPath);
}
}

View File

@ -0,0 +1,100 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package sys.io;
import haxe.io.Eof;
import haxe.io.Error;
import haxe.io.Bytes;
import php.*;
import php.Global.*;
import php.Const.*;
@:coreApi
class FileInput extends haxe.io.Input {
private var __f:Resource;
function new(f:Resource):Void {
__f = f;
}
public override function readByte():Int {
var r = fread(__f, 1);
if (feof(__f))
throw new Eof();
if (r == false)
throw Custom('An error occurred');
return ord(r);
}
public override function readBytes(s:Bytes, p:Int, l:Int):Int {
if (feof(__f))
throw new Eof();
var r = fread(__f, l);
if (r == false)
throw Custom('An error occurred');
if (strlen(r) == 0)
throw new Eof();
var b = Bytes.ofString(r);
s.blit(p, b, 0, strlen(r));
return strlen(r);
}
public override function close():Void {
super.close();
if (__f != null)
fclose(__f);
}
public function seek(p:Int, pos:FileSeek):Void {
var w;
switch (pos) {
case SeekBegin:
w = SEEK_SET;
case SeekCur:
w = SEEK_CUR;
case SeekEnd:
w = SEEK_END;
}
var r = fseek(__f, p, w);
if (r == -1)
throw Custom('An error occurred');
}
public function tell():Int {
var r = ftell(__f);
if (r == false)
throw Custom('An error occurred');
return cast r;
}
public function eof():Bool {
return feof(__f);
}
override function readLine():String {
var r = fgets(__f);
if (false == r)
throw new Eof();
return rtrim(r, "\r\n");
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package sys.io;
import php.*;
import php.Global.*;
import php.Const.*;
@:coreApi
class FileOutput extends haxe.io.Output {
private var __f:Resource;
function new(f:Resource):Void {
__f = f;
}
public override function writeByte(c:Int):Void {
var r = fwrite(__f, chr(c));
if (r == false)
throw haxe.io.Error.Custom('An error occurred');
}
public override function writeBytes(b:haxe.io.Bytes, p:Int, l:Int):Int {
var s = b.getString(p, l);
if (feof(__f))
throw new haxe.io.Eof();
var r = fwrite(__f, s, l);
if (r == false)
throw haxe.io.Error.Custom('An error occurred');
return r;
}
public override function flush():Void {
var r = fflush(__f);
if (r == false)
throw haxe.io.Error.Custom('An error occurred');
}
public override function close():Void {
super.close();
if (__f != null)
fclose(__f);
}
public function seek(p:Int, pos:FileSeek):Void {
var w;
switch (pos) {
case SeekBegin:
w = SEEK_SET;
case SeekCur:
w = SEEK_CUR;
case SeekEnd:
w = SEEK_END;
}
var r = fseek(__f, p, w);
if (r == -1)
throw haxe.io.Error.Custom('An error occurred');
}
public function tell():Int {
var r = ftell(__f);
if (r == false)
throw haxe.io.Error.Custom('An error occurred');
return r;
}
}

View File

@ -0,0 +1,200 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package sys.io;
import php.*;
import haxe.io.*;
import haxe.SysTools;
using StringTools;
using php.Global;
@:forward(iterator)
private abstract ProcessPipes(NativeIndexedArray<Resource>) from NativeIndexedArray<Resource> to NativeIndexedArray<Resource> {
public var stdin(get, never):Resource;
public var stdout(get, never):Resource;
public var stderr(get, never):Resource;
inline function get_stdin()
return this[0];
inline function get_stdout()
return this[1];
inline function get_stderr()
return this[2];
}
private class ReadablePipe extends Input {
var pipe:Resource;
var tmpBytes:Bytes;
public function new(pipe:Resource) {
this.pipe = pipe;
tmpBytes = Bytes.alloc(1);
}
override public function close():Void {
pipe.fclose();
}
override public function readByte():Int {
if (readBytes(tmpBytes, 0, 1) == 0)
throw Error.Blocked;
return tmpBytes.get(0);
}
override public function readBytes(s:Bytes, pos:Int, len:Int):Int {
if (pipe.feof())
throw new Eof();
var result = pipe.fread(len);
if (result == "")
throw new Eof();
if (result == false)
return throw Error.Custom('Failed to read process output');
var result:String = result;
var bytes = Bytes.ofString(result);
s.blit(pos, bytes, 0, result.strlen());
return result.strlen();
}
}
private class WritablePipe extends Output {
var pipe:Resource;
var tmpBytes:Bytes;
public function new(pipe:Resource) {
this.pipe = pipe;
tmpBytes = Bytes.alloc(1);
}
override public function close():Void {
pipe.fclose();
}
override public function writeByte(c:Int):Void {
tmpBytes.set(0, c);
writeBytes(tmpBytes, 0, 1);
}
override public function writeBytes(b:Bytes, pos:Int, l:Int):Int {
var s = b.getString(pos, l);
if (pipe.feof())
throw new Eof();
var result = Global.fwrite(pipe, s, l);
if (result == false)
throw Error.Custom('Failed to write to process input');
return result;
}
}
class Process {
public var stdout(default, null):Input;
public var stderr(default, null):Input;
public var stdin(default, null):Output;
var process:Resource;
var pipes:ProcessPipes;
var pid:Int = -1;
var running:Bool = true;
var _exitCode:Int = -1;
public function new(cmd:String, ?args:Array<String>, ?detached:Bool):Void {
if (detached)
throw "Detached process is not supported on this platform";
var descriptors = Syntax.arrayDecl(Syntax.arrayDecl('pipe', 'r'), Syntax.arrayDecl('pipe', 'w'), Syntax.arrayDecl('pipe', 'w'));
var result = buildCmd(cmd, args).proc_open(descriptors, pipes);
if (result == false)
throw Error.Custom('Failed to start process: $cmd');
process = result;
updateStatus();
stdin = new WritablePipe(pipes.stdin);
stdout = new ReadablePipe(pipes.stdout);
stderr = new ReadablePipe(pipes.stderr);
}
public function getPid():Int {
return pid;
}
public function exitCode(block:Bool = true):Null<Int> {
if (!block) {
updateStatus();
return (running ? null : _exitCode);
}
while (running) {
var arr = Syntax.arrayDecl(process);
try {
Syntax.suppress(Global.stream_select(arr, arr, arr, null));
} catch(_) {}
updateStatus();
}
return _exitCode;
}
public function close():Void {
if (!running)
return;
for (pipe in pipes)
Global.fclose(pipe);
process.proc_close();
}
public function kill():Void {
process.proc_terminate();
}
function buildCmd(cmd:String, ?args:Array<String>):String {
if (args == null)
return cmd;
return switch (Sys.systemName()) {
case "Windows":
[cmd.replace("/", "\\")].concat(args).map(SysTools.quoteWinArg.bind(_, true)).join(" ");
case _:
[cmd].concat(args).map(SysTools.quoteUnixArg).join(" ");
}
}
function updateStatus():Void {
if (!running)
return;
var status = process.proc_get_status();
if (status == false)
throw Error.Custom('Failed to obtain process status');
var status:NativeAssocArray<Scalar> = status;
pid = status['pid'];
running = status['running'];
_exitCode = status['exitcode'];
}
}

View File

@ -0,0 +1,62 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package sys.net;
import php.Global.*;
import php.SuperGlobal.*;
@:coreApi
class Host {
public var host(default, null):String;
private var _ip:String;
public var ip(default, null):Int;
public function new(name:String):Void {
host = name;
if (~/^(\d{1,3}\.){3}\d{1,3}$/.match(name)) {
_ip = name;
} else {
_ip = gethostbyname(name);
if (_ip == name) {
ip = 0;
return;
}
}
var p = _ip.split('.');
ip = intval(sprintf('%02X%02X%02X%02X', p[3], p[2], p[1], p[0]), 16);
}
public function toString():String {
return _ip;
}
public function reverse():String {
return gethostbyaddr(_ip);
}
public static function localhost():String {
return php.Syntax.coalesce(_SERVER['HTTP_HOST'], "localhost");
}
}

View File

@ -0,0 +1,200 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package sys.net;
import php.*;
import php.Global.*;
import php.Const.*;
import sys.io.FileInput;
import sys.io.FileOutput;
@:coreApi
class Socket {
private var __s:Resource;
private var stream:Resource;
public var input(default, null):haxe.io.Input;
public var output(default, null):haxe.io.Output;
public var custom:Dynamic;
var protocol:String;
public function new():Void {
input = @:privateAccess new sys.io.FileInput(null);
output = @:privateAccess new sys.io.FileOutput(null);
initSocket();
protocol = "tcp";
}
private function initSocket():Void {
__s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
}
private function assignHandler():Void {
stream = socket_export_stream(__s);
@:privateAccess (cast input : FileInput).__f = stream;
@:privateAccess (cast output : FileOutput).__f = stream;
}
public function close():Void {
socket_close(__s);
@:privateAccess (cast input : FileInput).__f = null;
@:privateAccess (cast output : FileOutput).__f = null;
input.close();
output.close();
}
public function read():String {
var b = '';
while (!feof(stream))
b += fgets(stream);
return b;
}
public function write(content:String):Void {
fwrite(stream, content);
}
public function connect(host:Host, port:Int):Void {
var r = socket_connect(__s, host.host, port);
checkError(r, 0, 'Unable to connect');
assignHandler();
}
public function listen(connections:Int):Void {
var r = socket_listen(__s, connections);
checkError(r, 0, 'Unable to listen on socket');
assignHandler();
}
public function shutdown(read:Bool, write:Bool):Void {
var rw = read && write ? 2 : (write ? 1 : (read ? 0 : 2));
var r = socket_shutdown(__s, rw);
checkError(r, 0, 'Unable to shutdown');
}
public function bind(host:Host, port:Int):Void {
var r = socket_bind(__s, host.host, port);
checkError(r, 0, "Unable to bind socket");
}
public function accept():Socket {
var r = socket_accept(__s);
checkError(r, 0, 'Unable to accept connections on socket');
var s = new Socket();
// FIXME: wasted resource here
s.__s = r;
s.assignHandler();
return s;
}
public function peer():{host:Host, port:Int} {
var host:String = "", port:Int = 0;
var r = socket_getpeername(__s, host, port);
checkError(r, 0, 'Unable to retrieve the peer name');
return {host: new Host(host), port: port};
}
public function host():{host:Host, port:Int} {
var host:String = "", port:Int = 0;
var r = socket_getsockname(__s, host, port);
checkError(r, 0, 'Unable to retrieve the host name');
return {host: new Host(host), port: port};
}
public function setTimeout(timeout:Float):Void {
var s = Std.int(timeout);
var ms = Std.int((timeout - s) * 1000000);
var timeOut:NativeStructArray<{sec:Int, usec:Int}> = {sec: s, usec: ms};
var r = socket_set_option(__s, SOL_SOCKET, SO_RCVTIMEO, timeOut);
checkError(r, 0, 'Unable to set receive timeout');
r = socket_set_option(__s, SOL_SOCKET, SO_SNDTIMEO, timeOut);
checkError(r, 0, 'Unable to set send timeout');
}
public function setBlocking(b:Bool):Void {
var r = b ? socket_set_block(__s) : socket_set_nonblock(__s);
checkError(r, 0, 'Unable to set blocking');
}
public function setFastSend(b:Bool):Void {
var r = socket_set_option(__s, SOL_TCP, TCP_NODELAY, true);
checkError(r, 0, "Unable to set TCP_NODELAY on socket");
}
public function waitForRead():Void {
select([this], null, null);
}
private static function checkError(r:Bool, code:Int, msg:String):Void {
if (r != false)
return;
throw haxe.io.Error.Custom('Error [$code]: $msg');
}
/**
Since PHP 8 sockets are represented as instances of class \Socket
TODO:
rewrite without `cast` after resolving https://github.com/HaxeFoundation/haxe/issues/9964
*/
static inline function getSocketId(s:Resource):Int {
return PHP_VERSION_ID < 80000 ? Syntax.int(s) : spl_object_id(cast s);
}
public static function select(read:Array<Socket>, write:Array<Socket>, others:Array<Socket>,
?timeout:Float):{read:Array<Socket>, write:Array<Socket>, others:Array<Socket>} {
var map:Map<Int, Socket> = new Map();
inline function addSockets(sockets:Array<Socket>) {
if (sockets != null)
for (s in sockets)
map[getSocketId(s.__s)] = s;
}
inline function getRaw(sockets:Array<Socket>):Array<Resource> {
return sockets == null ? [] : [for (s in sockets) s.__s];
}
inline function getOriginal(result:Array<Resource>) {
return [for (r in result) map[getSocketId(r)]];
}
addSockets(read);
addSockets(write);
addSockets(others);
// unwrap Sockets into Resources
var rawRead:NativeIndexedArray<Resource> = getRaw(read),
rawWrite:NativeIndexedArray<Resource> = getRaw(write),
rawOthers:NativeIndexedArray<Resource> = getRaw(others);
var sec = timeout == null ? null : Std.int(timeout);
var usec = timeout == null ? 0 : Std.int((timeout % 1) * 1000000);
var result = socket_select(rawRead, rawWrite, rawOthers, sec, usec);
checkError(result, 0, "Error during select call");
// convert raw resources back to Socket objects
return {
read: getOriginal(rawRead),
write: getOriginal(rawWrite),
others: getOriginal(rawOthers),
}
}
}

Some files were not shown because too many files have changed in this diff Show More