初始化代码

This commit is contained in:
2025-12-22 14:34:25 +08:00
parent c2c5ae2fdd
commit a77dbc743f
1510 changed files with 213008 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
<?php
if (SWOOLE_USE_SHORTNAME) {
class_alias(Swoole\Coroutine\WaitGroup::class, Co\WaitGroup::class, false);
class_alias(Swoole\Coroutine\Server::class, Co\Server::class, false);
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Swoole\Coroutine {
function run(callable $fn, ...$args)
{
$s = new Scheduler();
$s->add($fn, ...$args);
return $s->start();
}
}
namespace Co {
if (SWOOLE_USE_SHORTNAME) {
function run(callable $fn, ...$args)
{
return \Swoole\Coroutine\Run($fn, ...$args);
}
}
}

View File

@@ -0,0 +1,6 @@
<?php
define('SWOOLE_LIBRARY', true);
$useShortname = ini_get_all('swoole')['swoole.use_shortname']['local_value'];
$useShortname = strtolower(trim(str_replace('0', '', $useShortname)));
define('SWOOLE_USE_SHORTNAME', !in_array($useShortname, ['', 'off', 'false'], true));

View File

@@ -0,0 +1,665 @@
<?php
namespace Swoole;
use ArrayAccess;
use Countable;
use Iterator;
use RuntimeException;
use Serializable;
class ArrayObject implements ArrayAccess, Serializable, Countable, Iterator
{
/**
* @var array
*/
protected $array;
/**
* ArrayObject constructor.
* @param array $array
*/
public function __construct(array $array = [])
{
$this->array = $array;
}
/**
* @return bool
*/
public function isEmpty(): bool
{
return empty($this->array);
}
/**
* @return int
*/
public function count(): int
{
return count($this->array);
}
/**
* @return mixed
*/
public function current()
{
return current($this->array);
}
/**
* @return mixed
*/
public function key()
{
return key($this->array);
}
/**
* @return bool
*/
public function valid(): bool
{
return array_key_exists($this->key(), $this->array);
}
/**
* @return mixed
*/
public function rewind()
{
return reset($this->array);
}
/**
* @return mixed
*/
public function next()
{
return next($this->array);
}
/**
* @param $key
* @return ArrayObject|StringObject|mixed
*/
public function get($key)
{
return static::detectType($this->array[$key]);
}
/**
* @param $key
* @param $value
* @return $this
*/
public function set($key, $value): self
{
$this->array[$key] = $value;
return $this;
}
/**
* @param $key
* @return $this
*/
public function delete($key): self
{
unset($this->array[$key]);
return $this;
}
/**
* @param $value
* @param bool $strict
* @param bool $loop
* @return $this
*/
public function remove($value, bool $strict = true, bool $loop = false): self
{
do {
$key = $this->search($value, $strict);
if ($key) {
unset($this->array[$key]);
} else {
break;
}
} while ($loop);
return $this;
}
/**
* @return $this
*/
public function clear(): self
{
$this->array = [];
return $this;
}
/**
* @param mixed $key
* @return mixed|null
*/
public function offsetGet($key)
{
if (!array_key_exists($key, $this->array)) {
return null;
}
return $this->array[$key];
}
/**
* @param mixed $key
* @param mixed $value
*/
public function offsetSet($key, $value)
{
$this->array[$key] = $value;
}
/**
* @param mixed $key
*/
public function offsetUnset($key)
{
unset($this->array[$key]);
}
/**
* @param mixed $key
* @return bool
*/
public function offsetExists($key)
{
return isset($this->array[$key]);
}
/**
* @param $key
* @return bool
*/
public function exists($key): bool
{
return array_key_exists($key, $this->array);
}
/**
* @param $value
* @param bool $strict
* @return bool
*/
public function contains($value, bool $strict = true): bool
{
return in_array($value, $this->array, $strict);
}
/**
* @param $value
* @param bool $strict
* @return mixed
*/
public function indexOf($value, bool $strict = true)
{
return $this->search($value, $strict);
}
/**
* @param $value
* @param bool $strict
* @return mixed
*/
public function lastIndexOf($value, bool $strict = true)
{
$array = $this->array;
for (end($array); ($currentKey = key($array)) !== null; prev($array)) {
$currentValue = current($array);
if ($currentValue == $value) {
if ($strict && $currentValue !== $value) {
continue;
}
break;
}
}
return $currentKey;
}
/**
* @param $needle
* @param $strict
* @return mixed
*/
public function search($needle, $strict = true)
{
return array_search($needle, $this->array, $strict);
}
/**
* @param string $glue
* @return StringObject
*/
public function join(string $glue = ''): StringObject
{
return static::detectStringType(implode($glue, $this->array));
}
/**
* @return StringObject
*/
public function serialize(): StringObject
{
return static::detectStringType(serialize($this->array));
}
/**
* @param string $string
* @return $this
*/
public function unserialize($string): self
{
$this->array = (array)unserialize($string);
return $this;
}
/**
* @return float|int
*/
public function sum()
{
return array_sum($this->array);
}
/**
* @return float|int
*/
public function product()
{
return array_product($this->array);
}
/**
* @param $value
* @return int
*/
public function push($value)
{
return array_push($this->array, $value);
}
/**
* @param $value
* @return int
*/
public function pushBack($value)
{
return array_unshift($this->array, $value);
}
/**
* @param int $offset
* @param $value
* @return $this
*/
public function insert(int $offset, $value): self
{
if (is_array($value) || is_object($value) || is_null($value)) {
$value = [$value];
}
array_splice($this->array, $offset, 0, $value);
return $this;
}
/**
* @return mixed
*/
public function pop()
{
return array_pop($this->array);
}
/**
* @return mixed
*/
public function popFront()
{
return array_shift($this->array);
}
/**
* @param $offset
* @param int $length
* @param bool $preserve_keys
* @return static
*/
public function slice($offset, int $length = null, bool $preserve_keys = false): self
{
return new static(array_slice($this->array, ...func_get_args()));
}
/**
* @return ArrayObject|StringObject|mixed
*/
public function randomGet()
{
return static::detectType($this->array[array_rand($this->array, 1)]);
}
/**
* @param $fn callable
* @return $this
*/
public function each(callable $fn): self
{
if (array_walk($this->array, $fn) === false) {
throw new RuntimeException('array_walk() failed');
}
return $this;
}
/**
* @param $fn callable
* @return static
*/
public function map(callable $fn): self
{
return new static(array_map($fn, $this->array));
}
/**
* @param $fn callable
* @return mixed
*/
public function reduce(callable $fn)
{
return array_reduce($this->array, $fn);
}
/**
* @param int $search_value
* @param bool $strict
* @return static
*/
public function keys(int $search_value = null, $strict = false): self
{
return new static(array_keys($this->array, $search_value, $strict));
}
/**
* @return static
*/
public function values(): self
{
return new static(array_values($this->array));
}
/**
* @param $column_key
* @param mixed ...$index
* @return static
*/
public function column($column_key, ...$index): self
{
return new static(array_column($this->array, $column_key, ...$index));
}
/**
* @param int $sort_flags
* @return static
*/
public function unique(int $sort_flags = SORT_STRING): self
{
return new static(array_unique($this->array, $sort_flags));
}
/**
* @param bool $preserve_keys
* @return static
*/
public function reverse(bool $preserve_keys = false): self
{
return new static(array_reverse($this->array, $preserve_keys));
}
/**
* @param int $size
* @param bool $preserve_keys
* @return static
*/
public function chunk(int $size, bool $preserve_keys = false): self
{
return new static(array_chunk($this->array, $size, $preserve_keys));
}
/**
* Swap keys and values in an array
* @return static
*/
public function flip(): self
{
return new static(array_flip($this->array));
}
/**
* @param $fn callable
* @param int $flag
* @return static
*/
public function filter(callable $fn, int $flag = 0): self
{
return new static(array_filter($this->array, $fn, $flag));
}
/**
* | Function name | Sorts by | Maintains key association | Order of sort | Related functions |
* | :---------------- | :------- | :-------------------------- | :-------------------------- | :---------------- |
* | array_multisort() | value | associative yes, numeric no | first array or sort options | array_walk() |
* | asort() | value | yes | low to high | arsort() |
* | arsort() | value | yes | high to low | asort() |
* | krsort() | key | yes | high to low | ksort() |
* | ksort() | key | yes | low to high | asort() |
* | natcasesort() | value | yes | natural, case insensitive | natsort() |
* | natsort() | value | yes | natural | natcasesort() |
* | rsort() | value | no | high to low | sort() |
* | shuffle() | value | no | random | array_rand() |
* | sort() | value | no | low to high | rsort() |
* | uasort() | value | yes | user defined | uksort() |
* | uksort() | key | yes | user defined | uasort() |
* | usort() | value | no | user defined | uasort() |
*/
/**
* @param int $sort_order
* @param int $sort_flags
* @return $this
*/
public function multiSort(int $sort_order = SORT_ASC, int $sort_flags = SORT_REGULAR): self
{
if (array_multisort($this->array, $sort_order, $sort_flags) !== true) {
throw new RuntimeException('array_multisort() failed');
}
return $this;
}
/**
* @param int $sort_flags
* @return $this
*/
public function asort(int $sort_flags = SORT_REGULAR): self
{
if (asort($this->array, $sort_flags) !== true) {
throw new RuntimeException('asort() failed');
}
return $this;
}
/**
* @param int $sort_flags
* @return $this
*/
public function arsort(int $sort_flags = SORT_REGULAR): self
{
if (arsort($this->array, $sort_flags) !== true) {
throw new RuntimeException('arsort() failed');
}
return $this;
}
/**
* @param int $sort_flags
* @return $this
*/
public function krsort(int $sort_flags = SORT_REGULAR): self
{
if (krsort($this->array, $sort_flags) !== true) {
throw new RuntimeException('krsort() failed');
}
return $this;
}
/**
* @param int $sort_flags
* @return $this
*/
public function ksort(int $sort_flags = SORT_REGULAR): self
{
if (ksort($this->array, $sort_flags) !== true) {
throw new RuntimeException('ksort() failed');
}
return $this;
}
/**
* @return $this
*/
public function natcasesort(): self
{
if (natcasesort($this->array) !== true) {
throw new RuntimeException('natcasesort() failed');
}
return $this;
}
/**
* @return $this
*/
public function natsort(): self
{
if (natsort($this->array) !== true) {
throw new RuntimeException('natsort() failed');
}
return $this;
}
/**
* @param int $sort_flags
* @return $this
*/
public function rsort(int $sort_flags = SORT_REGULAR): self
{
if (rsort($this->array, $sort_flags) !== true) {
throw new RuntimeException('rsort() failed');
}
return $this;
}
/**
* @return $this
*/
public function shuffle(): self
{
if (shuffle($this->array) !== true) {
throw new RuntimeException('shuffle() failed');
}
return $this;
}
/**
* @param int $sort_flags
* @return $this
*/
public function sort(int $sort_flags = SORT_REGULAR): self
{
if (sort($this->array, $sort_flags) !== true) {
throw new RuntimeException('sort() failed');
}
return $this;
}
/**
* @param callable $value_compare_func
* @return $this
*/
public function uasort(callable $value_compare_func): self
{
if (uasort($this->array, $value_compare_func) !== true) {
throw new RuntimeException('uasort() failed');
}
return $this;
}
/**
* @param callable $value_compare_func
* @return $this
*/
public function uksort(callable $value_compare_func): self
{
if (uksort($this->array, $value_compare_func) !== true) {
throw new RuntimeException('uksort() failed');
}
return $this;
}
/**
* @param callable $value_compare_func
* @return $this
*/
public function usort(callable $value_compare_func): self
{
if (usort($this->array, $value_compare_func) !== true) {
throw new RuntimeException('usort() failed');
}
return $this;
}
/**
* @return array
*/
public function __toArray(): array
{
return $this->array;
}
/**
* @param $value
* @return ArrayObject|StringObject|mixed
*/
protected static function detectType($value)
{
if (is_string($value)) {
return static::detectStringType($value);
} elseif (is_array($value)) {
return static::detectArrayType($value);
} else {
return $value;
}
}
/**
* @param string $value
* @return StringObject
*/
protected static function detectStringType(string $value): StringObject
{
return new StringObject($value);
}
/**
* @param array $value
* @return static
*/
protected static function detectArrayType(array $value): self
{
return new static($value);
}
}

View File

@@ -0,0 +1,186 @@
<?php
namespace Swoole;
class Constant
{
const EVENT_RECEIVE = 'receive';
const EVENT_CONNECT = 'connect';
const EVENT_CLOSE = 'close';
const EVENT_PACKET = 'packet';
const EVENT_REQUEST = 'request';
const EVENT_MESSAGE = 'message';
const EVENT_OPEN = 'open';
const EVENT_HANDSHAKE = 'handshake';
const EVENT_TASK = 'task';
const EVENT_FINISH = 'finish';
const EVENT_START = 'start';
const EVENT_SHUTDOWN = 'shutdown';
const EVENT_WORKER_START = 'workerStart';
const EVENT_WORKER_EXIT = 'workerExit';
const EVENT_WORKER_ERROR = 'workerError';
const EVENT_WORKER_STOP = 'workerStop';
const EVENT_PIPE_MESSAGE = 'pipeMessage';
const EVENT_MANAGER_START = 'managerStart';
const EVENT_MANAGER_STOP = 'managerStop';
const EVENT_ERROR = 'error';
/* {{{ OPTION */
const OPTION_ENABLE_SIGNALFD = 'enable_signalfd';
const OPTION_DNS_CACHE_REFRESH_TIME = 'dns_cache_refresh_time';
const OPTION_SOCKET_BUFFER_SIZE = 'socket_buffer_size';
const OPTION_SOCKET_SEND_TIMEOUT = 'socket_send_timeout';
const OPTION_LOG_LEVEL = 'log_level';
const OPTION_THREAD_NUM = 'thread_num';
const OPTION_MIN_THREAD_NUM = 'min_thread_num';
const OPTION_MAX_THREAD_NUM = 'max_thread_num';
const OPTION_DISPLAY_ERRORS = 'display_errors';
const OPTION_SOCKET_DONTWAIT = 'socket_dontwait';
const OPTION_DNS_LOOKUP_RANDOM = 'dns_lookup_random';
const OPTION_DNS_SERVER = 'dns_server';
const OPTION_USE_ASYNC_RESOLVER = 'use_async_resolver';
const OPTION_ENABLE_COROUTINE = 'enable_coroutine';
const OPTION_ENABLE_REUSE_PORT = 'enable_reuse_port';
const OPTION_SSL_METHOD = 'ssl_method';
const OPTION_SSL_PROTOCOLS = 'ssl_protocols';
const OPTION_SSL_COMPRESS = 'ssl_compress';
const OPTION_SSL_CERT_FILE = 'ssl_cert_file';
const OPTION_SSL_KEY_FILE = 'ssl_key_file';
const OPTION_SSL_PASSPHRASE = 'ssl_passphrase';
const OPTION_SSL_HOST_NAME = 'ssl_host_name';
const OPTION_SSL_VERIFY_PEER = 'ssl_verify_peer';
const OPTION_SSL_ALLOW_SELF_SIGNED = 'ssl_allow_self_signed';
const OPTION_SSL_CAFILE = 'ssl_cafile';
const OPTION_SSL_CAPATH = 'ssl_capath';
const OPTION_SSL_VERIFY_DEPTH = 'ssl_verify_depth';
const OPTION_OPEN_EOF_CHECK = 'open_eof_check';
const OPTION_OPEN_EOF_SPLIT = 'open_eof_split';
const OPTION_PACKAGE_EOF = 'package_eof';
const OPTION_OPEN_MQTT_PROTOCOL = 'open_mqtt_protocol';
const OPTION_OPEN_LENGTH_CHECK = 'open_length_check';
const OPTION_PACKAGE_LENGTH_TYPE = 'package_length_type';
const OPTION_PACKAGE_LENGTH_OFFSET = 'package_length_offset';
const OPTION_PACKAGE_BODY_OFFSET = 'package_body_offset';
const OPTION_PACKAGE_LENGTH_FUNC = 'package_length_func';
const OPTION_PACKAGE_MAX_LENGTH = 'package_max_length';
const OPTION_BUFFER_HIGH_WATERMARK = 'buffer_high_watermark';
const OPTION_BUFFER_LOW_WATERMARK = 'buffer_low_watermark';
const OPTION_BIND_PORT = 'bind_port';
const OPTION_BIND_ADDRESS = 'bind_address';
const OPTION_OPEN_TCP_NODELAY = 'open_tcp_nodelay';
const OPTION_SOCKS5_HOST = 'socks5_host';
const OPTION_SOCKS5_PORT = 'socks5_port';
const OPTION_SOCKS5_USERNAME = 'socks5_username';
const OPTION_SOCKS5_PASSWORD = 'socks5_password';
const OPTION_HTTP_PROXY_HOST = 'http_proxy_host';
const OPTION_HTTP_PROXY_PORT = 'http_proxy_port';
const OPTION_HTTP_PROXY_USERNAME = 'http_proxy_username';
const OPTION_HTTP_PROXY_USER = 'http_proxy_user';
const OPTION_HTTP_PROXY_PASSWORD = 'http_proxy_password';
const OPTION_TIMEOUT = 'timeout';
const OPTION_CONNECT_TIMEOUT = 'connect_timeout';
const OPTION_READ_TIMEOUT = 'read_timeout';
const OPTION_WRITE_TIMEOUT = 'write_timeout';
const OPTION_SSL_DISABLE_COMPRESSION = 'ssl_disable_compression';
const OPTION_MAX_COROUTINE = 'max_coroutine';
const OPTION_HOOK_FLAGS = 'hook_flags';
const OPTION_C_STACK_SIZE = 'c_stack_size';
const OPTION_STACK_SIZE = 'stack_size';
const OPTION_SOCKET_CONNECT_TIMEOUT = 'socket_connect_timeout';
const OPTION_SOCKET_TIMEOUT = 'socket_timeout';
const OPTION_SOCKET_READ_TIMEOUT = 'socket_read_timeout';
const OPTION_SOCKET_WRITE_TIMEOUT = 'socket_write_timeout';
const OPTION_TRACE_FLAGS = 'trace_flags';
const OPTION_DNS_CACHE_EXPIRE = 'dns_cache_expire';
const OPTION_DNS_CACHE_CAPACITY = 'dns_cache_capacity';
const OPTION_AIO_CORE_WORKER_NUM = 'aio_core_worker_num';
const OPTION_AIO_WORKER_NUM = 'aio_worker_num';
const OPTION_AIO_MAX_WAIT_TIME = 'aio_max_wait_time';
const OPTION_AIO_MAX_IDLE_TIME = 'aio_max_idle_time';
const OPTION_RECONNECT = 'reconnect';
const OPTION_DEFER = 'defer';
const OPTION_KEEP_ALIVE = 'keep_alive';
const OPTION_WEBSOCKET_MASK = 'websocket_mask';
const OPTION_WEBSOCKET_COMPRESSION = 'websocket_compression';
const OPTION_HOST = 'host';
const OPTION_PORT = 'port';
const OPTION_SSL = 'ssl';
const OPTION_USER = 'user';
const OPTION_PASSWORD = 'password';
const OPTION_DATABASE = 'database';
const OPTION_CHARSET = 'charset';
const OPTION_STRICT_TYPE = 'strict_type';
const OPTION_FETCH_MODE = 'fetch_mode';
const OPTION_SERIALIZE = 'serialize';
const OPTION_COMPATIBILITY_MODE = 'compatibility_mode';
const OPTION_CHROOT = 'chroot';
const OPTION_GROUP = 'group';
const OPTION_DAEMONIZE = 'daemonize';
const OPTION_DEBUG_MODE = 'debug_mode';
const OPTION_PID_FILE = 'pid_file';
const OPTION_REACTOR_NUM = 'reactor_num';
const OPTION_SINGLE_THREAD = 'single_thread';
const OPTION_WORKER_NUM = 'worker_num';
const OPTION_MAX_WAIT_TIME = 'max_wait_time';
const OPTION_MAX_CORO_NUM = 'max_coro_num';
const OPTION_SEND_TIMEOUT = 'send_timeout';
const OPTION_DISPATCH_MODE = 'dispatch_mode';
const OPTION_SEND_YIELD = 'send_yield';
const OPTION_DISPATCH_FUNC = 'dispatch_func';
const OPTION_LOG_FILE = 'log_file';
const OPTION_DISCARD_TIMEOUT_REQUEST = 'discard_timeout_request';
const OPTION_ENABLE_UNSAFE_EVENT = 'enable_unsafe_event';
const OPTION_ENABLE_DELAY_RECEIVE = 'enable_delay_receive';
const OPTION_TASK_USE_OBJECT = 'task_use_object';
const OPTION_TASK_ENABLE_COROUTINE = 'task_enable_coroutine';
const OPTION_TASK_WORKER_NUM = 'task_worker_num';
const OPTION_TASK_IPC_MODE = 'task_ipc_mode';
const OPTION_TASK_TMPDIR = 'task_tmpdir';
const OPTION_TASK_MAX_REQUEST = 'task_max_request';
const OPTION_TASK_MAX_REQUEST_GRACE = 'task_max_request_grace';
const OPTION_MAX_CONNECTION = 'max_connection';
const OPTION_MAX_CONN = 'max_conn';
const OPTION_HEARTBEAT_CHECK_INTERVAL = 'heartbeat_check_interval';
const OPTION_HEARTBEAT_IDLE_TIME = 'heartbeat_idle_time';
const OPTION_MAX_REQUEST = 'max_request';
const OPTION_MAX_REQUEST_GRACE = 'max_request_grace';
const OPTION_RELOAD_ASYNC = 'reload_async';
const OPTION_OPEN_CPU_AFFINITY = 'open_cpu_affinity';
const OPTION_CPU_AFFINITY_IGNORE = 'cpu_affinity_ignore';
const OPTION_HTTP_PARSE_COOKIE = 'http_parse_cookie';
const OPTION_HTTP_PARSE_POST = 'http_parse_post';
const OPTION_HTTP_PARSE_FILES = 'http_parse_files';
const OPTION_HTTP_COMPRESSION = 'http_compression';
const OPTION_HTTP_GZIP_LEVEL = 'http_gzip_level';
const OPTION_HTTP_COMPRESSION_LEVEL = 'http_compression_level';
const OPTION_UPLOAD_TMP_DIR = 'upload_tmp_dir';
const OPTION_ENABLE_STATIC_HANDLER = 'enable_static_handler';
const OPTION_DOCUMENT_ROOT = 'document_root';
const OPTION_STATIC_HANDLER_LOCATIONS = 'static_handler_locations';
const OPTION_BUFFER_INPUT_SIZE = 'buffer_input_size';
const OPTION_BUFFER_OUTPUT_SIZE = 'buffer_output_size';
const OPTION_MESSAGE_QUEUE_KEY = 'message_queue_key';
const OPTION_BACKLOG = 'backlog';
const OPTION_KERNEL_SOCKET_RECV_BUFFER_SIZE = 'kernel_socket_recv_buffer_size';
const OPTION_KERNEL_SOCKET_SEND_BUFFER_SIZE = 'kernel_socket_send_buffer_size';
const OPTION_TCP_DEFER_ACCEPT = 'tcp_defer_accept';
const OPTION_OPEN_TCP_KEEPALIVE = 'open_tcp_keepalive';
const OPTION_OPEN_HTTP_PROTOCOL = 'open_http_protocol';
const OPTION_OPEN_WEBSOCKET_PROTOCOL = 'open_websocket_protocol';
const OPTION_WEBSOCKET_SUBPROTOCOL = 'websocket_subprotocol';
const OPTION_OPEN_WEBSOCKET_CLOSE_FRAME = 'open_websocket_close_frame';
const OPTION_OPEN_HTTP2_PROTOCOL = 'open_http2_protocol';
const OPTION_OPEN_REDIS_PROTOCOL = 'open_redis_protocol';
const OPTION_TCP_KEEPIDLE = 'tcp_keepidle';
const OPTION_TCP_KEEPINTERVAL = 'tcp_keepinterval';
const OPTION_TCP_KEEPCOUNT = 'tcp_keepcount';
const OPTION_TCP_FASTOPEN = 'tcp_fastopen';
const OPTION_PACKAGE_BODY_START = 'package_body_start';
const OPTION_SSL_CLIENT_CERT_FILE = 'ssl_client_cert_file';
const OPTION_SSL_PREFER_SERVER_CIPHERS = 'ssl_prefer_server_ciphers';
const OPTION_SSL_CIPHERS = 'ssl_ciphers';
const OPTION_SSL_ECDH_CURVE = 'ssl_ecdh_curve';
const OPTION_SSL_DHPARAM = 'ssl_dhparam';
const OPTION_OPEN_SSL = 'open_ssl';
/* }}} OPTION */
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Swoole\Coroutine;
use BadMethodCallException;
use InvalidArgumentException;
use RuntimeException;
use Swoole\Coroutine;
abstract class ObjectPool
{
protected static $context = [];
protected $object_pool;
protected $busy_pool;
protected $type;
public function __construct($type, $pool_size = 10, $concurrency = 10)
{
if (empty($type)) {
throw new InvalidArgumentException('ObjectPool misuse: parameter type can not be empty');
}
if (!is_numeric($concurrency) || $concurrency <= 0) {
throw new InvalidArgumentException('ObjectPool misuse: parameter concurrency must larger than 0');
}
$this->object_pool = new Channel($pool_size);
$this->busy_pool = new Channel($concurrency);
$this->type = $type;
}
public function get()
{
$context = Coroutine::getContext();
if (!$context) {
throw new BadMethodCallException('ObjectPool misuse: get must be used in coroutine');
}
$type = $this->type;
Coroutine::defer(function () {
$this->free();
});
if (isset($context[$type])) {
return $context[$type];
}
if (!$this->object_pool->isEmpty()) {
$object = $this->object_pool->pop();
$context["new"] = false;
} else {
/* create concurrency control */
$this->busy_pool->push(true);
$object = $this->create();
if (empty($object)) {
throw new RuntimeException('ObjectPool misuse: create object failed');
}
$context["new"] = true;
}
$context[$type] = $object;
return $object;
}
public function free()
{
$context = Coroutine::getContext();
if (!$context) {
throw new BadMethodCallException('ObjectPool misuse: free must be used in coroutine');
}
$type = $this->type;
$object = $context[$type];
$this->object_pool->push($object);
if ($context["new"]) {
$this->busy_pool->pop();
}
}
public abstract function create();
}

View File

@@ -0,0 +1,125 @@
<?php
namespace Swoole\Coroutine;
use Swoole\Coroutine;
use Swoole\Coroutine\Server\Connection;
use Swoole\Exception;
class Server
{
/** @var string */
public $host = '';
/** @var int */
public $port = 0;
/** @var int */
public $type = AF_INET;
/** @var int */
public $fd = -1;
/** @var int */
public $errCode = 0;
/** @var array */
public $setting = [];
/** @var bool */
protected $running = false;
/** @var callable|null */
protected $fn;
/** @var Socket */
protected $socket;
/**
* Server constructor.
* @param string $host
* @param int $port
* @param bool $ssl
* @param bool $reuse_port
* @throws Exception
*/
public function __construct(string $host, int $port = 0, bool $ssl = false, bool $reuse_port = false)
{
$_host = swoole_string($host);
if ($_host->contains('::')) {
$this->type = AF_INET6;
} else {
if ($_host->startsWith('unix:/')) {
$host = $_host->substr(5)->__toString();
$this->type = AF_UNIX;
} else {
$this->type = AF_INET;
}
}
$this->host = $host;
$socket = new Socket($this->type, SOCK_STREAM, 0);
if ($reuse_port and defined('SO_REUSEPORT')) {
$socket->setOption(SOL_SOCKET, SO_REUSEPORT, true);
}
if (!$socket->bind($this->host, $port)) {
throw new Exception("bind({$this->host}:{$port}) failed", $socket->errCode);
}
if (!$socket->listen()) {
throw new Exception("listen() failed", $socket->errCode);
}
$this->port = $socket->getsockname()['port'] ?? 0;
$this->fd = $socket->fd;
$this->socket = $socket;
$this->setting['open_ssl'] = $ssl;
}
public function set(array $setting): void
{
$this->setting = array_merge($this->setting, $setting);
}
public function handle(callable $fn): void
{
$this->fn = $fn;
}
public function shutdown(): bool
{
$this->running = false;
return $this->socket->cancel();
}
public function start(): bool
{
$this->running = true;
if ($this->fn == null) {
$this->errCode = SOCKET_EINVAL;
return false;
}
$socket = $this->socket;
if (!$socket->setProtocol($this->setting)) {
$this->errCode = SOCKET_EINVAL;
return false;
}
while ($this->running) {
/** @var $conn Socket */
$conn = $socket->accept();
if ($conn) {
$conn->setProtocol($this->setting);
if (Coroutine::create($this->fn, new Connection($conn)) < 0) {
goto _wait;
}
} else {
if ($socket->errCode == SOCKET_EMFILE or $socket->errCode == SOCKET_ENFILE) {
_wait:
Coroutine::sleep(1);
continue;
} elseif ($socket->errCode == SOCKET_ETIMEDOUT) {
continue;
} elseif ($socket->errCode == SOCKET_ECANCELED) {
break;
} else {
trigger_error("accept failed, Error: {$socket->errMsg}[{$socket->errCode}]", E_USER_WARNING);
break;
}
}
}
return true;
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Swoole\Coroutine\Server;
use Swoole\Coroutine\Socket;
class Connection
{
public $socket;
public function __construct(Socket $conn)
{
$this->socket = $conn;
}
public function recv($timeout = 0)
{
return $this->socket->recvPacket($timeout);
}
public function send($data)
{
return $this->socket->sendAll($data);
}
public function close()
{
return $this->socket->close();
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Swoole\Coroutine;
use BadMethodCallException;
use InvalidArgumentException;
class WaitGroup
{
protected $chan;
protected $count = 0;
protected $waiting = false;
public function __construct()
{
$this->chan = new Channel(1);
}
public function add(int $delta = 1): void
{
if ($this->waiting) {
throw new BadMethodCallException('WaitGroup misuse: add called concurrently with wait');
}
$count = $this->count + $delta;
if ($count < 0) {
throw new InvalidArgumentException('negative WaitGroup counter');
}
$this->count = $count;
}
public function done(): void
{
$count = $this->count - 1;
if ($count < 0) {
throw new BadMethodCallException('negative WaitGroup counter');
}
$this->count = $count;
if ($count === 0 && $this->waiting) {
$this->chan->push(true);
}
}
public function wait(float $timeout = -1): bool
{
if ($this->count > 0) {
$this->waiting = true;
$done = $this->chan->pop($timeout);
$this->waiting = false;
return $done;
}
return true;
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Swoole\Curl;
use Swoole;
class Exception extends Swoole\Exception
{
}

View File

@@ -0,0 +1,560 @@
<?php
namespace Swoole\Curl;
use Swoole;
use Swoole\Coroutine\Http\Client;
use CURLFile;
use Iterator;
class Handler
{
private const ERRORS = [
CURLE_URL_MALFORMAT => 'No URL set!',
];
/**
* @var Client
*/
private $client;
private $info = [
'url' => '',
'content_type' => '',
'http_code' => 0,
'header_size' => 0,
'request_size' => 0,
'filetime' => -1,
'ssl_verify_result' => 0,
'redirect_count' => 0,
'total_time' => 5.3E-5,
'namelookup_time' => 0.0,
'connect_time' => 0.0,
'pretransfer_time' => 0.0,
'size_upload' => 0.0,
'size_download' => 0.0,
'speed_download' => 0.0,
'speed_upload' => 0.0,
'download_content_length' => -1.0,
'upload_content_length' => -1.0,
'starttransfer_time' => 0.0,
'redirect_time' => 0.0,
'redirect_url' => '',
'primary_ip' => '',
'certinfo' => [],
'primary_port' => 0,
'local_ip' => '',
'local_port' => 0,
'http_version' => 0,
'protocol' => 0,
'ssl_verifyresult' => 0,
'scheme' => '',
];
private $withHeaderOut = false;
private $withFileTime = false;
private $urlInfo;
private $postData;
private $outputStream;
private $proxy;
private $clientOptions = [];
private $followLocation = false;
private $autoReferer = false;
private $maxRedirs;
private $withHeader = false;
private $nobody = false;
/** @var callable */
private $headerFunction;
/** @var callable */
private $readFunction;
/** @var callable */
private $writeFunction;
/** @var callable */
private $progressFunction;
public $returnTransfer = false;
public $method = 'GET';
public $headers = [];
public $transfer;
public $errCode = 0;
public $errMsg = '';
public function __construct($url = null)
{
if ($url) {
$this->create($url);
}
}
private function create(string $url): void
{
if (!swoole_string($url)->contains('://')) {
$url = 'http://' . $url;
}
$this->info['url'] = $url;
$info = parse_url($url);
$proto = swoole_array_default_value($info, 'scheme');
if ($proto != 'http' and $proto != 'https') {
$this->setError(CURLE_UNSUPPORTED_PROTOCOL, "Protocol \"{$proto}\" not supported or disabled in libcurl");
return;
}
$ssl = $proto === 'https';
if (empty($info['port'])) {
$port = $ssl ? 443 : 80;
} else {
$port = intval($info['port']);
}
$this->urlInfo = $info;
$this->client = new Client($info['host'], $port, $ssl);
}
public function execute()
{
$this->info['redirect_count'] = $this->info['starttransfer_time'] = 0;
$this->info['redirect_url'] = '';
$timeBegin = microtime(true);
/**
* Socket
*/
$client = $this->client;
if (!$client) {
if (!$this->errCode) {
$this->setError(CURLE_URL_MALFORMAT);
}
return false;
}
$isRedirect = false;
do {
if ($isRedirect and !$client) {
$proto = swoole_array_default_value($this->urlInfo, 'scheme');
if ($proto != 'http' and $proto != 'https') {
$this->setError(CURLE_UNSUPPORTED_PROTOCOL, "Protocol \"{$proto}\" not supported or disabled in libcurl");
return false;
}
$ssl = $proto === 'https';
if (empty($this->urlInfo['port'])) {
$port = $ssl ? 443 : 80;
} else {
$port = intval($this->urlInfo['port']);
}
$client = new Client($this->urlInfo['host'], $port, $ssl);
}
/**
* Http Proxy
*/
if ($this->proxy) {
list($proxy_host, $proxy_port) = explode(':', $this->proxy);
if (!filter_var($proxy_host, FILTER_VALIDATE_IP)) {
$ip = Swoole\Coroutine::gethostbyname($proxy_host);
if (!$ip) {
$this->setError(CURLE_COULDNT_RESOLVE_PROXY, 'Could not resolve proxy: ' . $proxy_host);
return false;
} else {
$proxy_host = $ip;
}
}
$client->set(['http_proxy_host' => $proxy_host, 'http_proxy_port' => $proxy_port]);
}
/**
* Client Options
*/
if ($this->clientOptions) {
$client->set($this->clientOptions);
}
$client->setMethod($this->method);
/**
* Upload File
*/
if ($this->postData and is_array($this->postData)) {
foreach ($this->postData as $k => $v) {
if ($v instanceof CURLFile) {
$client->addFile($v->getFilename(), $k, $v->getMimeType() ?: 'application/octet-stream', $v->getPostFilename());
unset($this->postData[$k]);
}
}
}
/**
* Post Data
*/
if ($this->postData) {
if (is_string($this->postData) and empty($this->headers['Content-Type'])) {
$this->headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
$client->setData($this->postData);
$this->postData = [];
}
/**
* Http Header
*/
$this->headers['Host'] = $this->urlInfo['host'] . (isset($this->urlInfo['port']) ? (':' . $this->urlInfo['port']) : '');
$client->setHeaders($this->headers);
/**
* Execute
*/
$executeResult = $client->execute($this->getUrl());
if (!$executeResult) {
$errCode = $client->errCode;
if ($errCode == SWOOLE_ERROR_DNSLOOKUP_RESOLVE_FAILED or $errCode == SWOOLE_ERROR_DNSLOOKUP_RESOLVE_TIMEOUT) {
$this->setError(CURLE_COULDNT_RESOLVE_HOST, 'Could not resolve host: ' . $client->host);
}
$this->info['total_time'] = microtime(true) - $timeBegin;
return false;
}
if ($client->statusCode >= 300 and $client->statusCode < 400 and isset($client->headers['location'])) {
$redirectParsedUrl = $this->getRedirectUrl($client->headers['location']);
$redirectUrl = $this->unparseUrl($redirectParsedUrl);
if ($this->followLocation and (null === $this->maxRedirs or $this->info['redirect_count'] < $this->maxRedirs)) {
$isRedirect = true;
if (0 === $this->info['redirect_count']) {
$this->info['starttransfer_time'] = microtime(true) - $timeBegin;
$redirectBeginTime = microtime(true);
}
// force GET
if (in_array($client->statusCode, [301, 302, 303])) {
$this->method = 'GET';
}
if ($this->urlInfo['host'] !== $redirectParsedUrl['host'] or ($this->urlInfo['port'] ?? null) !== ($redirectParsedUrl['port'] ?? null) or $this->urlInfo['scheme'] !== $redirectParsedUrl['scheme']) {
// If host, port, and scheme are the same, reuse $client. Otherwise, release the old $client
$client = null;
}
if ($this->autoReferer) {
$this->headers['Referer'] = $this->info['url'];
}
$this->urlInfo = $redirectParsedUrl;
$this->info['url'] = $redirectUrl;
$this->info['redirect_count']++;
} else {
$this->info['redirect_url'] = $redirectUrl;
break;
}
} else {
break;
}
} while (true);
$this->info['total_time'] = microtime(true) - $timeBegin;
$this->info['http_code'] = $client->statusCode;
$this->info['content_type'] = $client->headers['content-type'] ?? '';
$this->info['size_download'] = $this->info['download_content_length'] = strlen($client->body);;
$this->info['speed_download'] = 1 / $this->info['total_time'] * $this->info['size_download'];
if (isset($redirectBeginTime)) {
$this->info['redirect_time'] = microtime(true) - $redirectBeginTime;
}
$headerContent = '';
if ($client->headers) {
$cb = $this->headerFunction;
if ($client->statusCode > 0) {
$row = 'HTTP/1.1 ' . $client->statusCode . ' ' . Swoole\Http\StatusCode::getReasonPhrase($client->statusCode) . "\r\n";
if ($cb) {
$cb($this, $row);
}
$headerContent .= $row;
}
foreach ($client->headers as $k => $v) {
$row = "$k: $v\r\n";
if ($cb) {
$cb($this, $row);
}
$headerContent .= $row;
}
$headerContent .= "\r\n";
$this->info['header_size'] = strlen($headerContent);
if ($cb) {
$cb($this, '');
}
} else {
$this->info['header_size'] = 0;
}
if ($client->body and $this->readFunction) {
$cb = $this->readFunction;
$cb($this, $this->outputStream, strlen($client->body));
}
if ($this->withHeader) {
$transfer = $headerContent . $client->body;
} else {
$transfer = $client->body;
}
if ($this->withHeaderOut) {
$headerOutContent = $client->getHeaderOut();
$this->info['request_header'] = $headerOutContent ? $headerOutContent . "\r\n\r\n" : '';
}
if ($this->withFileTime) {
if (!empty($client->headers['last-modified'])) {
$this->info['filetime'] = strtotime($client->headers['last-modified']);
} else {
$this->info['filetime'] = -1;
}
}
if ($this->returnTransfer) {
return $this->transfer = $transfer;
} else {
if ($this->outputStream) {
return fwrite($this->outputStream, $transfer) === strlen($transfer);
} else {
echo $transfer;
}
return true;
}
}
public function close(): void
{
$this->client = null;
}
private function setError($code, $msg = ''): void
{
$this->errCode = $code;
$this->errMsg = $msg ? $msg : self::ERRORS[$code];
}
private function getUrl(): string
{
if (empty($this->urlInfo['path'])) {
$url = '/';
} else {
$url = $this->urlInfo['path'];
}
if (!empty($this->urlInfo['query'])) {
$url .= '?' . $this->urlInfo['query'];
}
if (!empty($this->urlInfo['fragment'])) {
$url .= '#' . $this->urlInfo['fragment'];
}
return $url;
}
/**
* @param int $opt
* @param $value
* @return bool
* @throws Swoole\Curl\Exception
*/
public function setOption(int $opt, $value): bool
{
switch ($opt) {
/**
* Basic
*/
case CURLOPT_URL:
$this->create($value);
break;
case CURLOPT_RETURNTRANSFER:
$this->returnTransfer = $value;
$this->transfer = '';
break;
case CURLOPT_ENCODING:
if (empty($value)) {
$value = 'gzip';
}
$this->headers['Accept-Encoding'] = $value;
break;
case CURLOPT_PROXY:
$this->proxy = $value;
break;
case CURLOPT_NOBODY:
$this->nobody = boolval($value);
$this->method = 'HEAD';
break;
/**
* Ignore options
*/
case CURLOPT_SSLVERSION:
case CURLOPT_NOSIGNAL:
case CURLOPT_FRESH_CONNECT:
/**
* From PHP 5.1.3, this option has no effect: the raw output will always be returned when CURLOPT_RETURNTRANSFER is used.
*/
case CURLOPT_BINARYTRANSFER:
/**
* TODO
*/
case CURLOPT_VERBOSE:
case CURLOPT_DNS_CACHE_TIMEOUT:
break;
/**
* SSL
*/
case CURLOPT_SSL_VERIFYHOST:
break;
case CURLOPT_SSL_VERIFYPEER:
$this->clientOptions['ssl_verify_peer'] = $value;
break;
/**
* Http Post
*/
case CURLOPT_POST:
$this->method = 'POST';
break;
case CURLOPT_POSTFIELDS:
$this->postData = $value;
$this->method = 'POST';
break;
/**
* Upload
*/
case CURLOPT_SAFE_UPLOAD:
if (!$value) {
trigger_error('curl_setopt(): Disabling safe uploads is no longer supported', E_USER_WARNING);
}
break;
/**
* Http Header
*/
case CURLOPT_HTTPHEADER:
if (!is_array($value) and !($value instanceof Iterator)) {
trigger_error('swoole_curl_setopt(): You must pass either an object or an array with the CURLOPT_HTTPHEADER argument', E_USER_WARNING);
return false;
}
foreach ($value as $header) {
list($k, $v) = explode(':', $header);
$v = trim($v);
if ($v) {
$this->headers[$k] = $v;
}
}
break;
case CURLOPT_REFERER:
$this->headers['Referer'] = $value;
break;
case CURLINFO_HEADER_OUT:
$this->withHeaderOut = boolval($value);
break;
case CURLOPT_FILETIME:
$this->withFileTime = boolval($value);
break;
case CURLOPT_USERAGENT:
$this->headers['User-Agent'] = $value;
break;
case CURLOPT_CUSTOMREQUEST:
break;
case CURLOPT_PROTOCOLS:
if ($value > 3) {
throw new Swoole\Curl\Exception("option[{$opt}={$value}] not supported");
}
break;
case CURLOPT_HTTP_VERSION:
if ($value != CURL_HTTP_VERSION_1_1) {
trigger_error("swoole_curl: http version[{$value}] not supported", E_USER_WARNING);
}
break;
/**
* Http Cookie
*/
case CURLOPT_COOKIE:
$this->headers['Cookie'] = $value;
break;
case CURLOPT_CONNECTTIMEOUT:
$this->clientOptions['connect_timeout'] = $value;
break;
case CURLOPT_CONNECTTIMEOUT_MS:
$this->clientOptions['connect_timeout'] = $value / 1000;
break;
case CURLOPT_TIMEOUT:
$this->clientOptions['timeout'] = $value;
break;
case CURLOPT_TIMEOUT_MS:
$this->clientOptions['timeout'] = $value / 1000;
break;
case CURLOPT_FILE:
$this->outputStream = $value;
break;
case CURLOPT_HEADER:
$this->withHeader = $value;
break;
case CURLOPT_HEADERFUNCTION:
$this->headerFunction = $value;
break;
case CURLOPT_READFUNCTION:
$this->readFunction = $value;
break;
case CURLOPT_WRITEFUNCTION:
$this->writeFunction = $value;
break;
case CURLOPT_PROGRESSFUNCTION:
$this->progressFunction = $value;
break;
case CURLOPT_USERPWD:
$this->headers['Authorization'] = 'Basic ' . base64_encode($value);
break;
case CURLOPT_FOLLOWLOCATION:
$this->followLocation = $value;
break;
case CURLOPT_AUTOREFERER:
$this->autoReferer = $value;
break;
case CURLOPT_MAXREDIRS:
$this->maxRedirs = $value;
break;
default:
throw new Swoole\Curl\Exception("option[{$opt}] not supported");
}
return true;
}
public function reset(): void
{
}
public function getInfo()
{
return $this->info;
}
private function unparseUrl(array $parsedUrl): string
{
$scheme = ($parsedUrl['scheme'] ?? 'http') . '://';
$host = $parsedUrl['host'] ?? '';
$port = isset($parsedUrl['port']) ? ':' . $parsedUrl['port'] : '';
$user = $parsedUrl['user'] ?? '';
$pass = isset($parsedUrl['pass']) ? ':' . $parsedUrl['pass'] : '';
$pass = ($user or $pass) ? "$pass@" : '';
$path = $parsedUrl['path'] ?? '';
$query = (isset($parsedUrl['query']) and '' !== $parsedUrl['query']) ? '?' . $parsedUrl['query'] : '';
$fragment = isset($parsedUrl['fragment']) ? '#' . $parsedUrl['fragment'] : '';
return $scheme . $user . $pass . $host . $port . $path . $query . $fragment;
}
private function getRedirectUrl(string $location): array
{
$uri = parse_url($location);
if (isset($uri['host'])) {
$redirectUri = $uri;
} else {
if (!isset($location[0])) {
return [];
}
$redirectUri = $this->urlInfo;
$redirectUri['query'] = '';
if ('/' === $location[0]) {
$redirectUri['path'] = $location;
} else {
$path = dirname($redirectUri['path'] ?? '');
if ('.' === $path) {
$path = '/';
}
if (isset($location[1]) and './' === substr($location, 0, 2)) {
$location = substr($location, 2);
}
$redirectUri['path'] = $path . $location;
}
foreach ($uri as $k => $v) {
if (!in_array($k, ['path', 'query'])) {
$redirectUri[$k] = $v;
}
}
}
return $redirectUri;
}
}

View File

@@ -0,0 +1,142 @@
<?php
namespace Swoole\Http;
abstract class StatusCode
{
const CONTINUE = 100;
const SWITCHING_PROTOCOLS = 101;
const PROCESSING = 102;
const OK = 200;
const CREATED = 201;
const ACCEPTED = 202;
const NON_AUTHORITATIVE_INFORMATION = 203;
const NO_CONTENT = 204;
const RESET_CONTENT = 205;
const PARTIAL_CONTENT = 206;
const MULTI_STATUS = 207;
const ALREADY_REPORTED = 208;
const IM_USED = 226;
const MULTIPLE_CHOICES = 300;
const MOVED_PERMANENTLY = 301;
const FOUND = 302;
const SEE_OTHER = 303;
const NOT_MODIFIED = 304;
const USE_PROXY = 305;
const SWITCH_PROXY = 306;
const TEMPORARY_REDIRECT = 307;
const PERMANENT_REDIRECT = 308;
const BAD_REQUEST = 400;
const UNAUTHORIZED = 401;
const PAYMENT_REQUIRED = 402;
const FORBIDDEN = 403;
const NOT_FOUND = 404;
const METHOD_NOT_ALLOWED = 405;
const NOT_ACCEPTABLE = 406;
const PROXY_AUTHENTICATION_REQUIRED = 407;
const REQUEST_TIME_OUT = 408;
const CONFLICT = 409;
const GONE = 410;
const LENGTH_REQUIRED = 411;
const PRECONDITION_FAILED = 412;
const REQUEST_ENTITY_TOO_LARGE = 413;
const REQUEST_URI_TOO_LARGE = 414;
const UNSUPPORTED_MEDIA_TYPE = 415;
const REQUESTED_RANGE_NOT_SATISFIABLE = 416;
const EXPECTATION_FAILED = 417;
const MISDIRECTED_REQUEST = 421;
const UNPROCESSABLE_ENTITY = 422;
const LOCKED = 423;
const FAILED_DEPENDENCY = 424;
const UNORDERED_COLLECTION = 425;
const UPGRADE_REQUIRED = 426;
const PRECONDITION_REQUIRED = 428;
const TOO_MANY_REQUESTS = 429;
const REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
const UNAVAILABLE_FOR_LEGAL_REASONS = 451;
const INTERNAL_SERVER_ERROR = 500;
const NOT_IMPLEMENTED = 501;
const BAD_GATEWAY = 502;
const SERVICE_UNAVAILABLE = 503;
const GATEWAY_TIME_OUT = 504;
const HTTP_VERSION_NOT_SUPPORTED = 505;
const VARIANT_ALSO_NEGOTIATES = 506;
const INSUFFICIENT_STORAGE = 507;
const LOOP_DETECTED = 508;
const NOT_EXTENDED = 510;
const NETWORK_AUTHENTICATION_REQUIRED = 511;
protected static $reasonPhrases = [
self::CONTINUE => 'Continue',
self::SWITCHING_PROTOCOLS => 'Switching Protocols',
self::PROCESSING => 'Processing',
self::OK => 'OK',
self::CREATED => 'Created',
self::ACCEPTED => 'Accepted',
self::NON_AUTHORITATIVE_INFORMATION => 'Non-Authoritative Information',
self::NO_CONTENT => 'No Content',
self::RESET_CONTENT => 'Reset Content',
self::PARTIAL_CONTENT => 'Partial Content',
self::MULTI_STATUS => 'Multi-status',
self::ALREADY_REPORTED => 'Already Reported',
self::IM_USED => 'IM Used',
self::MULTIPLE_CHOICES => 'Multiple Choices',
self::MOVED_PERMANENTLY => 'Moved Permanently',
self::FOUND => 'Found',
self::SEE_OTHER => 'See Other',
self::NOT_MODIFIED => 'Not Modified',
self::USE_PROXY => 'Use Proxy',
self::SWITCH_PROXY => 'Switch Proxy',
self::TEMPORARY_REDIRECT => 'Temporary Redirect',
self::PERMANENT_REDIRECT => 'Permanent Redirect',
self::BAD_REQUEST => 'Bad Request',
self::UNAUTHORIZED => 'Unauthorized',
self::PAYMENT_REQUIRED => 'Payment Required',
self::FORBIDDEN => 'Forbidden',
self::NOT_FOUND => 'Not Found',
self::METHOD_NOT_ALLOWED => 'Method Not Allowed',
self::NOT_ACCEPTABLE => 'Not Acceptable',
self::PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required',
self::REQUEST_TIME_OUT => 'Request Time-out',
self::CONFLICT => 'Conflict',
self::GONE => 'Gone',
self::LENGTH_REQUIRED => 'Length Required',
self::PRECONDITION_FAILED => 'Precondition Failed',
self::REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large',
self::REQUEST_URI_TOO_LARGE => 'Request-URI Too Large',
self::UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type',
self::REQUESTED_RANGE_NOT_SATISFIABLE => 'Requested range not satisfiable',
self::EXPECTATION_FAILED => 'Expectation Failed',
self::MISDIRECTED_REQUEST => 'Unprocessable Entity',
self::UNPROCESSABLE_ENTITY => 'Unprocessable Entity',
self::LOCKED => 'Locked',
self::FAILED_DEPENDENCY => 'Failed Dependency',
self::UNORDERED_COLLECTION => 'Unordered Collection',
self::UPGRADE_REQUIRED => 'Upgrade Required',
self::PRECONDITION_REQUIRED => 'Precondition Required',
self::TOO_MANY_REQUESTS => 'Too Many Requests',
self::REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large',
self::UNAVAILABLE_FOR_LEGAL_REASONS => 'Unavailable For Legal Reasons',
self::INTERNAL_SERVER_ERROR => 'Internal Server Error',
self::NOT_IMPLEMENTED => 'Not Implemented',
self::BAD_GATEWAY => 'Bad Gateway',
self::SERVICE_UNAVAILABLE => 'Service Unavailable',
self::GATEWAY_TIME_OUT => 'Gateway Time-out',
self::HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported',
self::VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates',
self::INSUFFICIENT_STORAGE => 'Insufficient Storage',
self::LOOP_DETECTED => 'Loop Detected',
self::NOT_EXTENDED => 'Not Extended',
self::NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required'
];
/**
* getReasonPhrase
* @param int $value
* @return string
*/
public static function getReasonPhrase(int $value): string
{
return static::$reasonPhrases[$value] ?? 'Unknown';
}
}

View File

@@ -0,0 +1,237 @@
<?php
namespace Swoole;
class StringObject
{
/**
* @var string
*/
protected $string;
/**
* StringObject constructor.
* @param $string
*/
public function __construct(string $string = '')
{
$this->string = $string;
}
/**
* @return int
*/
public function length(): int
{
return strlen($this->string);
}
/**
* @param string $needle
* @param int $offset
* @return bool|int
*/
public function indexOf(string $needle, int $offset = 0)
{
return strpos($this->string, $needle, $offset);
}
/**
* @param string $needle
* @param int $offset
* @return bool|int
*/
public function lastIndexOf(string $needle, int $offset = 0)
{
return strrpos($this->string, $needle, $offset);
}
/**
* @param string $needle
* @param int $offset
* @return bool|int
*/
public function pos(string $needle, int $offset = 0)
{
return strpos($this->string, $needle, $offset);
}
/**
* @param string $needle
* @param int $offset
* @return bool|int
*/
public function rpos(string $needle, int $offset = 0)
{
return strrpos($this->string, $needle, $offset);
}
/**
* @param string $needle
* @return bool|int
*/
public function ipos(string $needle)
{
return stripos($this->string, $needle);
}
/**
* @return static
*/
public function lower(): self
{
return new static(strtolower($this->string));
}
/**
* @return static
*/
public function upper(): self
{
return new static(strtoupper($this->string));
}
/**
* @return static
*/
public function trim(): self
{
return new static(trim($this->string));
}
/**
* @return static
*/
public function lrim(): self
{
return new static(ltrim($this->string));
}
/**
* @return static
*/
public function rtrim(): self
{
return new static(rtrim($this->string));
}
/**
* @param int $offset
* @param mixed ...$length
* @return static
*/
public function substr(int $offset, ...$length): self
{
return new static(substr($this->string, $offset, ...$length));
}
/**
* @param $n
* @return StringObject
*/
public function repeat($n)
{
return new static(str_repeat($this->string, $n));
}
/**
* @param string $search
* @param string $replace
* @param null $count
* @return static
*/
public function replace(string $search, string $replace, &$count = null): self
{
return new static(str_replace($search, $replace, $this->string, $count));
}
/**
* @param string $needle
* @return bool
*/
public function startsWith(string $needle): bool
{
return strpos($this->string, $needle) === 0;
}
/**
* @param string $subString
* @return bool
*/
public function contains(string $subString): bool
{
return strpos($this->string, $subString) !== false;
}
/**
* @param string $needle
* @return bool
*/
public function endsWith(string $needle): bool
{
return strrpos($this->string, $needle) === (strlen($needle) - 1);
}
/**
* @param string $delimiter
* @param int $limit
* @return ArrayObject
*/
public function split(string $delimiter, int $limit = PHP_INT_MAX): ArrayObject
{
return static::detectArrayType(explode($delimiter, $this->string, $limit));
}
/**
* @param int $index
* @return string
*/
public function char(int $index): string
{
return $this->string[$index];
}
/**
* @param int $chunkLength
* @param string $chunkEnd
* @return static
*/
public function chunkSplit(int $chunkLength = 1, string $chunkEnd = ''): self
{
return new static(chunk_split($this->string, $chunkLength, $chunkEnd));
}
/**
* @param int $splitLength
* @return ArrayObject
*/
public function chunk($splitLength = 1): ArrayObject
{
return static::detectArrayType(str_split($this->string, $splitLength));
}
/**
* @return string
*/
public function toString()
{
return $this->string;
}
/**
* @return string
*/
public function __toString(): string
{
return $this->string;
}
/**
* @param array $value
* @return ArrayObject
*/
protected static function detectArrayType(array $value): ArrayObject
{
return new ArrayObject($value);
}
}

View File

@@ -0,0 +1,49 @@
<?php
if (SWOOLE_USE_SHORTNAME) {
/**
* @param string $string
* @return Swoole\StringObject
*/
function _string(string $string = ''): Swoole\StringObject
{
return new Swoole\StringObject($string);
}
/**
* @param array $array
* @return Swoole\ArrayObject
*/
function _array(array $array = []): Swoole\ArrayObject
{
return new Swoole\ArrayObject($array);
}
}
/**
* @param string $string
* @return Swoole\StringObject
*/
function swoole_string(string $string = ''): Swoole\StringObject
{
return new Swoole\StringObject($string);
}
/**
* @param array $array
* @return Swoole\ArrayObject
*/
function swoole_array(array $array = []): Swoole\ArrayObject
{
return new Swoole\ArrayObject($array);
}
/**
* @param array $array
* @param $key
* @param $default_value
* @return mixed
*/
function swoole_array_default_value(array $array, $key, $default_value = '')
{
return array_key_exists($key, $array) ? $array[$key] : $default_value;
}