diff --git a/libs/arr-utils/src/Arr.php b/libs/arr-utils/src/Arr.php index 92d2f96..5cd13cb 100644 --- a/libs/arr-utils/src/Arr.php +++ b/libs/arr-utils/src/Arr.php @@ -11,6 +11,7 @@ /** * Class Arr * alias of the StringHelper + * * @package Toolkit\ArrUtil */ class Arr extends ArrayHelper diff --git a/libs/arr-utils/src/ArrBuffer.php b/libs/arr-utils/src/ArrBuffer.php index 39179f5..b585771 100644 --- a/libs/arr-utils/src/ArrBuffer.php +++ b/libs/arr-utils/src/ArrBuffer.php @@ -10,6 +10,7 @@ /** * Class ArrBuffer + * * @package Toolkit\ArrUtil */ final class ArrBuffer @@ -22,6 +23,7 @@ final class ArrBuffer /** * constructor. + * * @param string $content */ public function __construct(string $content = '') diff --git a/libs/arr-utils/src/ArrayHelper.php b/libs/arr-utils/src/ArrayHelper.php index f30e15b..51c8bae 100644 --- a/libs/arr-utils/src/ArrayHelper.php +++ b/libs/arr-utils/src/ArrayHelper.php @@ -9,45 +9,84 @@ namespace Toolkit\ArrUtil; +use ArrayAccess; +use ArrayObject; +use stdClass; use Toolkit\Collection\CollectionInterface; +use Traversable; +use function array_change_key_case; +use function array_diff; +use function array_filter; +use function array_intersect; +use function array_key_exists; +use function array_keys; +use function array_map; +use function array_merge; +use function array_reduce; +use function array_shift; +use function array_values; +use function array_walk_recursive; +use function count; +use function explode; +use function get_class; +use function gettype; +use function in_array; +use function is_array; +use function is_int; +use function is_numeric; +use function is_object; +use function is_resource; +use function is_scalar; +use function is_string; +use function mb_strlen; +use function strlen; +use function strpos; +use function strtolower; +use function trim; /** * Class ArrayHelper + * * @package Toolkit\ArrUtil */ class ArrayHelper { /** * Determine whether the given value is array accessible. - * @param mixed $value + * + * @param mixed $value + * * @return bool */ public static function accessible($value): bool { - return \is_array($value) || $value instanceof \ArrayAccess; + return is_array($value) || $value instanceof ArrayAccess; } /** * Determines if an array is associative. * An array is "associative" if it doesn't have sequential numerical keys beginning with zero. - * @param array $array + * + * @param array $array + * * @return bool */ public static function isAssoc(array $array): bool { - $keys = \array_keys($array); + $keys = array_keys($array); - return \array_keys($keys) !== $keys; + return array_keys($keys) !== $keys; } /** * @param mixed $array - * @return \Traversable + * + * @return Traversable */ - public static function toIterator($array): \Traversable + public static function toIterator($array): Traversable { - if (!$array instanceof \Traversable) { - $array = new \ArrayObject((array)$array); + if (!$array instanceof Traversable) { + $array = new ArrayObject((array)$array); } return $array; @@ -55,22 +94,24 @@ public static function toIterator($array): \Traversable /** * array data to object - * @param array|\Traversable $array - * @param string $class + * + * @param array|Traversable $array + * @param string $class + * * @return mixed */ - public static function toObject($array, $class = \stdClass::class) + public static function toObject($array, $class = stdClass::class) { $object = new $class; foreach ($array as $name => $value) { - $name = \trim($name); + $name = trim($name); - if (!$name || \is_numeric($name)) { + if (!$name || is_numeric($name)) { continue; } - $object->$name = \is_array($value) ? self::toObject($value) : $value; + $object->$name = is_array($value) ? self::toObject($value) : $value; } return $object; @@ -78,14 +119,16 @@ public static function toObject($array, $class = \stdClass::class) /** * Get Multi - 获取多个, 可以设置默认值 + * * @param array $data array data * @param array $needKeys - * $needKeys = [ - * 'name', - * 'password', - * 'status' => '1' - * ] + * $needKeys = [ + * 'name', + * 'password', + * 'status' => '1' + * ] * @param bool|false $unsetKey + * * @return array */ public static function gets(array &$data, array $needKeys = [], $unsetKey = false): array @@ -93,19 +136,19 @@ public static function gets(array &$data, array $needKeys = [], $unsetKey = fals $needed = []; foreach ($needKeys as $key => $default) { - if (\is_int($key)) { - $key = $default; + if (is_int($key)) { + $key = $default; $default = null; } if (isset($data[$key])) { $value = $data[$key]; - if (\is_int($default)) { + if (is_int($default)) { $value = (int)$value; - } elseif (\is_string($default)) { - $value = \trim($value); - } elseif (\is_array($default)) { + } elseif (is_string($default)) { + $value = trim($value); + } elseif (is_array($default)) { $value = (array)$value; } @@ -124,13 +167,15 @@ public static function gets(array &$data, array $needKeys = [], $unsetKey = fals /** * 递归合并两个多维数组,后面的值将会递归覆盖原来的值 - * @param array|null $src - * @param array $new + * + * @param array|null $src + * @param array $new + * * @return array */ public static function merge($src, array $new): array { - if (!$src || !\is_array($src)) { + if (!$src || !is_array($src)) { return $new; } @@ -139,13 +184,13 @@ public static function merge($src, array $new): array } foreach ($new as $key => $value) { - if (\is_int($key)) { + if (is_int($key)) { if (isset($src[$key])) { $src[] = $value; } else { $src[$key] = $value; } - } elseif (\array_key_exists($key, $src) && \is_array($value)) { + } elseif (array_key_exists($key, $src) && is_array($value)) { $src[$key] = self::merge($src[$key], $new[$key]); } else { $src[$key] = $value; @@ -157,9 +202,12 @@ public static function merge($src, array $new): array /** * 递归合并多个多维数组, + * * @from yii2 * Merges two or more arrays into one recursively. + * * @param array $args + * * @return array the merged array (the original arrays are not changed.) */ public static function merge2(...$args): array @@ -172,13 +220,13 @@ public static function merge2(...$args): array $next = array_shift($args); foreach ($next as $k => $v) { - if (\is_int($k)) { + if (is_int($k)) { if (isset($res[$k])) { $res[] = $v; } else { $res[$k] = $v; } - } elseif (\is_array($v) && isset($res[$k]) && \is_array($res[$k])) { + } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) { $res[$k] = self::merge2($res[$k], $v); } else { $res[$k] = $v; @@ -191,17 +239,19 @@ public static function merge2(...$args): array /** * 清理数组值的空白 + * * @param array $data + * * @return array|string */ public static function valueTrim(array $data) { - if (\is_scalar($data)) { - return \trim($data); + if (is_scalar($data)) { + return trim($data); } - \array_walk_recursive($data, function (&$value) { - $value = \trim($value); + array_walk_recursive($data, function (&$value) { + $value = trim($value); }); return $data; @@ -209,17 +259,20 @@ public static function valueTrim(array $data) /** * 不区分大小写检测数据键名是否存在 + * * @param int|string $key * @param array $arr + * * @return bool */ public static function keyExists($key, array $arr): bool { - return \array_key_exists(\strtolower($key), \array_change_key_case($arr)); + return array_key_exists(strtolower($key), array_change_key_case($arr)); } /** * @param array $arr + * * @return array */ public static function valueToLower(array $arr): array @@ -229,6 +282,7 @@ public static function valueToLower(array $arr): array /** * @param array $arr + * * @return array */ public static function valueToUpper(array $arr): array @@ -238,20 +292,22 @@ public static function valueToUpper(array $arr): array /** * 将数组中的值全部转为大写或小写 + * * @param array $arr * @param int $toUpper 1 值大写 0 值小写 + * * @return array */ public static function changeValueCase($arr, $toUpper = 1): array { $function = $toUpper ? 'strtoupper' : 'strtolower'; - $newArr = []; //格式化后的数组 + $newArr = []; //格式化后的数组 foreach ($arr as $k => $v) { - if (\is_array($v)) { + if (is_array($v)) { $newArr[$k] = self::changeValueCase($v, $toUpper); } else { - $v = \trim($v); + $v = trim($v); $newArr[$k] = $function($v); } } @@ -262,63 +318,69 @@ public static function changeValueCase($arr, $toUpper = 1): array /** * ******* 检查 一个或多个值是否全部存在数组中 ******* * 有一个不存在即返回 false + * * @param string|array $check * @param array $sampleArr 只能检查一维数组 - * 注: 不分类型, 区分大小写 2 == '2' ‘a' != 'A' + * 注: 不分类型, 区分大小写 2 == '2' ‘a' != 'A' + * * @return bool */ public static function valueExistsAll($check, array $sampleArr): bool { // 以逗号分隔的会被拆开,组成数组 - if (\is_string($check)) { - $check = \trim($check, ', '); - $check = \strpos($check, ',') !== false ? explode(',', $check) : [$check]; + if (is_string($check)) { + $check = trim($check, ', '); + $check = strpos($check, ',') !== false ? explode(',', $check) : [$check]; } - return !\array_diff((array)$check, $sampleArr); + return !array_diff((array)$check, $sampleArr); } /** * ******* 检查 一个或多个值是否存在数组中 ******* * 有一个存在就返回 true 都不存在 return false + * * @param string|array $check * @param array $sampleArr 只能检查一维数组 + * * @return bool */ public static function valueExistsOne($check, array $sampleArr): bool { // 以逗号分隔的会被拆开,组成数组 - if (\is_string($check)) { - $check = \trim($check, ', '); - $check = \strpos($check, ',') !== false ? explode(',', $check) : [$check]; + if (is_string($check)) { + $check = trim($check, ', '); + $check = strpos($check, ',') !== false ? explode(',', $check) : [$check]; } - return (bool)\array_intersect((array)$check, $sampleArr); + return (bool)array_intersect((array)$check, $sampleArr); } /** * ******* 不区分大小写,检查 一个或多个值是否 全存在数组中 ******* * 有一个不存在即返回 false + * * @param string|array $need - * @param array $arr 只能检查一维数组 + * @param array $arr 只能检查一维数组 * @param bool $type 是否同时验证类型 + * * @return bool | string 不存在的会返回 检查到的 字段,判断时 请使用 ArrHelper::existsAll($need,$arr)===true 来验证是否全存在 */ public static function existsAll($need, $arr, $type = false) { - if (\is_array($need)) { + if (is_array($need)) { foreach ((array)$need as $v) { self::existsAll($v, $arr, $type); } - } elseif (\strpos($need, ',') !== false) { - $need = \explode(',', $need); + } elseif (strpos($need, ',') !== false) { + $need = explode(',', $need); self::existsAll($need, $arr, $type); } else { - $arr = self::valueToLower($arr);//小写 - $need = \strtolower(trim($need));//小写 + $arr = self::valueToLower($arr);//小写 + $need = strtolower(trim($need));//小写 - if (!\in_array($need, $arr, $type)) { + if (!in_array($need, $arr, $type)) { return $need; } } @@ -329,14 +391,16 @@ public static function existsAll($need, $arr, $type = false) /** * ******* 不区分大小写,检查 一个或多个值是否存在数组中 ******* * 有一个存在就返回 true 都不存在 return false + * * @param string|array $need - * @param array $arr 只能检查一维数组 + * @param array $arr 只能检查一维数组 * @param bool $type 是否同时验证类型 + * * @return bool */ public static function existsOne($need, $arr, $type = false): bool { - if (\is_array($need)) { + if (is_array($need)) { foreach ((array)$need as $v) { $result = self::existsOne($v, $arr, $type); if ($result) { @@ -350,10 +414,10 @@ public static function existsOne($need, $arr, $type = false): bool return self::existsOne($need, $arr, $type); } - $arr = self::changeValueCase($arr);//小写 - $need = \strtolower($need);//小写 + $arr = self::changeValueCase($arr);//小写 + $need = strtolower($need);//小写 - if (\in_array($need, $arr, $type)) { + if (in_array($need, $arr, $type)) { return true; } } @@ -363,12 +427,14 @@ public static function existsOne($need, $arr, $type = false): bool /** * get key Max Width - * @param array $data - * [ + * + * @param array $data + * [ * 'key1' => 'value1', * 'key2-test' => 'value2', - * ] - * @param bool $expectInt + * ] + * @param bool $expectInt + * * @return int */ public static function getKeyMaxWidth(array $data, $expectInt = true): int @@ -377,8 +443,8 @@ public static function getKeyMaxWidth(array $data, $expectInt = true): int foreach ($data as $key => $value) { // key is not a integer - if (!$expectInt || !\is_numeric($key)) { - $width = \mb_strlen($key, 'UTF-8'); + if (!$expectInt || !is_numeric($key)) { + $width = mb_strlen($key, 'UTF-8'); $keyMaxWidth = $width > $keyMaxWidth ? $width : $keyMaxWidth; } } @@ -390,10 +456,12 @@ public static function getKeyMaxWidth(array $data, $expectInt = true): int /** * Get data from array or object by path. * Example: `DataCollector::getByPath($array, 'foo.bar.yoo')` equals to $array['foo']['bar']['yoo']. - * @param array|\ArrayAccess $data An array or object to get value. - * @param mixed $path The key path. - * @param mixed $default - * @param string $separator Separator of paths. + * + * @param array|ArrayAccess $data An array or object to get value. + * @param mixed $path The key path. + * @param mixed $default + * @param string $separator Separator of paths. + * * @return mixed Found value, null if not exists. */ public static function getByPath($data, string $path, $default = null, string $separator = '.') @@ -404,19 +472,16 @@ public static function getByPath($data, string $path, $default = null, string $s // Error: will clear '0'. eg 'some-key.0' // if (!$nodes = array_filter(explode($separator, $path))) { - if (!$nodes = \explode($separator, $path)) { + if (!$nodes = explode($separator, $path)) { return $default; } $dataTmp = $data; foreach ($nodes as $arg) { - if (\is_object($dataTmp) && isset($dataTmp->$arg)) { + if (is_object($dataTmp) && isset($dataTmp->$arg)) { $dataTmp = $dataTmp->$arg; - } elseif ( - (\is_array($dataTmp) || $dataTmp instanceof \ArrayAccess) - && isset($dataTmp[$arg]) - ) { + } elseif ((is_array($dataTmp) || $dataTmp instanceof ArrayAccess) && isset($dataTmp[$arg])) { $dataTmp = $dataTmp[$arg]; } else { return $default; @@ -428,9 +493,11 @@ public static function getByPath($data, string $path, $default = null, string $s /** * findValueByNodes - * @param array $data - * @param array $nodes - * @param mixed $default + * + * @param array $data + * @param array $nodes + * @param mixed $default + * * @return mixed */ public static function getValueByNodes(array $data, array $nodes, $default = null) @@ -451,26 +518,27 @@ public static function getValueByNodes(array $data, array $nodes, $default = nul /** * setByPath - * @param array|\ArrayAccess &$data - * @param string $path - * @param mixed $value - * @param string $separator + * + * @param array|ArrayAccess &$data + * @param string $path + * @param mixed $value + * @param string $separator */ public static function setByPath(&$data, string $path, $value, string $separator = '.'): void { - if (false === \strpos($path, $separator)) { + if (false === strpos($path, $separator)) { $data[$path] = $value; return; } - if (!$nodes = \array_filter(\explode($separator, $path))) { + if (!$nodes = array_filter(explode($separator, $path))) { return; } $dataTmp = &$data; foreach ($nodes as $node) { - if (\is_array($dataTmp)) { + if (is_array($dataTmp)) { if (empty($dataTmp[$node])) { $dataTmp[$node] = []; } @@ -493,7 +561,9 @@ public static function setByPath(&$data, string $path, $value, string $separator /** * Collapse an array of arrays into a single array. - * @param array $array + * + * @param array $array + * * @return array */ public static function collapse(array $array): array @@ -503,7 +573,7 @@ public static function collapse(array $array): array foreach ($array as $values) { if ($values instanceof CollectionInterface) { $values = $values->all(); - } elseif (!\is_array($values)) { + } elseif (!is_array($values)) { continue; } @@ -511,20 +581,22 @@ public static function collapse(array $array): array $results[] = $values; } - return \array_merge(...$results); + return array_merge(...$results); } /** * Cross join the given arrays, returning all possible permutations. - * @param array ...$arrays + * + * @param array ...$arrays + * * @return array */ public static function crossJoin(...$arrays): array { - return \array_reduce($arrays, function ($results, $array) { - return static::collapse(\array_map(function ($parent) use ($array) { - return \array_map(function ($item) use ($parent) { - return \array_merge($parent, [$item]); + return array_reduce($arrays, function ($results, $array) { + return static::collapse(array_map(function ($parent) use ($array) { + return array_map(function ($item) use ($parent) { + return array_merge($parent, [$item]); }, $array); }, $results)); }, [[]]); @@ -532,18 +604,22 @@ public static function crossJoin(...$arrays): array /** * Divide an array into two arrays. One with keys and the other with values. - * @param array $array + * + * @param array $array + * * @return array */ public static function divide($array): array { - return [\array_keys($array), \array_values($array)]; + return [array_keys($array), array_values($array)]; } /** * Flatten a multi-dimensional associative array with dots. - * @param array $array - * @param string $prepend + * + * @param array $array + * @param string $prepend + * * @return array */ public static function dot(array $array, string $prepend = ''): array @@ -551,8 +627,8 @@ public static function dot(array $array, string $prepend = ''): array $results = []; foreach ($array as $key => $value) { - if (\is_array($value) && !empty($value)) { - $results = \array_merge($results, static::dot($value, $prepend . $key . '.')); + if (is_array($value) && !empty($value)) { + $results = array_merge($results, static::dot($value, $prepend . $key . '.')); } else { $results[$prepend . $key] = $value; } @@ -563,8 +639,10 @@ public static function dot(array $array, string $prepend = ''): array /** * Get all of the given array except for a specified array of items. - * @param array $array - * @param array|string $keys + * + * @param array $array + * @param array|string $keys + * * @return array */ public static function except(array $array, $keys): array @@ -576,13 +654,15 @@ public static function except(array $array, $keys): array /** * Determine if the given key exists in the provided array. - * @param \ArrayAccess|array $array - * @param string|int $key + * + * @param ArrayAccess|array $array + * @param string|int $key + * * @return bool */ public static function exists(array $array, $key): bool { - if ($array instanceof \ArrayAccess) { + if ($array instanceof ArrayAccess) { return $array->offsetExists($key); } @@ -591,9 +671,11 @@ public static function exists(array $array, $key): bool /** * Add an element to an array using "dot" notation if it doesn't exist. - * @param array $array - * @param string $key - * @param mixed $value + * + * @param array $array + * @param string $key + * @param mixed $value + * * @return array */ public static function add(array $array, $key, $value): array @@ -607,9 +689,11 @@ public static function add(array $array, $key, $value): array /** * Get an item from an array using "dot" notation. - * @param \ArrayAccess|array $array - * @param string $key - * @param mixed $default + * + * @param ArrayAccess|array $array + * @param string $key + * @param mixed $default + * * @return mixed */ public static function get($array, $key, $default = null) @@ -640,9 +724,11 @@ public static function get($array, $key, $default = null) /** * Set an array item to a given value using "dot" notation. * If no key is given to the method, the entire array will be replaced. - * @param array $array - * @param string $key - * @param mixed $value + * + * @param array $array + * @param string $key + * @param mixed $value + * * @return array */ public static function set(array &$array, $key, $value): array @@ -651,29 +737,31 @@ public static function set(array &$array, $key, $value): array return ($array = $value); } - $keys = \explode('.', $key); + $keys = explode('.', $key); - while (\count($keys) > 1) { + while (count($keys) > 1) { $key = array_shift($keys); // If the key doesn't exist at this depth, we will just create an empty array // to hold the next value, allowing us to create the arrays to hold final // values at the correct depth. Then we'll keep digging into the array. - if (!isset($array[$key]) || !\is_array($array[$key])) { + if (!isset($array[$key]) || !is_array($array[$key])) { $array[$key] = []; } $array = &$array[$key]; } - $array[\array_shift($keys)] = $value; + $array[array_shift($keys)] = $value; return $array; } /** * Flatten a multi-dimensional array into a single level. - * @param array $array - * @param int $depth + * + * @param array $array + * @param int $depth + * * @return array */ public static function flatten($array, $depth = INF): array @@ -681,30 +769,32 @@ public static function flatten($array, $depth = INF): array return array_reduce($array, function ($result, $item) use ($depth) { $item = $item instanceof CollectionInterface ? $item->all() : $item; - if (!\is_array($item)) { - return \array_merge($result, [$item]); + if (!is_array($item)) { + return array_merge($result, [$item]); } if ($depth === 1) { - return \array_merge($result, \array_values($item)); + return array_merge($result, array_values($item)); } - return \array_merge($result, static::flatten($item, $depth - 1)); + return array_merge($result, static::flatten($item, $depth - 1)); }, []); } /** * Remove one or many array items from a given array using "dot" notation. - * @param array $array - * @param array|string $keys + * + * @param array $array + * @param array|string $keys + * * @return void */ public static function forget(&$array, $keys): void { $original = &$array; - $keys = (array)$keys; + $keys = (array)$keys; - if (\count($keys) === 0) { + if (count($keys) === 0) { return; } @@ -721,10 +811,10 @@ public static function forget(&$array, $keys): void // clean up before each pass $array = &$original; - while (\count($parts) > 1) { + while (count($parts) > 1) { $part = array_shift($parts); - if (isset($array[$part]) && \is_array($array[$part])) { + if (isset($array[$part]) && is_array($array[$part])) { $array = &$array[$part]; } else { continue 2; @@ -737,8 +827,10 @@ public static function forget(&$array, $keys): void /** * Check if an item or items exist in an array using "dot" notation. - * @param \ArrayAccess|array $array - * @param string|array $keys + * + * @param ArrayAccess|array $array + * @param string|array $keys + * * @return bool */ public static function has($array, $keys): bool @@ -779,9 +871,11 @@ public static function has($array, $keys): bool /** * Push an item onto the beginning of an array. - * @param array $array - * @param mixed $value - * @param mixed $key + * + * @param array $array + * @param mixed $value + * @param mixed $key + * * @return array */ public static function prepend($array, $value, $key = null): array @@ -797,9 +891,11 @@ public static function prepend($array, $value, $key = null): array /** * remove the $key of the $arr, and return value. + * * @param string $key * @param array $arr * @param mixed $default + * * @return mixed */ public static function remove(&$arr, $key, $default = null) @@ -816,9 +912,11 @@ public static function remove(&$arr, $key, $default = null) /** * Get a value from the array, and remove it. - * @param array $array - * @param string $key - * @param mixed $default + * + * @param array $array + * @param string $key + * @param mixed $default + * * @return mixed */ public static function pull(&$array, $key, $default = null) @@ -832,8 +930,10 @@ public static function pull(&$array, $key, $default = null) /** * Get a subset of the items from the given array. - * @param array $array - * @param array|string $keys + * + * @param array $array + * @param array|string $keys + * * @return array */ public static function only($array, $keys): array @@ -843,7 +943,9 @@ public static function only($array, $keys): array /** * Shuffle the given array and return the result. - * @param array $array + * + * @param array $array + * * @return array */ public static function shuffle($array): array @@ -855,8 +957,10 @@ public static function shuffle($array): array /** * Filter the array using the given callback. - * @param array $array - * @param callable $callback + * + * @param array $array + * @param callable $callback + * * @return array */ public static function where($array, callable $callback): array @@ -866,12 +970,14 @@ public static function where($array, callable $callback): array /** * If the given value is not an array, wrap it in one. - * @param mixed $value + * + * @param mixed $value + * * @return array */ public static function wrap($value): array { - return !\is_array($value) ? (array)$value : $value; + return !is_array($value) ? (array)$value : $value; } //////////////////////////////////////////////////////////// @@ -880,13 +986,15 @@ public static function wrap($value): array /** * array 递归 转换成 字符串 - * @param array $array [大于1200字符 strlen($string)>1200 + * + * @param array $array [大于1200字符 strlen($string)>1200 * @param int $length * @param array|int $cycles [至多循环六次 $num >= 6 * @param bool $showKey * @param bool $addMark - * @param string $separator + * @param string $separator * @param string $string + * * @return string */ public static function toString( @@ -898,32 +1006,32 @@ public static function toString( $separator = ', ', $string = '' ): string { - if (!\is_array($array) || empty($array)) { + if (!is_array($array) || empty($array)) { return ''; } $mark = $addMark ? '\'' : ''; - $num = 0; + $num = 0; foreach ($array as $key => $value) { $num++; - if ($num >= $cycles || \strlen($string) > (int)$length) { + if ($num >= $cycles || strlen($string) > (int)$length) { $string .= '... ...'; break; } $keyStr = $showKey ? $key . '=>' : ''; - if (\is_array($value)) { + if (is_array($value)) { $string .= $keyStr . 'Array(' . self::toString($value, $length, $cycles, $showKey, $addMark, $separator, $string) . ')' . $separator; - } elseif (\is_object($value)) { - $string .= $keyStr . 'Object(' . \get_class($value) . ')' . $separator; - } elseif (\is_resource($value)) { + } elseif (is_object($value)) { + $string .= $keyStr . 'Object(' . get_class($value) . ')' . $separator; + } elseif (is_resource($value)) { $string .= $keyStr . 'Resource(' . get_resource_type($value) . ')' . $separator; } else { - $value = \strlen($value) > 150 ? substr($value, 0, 150) : $value; + $value = strlen($value) > 150 ? substr($value, 0, 150) : $value; $string .= $mark . $keyStr . trim(htmlspecialchars($value)) . $mark . $separator; } } @@ -945,6 +1053,7 @@ public static function toStringNoKey( /** * @param array $array * @param int $length + * * @return mixed|null|string|string[] */ public static function toFormatString($array, $length = 400) @@ -957,7 +1066,7 @@ public static function toFormatString($array, $length = 400) $string = preg_replace('/\s(?=\s)/', '', $string); $string = trim($string); - if (\strlen($string) > $length) { + if (strlen($string) > $length) { $string = substr($string, 0, $length) . '...'; } @@ -966,7 +1075,7 @@ public static function toFormatString($array, $length = 400) public static function toLimitOut($array): array { - if (!\is_array($array)) { + if (!is_array($array)) { return $array; } @@ -977,12 +1086,12 @@ public static function toLimitOut($array): array // break; // } - if (\is_array($value) || \is_object($value)) { - $value = \gettype($value) . '(...)'; - } elseif (\is_string($value) || is_numeric($value)) { - $value = \strlen(trim($value)); + if (is_array($value) || is_object($value)) { + $value = gettype($value) . '(...)'; + } elseif (is_string($value) || is_numeric($value)) { + $value = strlen(trim($value)); } else { - $value = \gettype($value) . "($value)"; + $value = gettype($value) . "($value)"; } $array[$key] = $value; diff --git a/libs/arr-utils/src/FixedArray.php b/libs/arr-utils/src/FixedArray.php index 9d19b5d..67aa6d1 100644 --- a/libs/arr-utils/src/FixedArray.php +++ b/libs/arr-utils/src/FixedArray.php @@ -8,13 +8,19 @@ namespace Toolkit\ArrUtil; +use ArrayAccess; +use IteratorAggregate; +use SplFixedArray; +use function count; + /** * Class FixedArray * fixed size array implements, and support string key. * `SplFixedArray` only allow int key. + * * @package Toolkit\ArrUtil */ -class FixedArray implements \ArrayAccess, \IteratorAggregate +class FixedArray implements ArrayAccess, IteratorAggregate { /** * @var array @@ -25,32 +31,35 @@ class FixedArray implements \ArrayAccess, \IteratorAggregate protected $keys; /** - * @var \SplFixedArray + * @var SplFixedArray */ protected $values; /** * FixedArray constructor. + * * @param int $size */ public function __construct(int $size = 0) { - $this->keys = []; - $this->values = new \SplFixedArray($size); + $this->keys = []; + $this->values = new SplFixedArray($size); } /** * reset + * * @param int $size */ public function reset(int $size = 0) { - $this->keys = []; - $this->values = new \SplFixedArray($size); + $this->keys = []; + $this->values = new SplFixedArray($size); } /** * @param string $key + * * @return bool */ public function __isset(string $key) @@ -69,6 +78,7 @@ public function __set(string $key, $value) /** * @param string $key + * * @return mixed */ public function __get(string $key) @@ -86,6 +96,7 @@ public function getSize(): int /** * @param $key + * * @return int */ public function getKeyIndex($key): int @@ -110,17 +121,17 @@ public function setKeys(array $keys) } /** - * @return \SplFixedArray + * @return SplFixedArray */ - public function getValues(): \SplFixedArray + public function getValues(): SplFixedArray { return $this->values; } /** - * @param \SplFixedArray $values + * @param SplFixedArray $values */ - public function setValues(\SplFixedArray $values) + public function setValues(SplFixedArray $values) { $this->values = $values; } @@ -128,16 +139,19 @@ public function setValues(\SplFixedArray $values) /** * Defined by IteratorAggregate interface * Returns an iterator for this object, for use with foreach - * @return \SplFixedArray + * + * @return SplFixedArray */ - public function getIterator(): \SplFixedArray + public function getIterator(): SplFixedArray { return $this->values; } /** * Checks whether an offset exists in the iterator. - * @param mixed $offset The array offset. + * + * @param mixed $offset The array offset. + * * @return boolean True if the offset exists, false otherwise. */ public function offsetExists($offset): bool @@ -147,7 +161,9 @@ public function offsetExists($offset): bool /** * Gets an offset in the iterator. - * @param mixed $offset The array offset. + * + * @param mixed $offset The array offset. + * * @return mixed The array value if it exists, null otherwise. */ public function offsetGet($offset) @@ -163,8 +179,10 @@ public function offsetGet($offset) /** * Sets an offset in the iterator. - * @param mixed $offset The array offset. - * @param mixed $value The array value. + * + * @param mixed $offset The array offset. + * @param mixed $value The array value. + * * @return void */ public function offsetSet($offset, $value): void @@ -172,17 +190,19 @@ public function offsetSet($offset, $value): void $index = $this->getSize(); // change size. - if ($index <= \count($this->keys)) { + if ($index <= count($this->keys)) { $this->values->setSize($index + 10); } $this->values[$index] = $value; - $this->keys[$offset] = $index; + $this->keys[$offset] = $index; } /** * Unset an offset in the iterator. - * @param mixed $offset The array offset. + * + * @param mixed $offset The array offset. + * * @return void */ public function offsetUnset($offset): void diff --git a/libs/file-utils/example/dir-watcher.php b/libs/file-utils/example/dir-watcher.php index ff37040..a680e7f 100644 --- a/libs/file-utils/example/dir-watcher.php +++ b/libs/file-utils/example/dir-watcher.php @@ -1,4 +1,5 @@ -setIdFile(__DIR__ . '/tmp/dir.id') - ->watch(dirname(__DIR__)) - ->isChanged(); +$mw = new ModifyWatcher(); +$ret = $mw// ->setIdFile(__DIR__ . '/tmp/dir.id') + ->watch(dirname(__DIR__))->isChanged(); // d41d8cd98f00b204e9800998ecf8427e // current file: ae4464472e898ba0bba8dc7302b157c0 diff --git a/libs/file-utils/example/file-finder.php b/libs/file-utils/example/file-finder.php index b3107d7..3eead56 100644 --- a/libs/file-utils/example/file-finder.php +++ b/libs/file-utils/example/file-finder.php @@ -6,19 +6,17 @@ * Time: 23:57 */ +use Toolkit\File\FileFinder; + require dirname(__DIR__) . '/test/boot.php'; // var_dump(fnmatch('.*', ".gitkeep"));die; // var_dump(glob(__DIR__ . '/{t,T}ests', GLOB_BRACE | GLOB_ONLYDIR)); -$finder = \Toolkit\File\FileFinder::create() - ->files() - ->name('*.php') - // ->ignoreVCS(false) +$finder = FileFinder::create()->files()->name('*.php')// ->ignoreVCS(false) // ->ignoreDotFiles(false) // ->exclude('tmp') - ->notPath('tmp') - ->inDir(dirname(__DIR__)); + ->notPath('tmp')->inDir(dirname(__DIR__)); foreach ($finder as $file) { // var_dump($file);die; diff --git a/libs/file-utils/src/Directory.php b/libs/file-utils/src/Directory.php index 5d3ebe6..85f81f7 100644 --- a/libs/file-utils/src/Directory.php +++ b/libs/file-utils/src/Directory.php @@ -10,11 +10,25 @@ namespace Toolkit\File; use DirectoryIterator; +use Exception; +use InvalidArgumentException; +use LogicException; +use RecursiveIteratorIterator; use Toolkit\File\Exception\FileNotFoundException; use Toolkit\File\Exception\FileSystemException; +use function basename; +use function glob; +use function implode; +use function is_array; +use function is_dir; +use function is_file; +use function preg_match; +use function strlen; +use function trim; /** * Class Directory + * * @package Toolkit\File */ class Directory extends FileSystem @@ -40,19 +54,23 @@ class Directory extends FileSystem * // $info->getFilename(); ... * } * ``` + * * @param string $srcDir * @param callable $filter - * @return \RecursiveIteratorIterator - * @throws \LogicException + * + * @return RecursiveIteratorIterator + * @throws LogicException */ - public static function getRecursiveIterator($srcDir, callable $filter): \RecursiveIteratorIterator + public static function getRecursiveIterator($srcDir, callable $filter): RecursiveIteratorIterator { return self::getIterator($srcDir, $filter); } /** * 判断文件夹是否为空 + * * @param $dir + * * @return bool * @throws FileSystemException */ @@ -80,9 +98,11 @@ public static function isEmpty($dir): bool /** * 查看一个目录中的所有文件和子目录 + * * @param $path - * @throws FileNotFoundException + * * @return array + * @throws FileNotFoundException */ public static function ls($path): array { @@ -94,7 +114,7 @@ public static function ls($path): array $list[] = $item; } /*** if an exception is thrown, catch it here ***/ - } catch (\Exception $e) { + } catch (Exception $e) { throw new FileNotFoundException($path . ' 没有任何内容'); } @@ -103,10 +123,12 @@ public static function ls($path): array /** * 只获得目录结构 + * * @param $path * @param int $pid * @param int $son * @param array $list + * * @return array * @throws FileNotFoundException */ @@ -124,8 +146,8 @@ public static function getList($path, $pid = 0, $son = 0, array $list = []): arr if (is_dir($v)) { $id++; - $list[$id]['id'] = $id; - $list[$id]['pid'] = $pid; + $list[$id]['id'] = $id; + $list[$id]['pid'] = $pid; $list[$id]['name'] = basename($v); $list[$id]['path'] = realpath($v); @@ -144,6 +166,7 @@ public static function getList($path, $pid = 0, $son = 0, array $list = []): arr * @param bool $loop * @param null $parent * @param array $list + * * @return array * @throws FileNotFoundException */ @@ -155,12 +178,12 @@ public static function getDirs($path, $loop = false, $parent = null, array $list throw new FileNotFoundException("directory not exists! DIR: $path"); } - $len = \strlen($path); + $len = strlen($path); foreach (glob($path . '*') as $v) { if (is_dir($v)) { $relatePath = substr($v, $len); - $list[] = $parent . $relatePath; + $list[] = $parent . $relatePath; //是否遍历子目录 if ($loop) { @@ -174,33 +197,35 @@ public static function getDirs($path, $loop = false, $parent = null, array $list /** * 获得目录下的文件,可选择类型、是否遍历子文件夹 - * @param string $dir string 目标目录 - * @param string|array $ext array('css','html','php') css|html|php + * + * @param string $dir string 目标目录 + * @param string|array $ext array('css','html','php') css|html|php * @param bool $recursive int|bool 是否包含子目录 + * * @return array * @throws FileNotFoundException */ public static function simpleInfo(string $dir, $ext = null, $recursive = false): array { $list = []; - $dir = self::pathFormat($dir); - $ext = \is_array($ext) ? \implode('|', $ext) : \trim($ext); + $dir = self::pathFormat($dir); + $ext = is_array($ext) ? implode('|', $ext) : trim($ext); - if (!\is_dir($dir)) { + if (!is_dir($dir)) { throw new FileNotFoundException("directory not exists! DIR: $dir"); } // glob()寻找与模式匹配的文件路径 $file is pull path - foreach (\glob($dir . '*') as $file) { + foreach (glob($dir . '*') as $file) { // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找 - if (\is_file($file) && (!$ext || \preg_match("/\.($ext)$/i", $file))) { + if (is_file($file) && (!$ext || preg_match("/\.($ext)$/i", $file))) { //basename — 返回路径中的 文件名部分 - $list[] = \basename($file); + $list[] = basename($file); // is directory } else { - $list[] = '/' . \basename($file); + $list[] = '/' . basename($file); if ($recursive) { $list = array_merge($list, self::simpleInfo($file, $ext, $recursive)); @@ -213,30 +238,37 @@ public static function simpleInfo(string $dir, $ext = null, $recursive = false): /** * 获得目录下的文件,可选择类型、是否遍历子文件夹 - * @param string $path string 目标目录 - * @param array|string $ext array('css','html','php') css|html|php + * + * @param string $path string 目标目录 + * @param array|string $ext array('css','html','php') css|html|php * @param bool $recursive 是否包含子目录 * @param null|string $parent * @param array $list + * * @return array * @throws FileNotFoundException */ - public static function getFiles(string $path, $ext = null, $recursive = false, $parent = null, array $list = []): array - { + public static function getFiles( + string $path, + $ext = null, + $recursive = false, + $parent = null, + array $list = [] + ): array { $path = self::pathFormat($path); if (!is_dir($path)) { throw new FileNotFoundException("directory not exists! DIR: $path"); } - $len = \strlen($path); - $ext = \is_array($ext) ? \implode('|', $ext) : \trim($ext); + $len = strlen($path); + $ext = is_array($ext) ? implode('|', $ext) : trim($ext); foreach (glob($path . '*') as $v) { $relatePath = substr($v, $len); // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找 - if (\is_file($v) && (!$ext || \preg_match("/\.($ext)$/i", $v))) { + if (is_file($v) && (!$ext || preg_match("/\.($ext)$/i", $v))) { $list[] = $parent . $relatePath; } elseif ($recursive) { @@ -249,12 +281,14 @@ public static function getFiles(string $path, $ext = null, $recursive = false, $ /** * 获得目录下的文件以及详细信息,可选择类型、是否遍历子文件夹 - * @param $path string 目标目录 - * @param array|string $ext array('css','html','php') css|html|php + * + * @param $path string 目标目录 + * @param array|string $ext array('css','html','php') css|html|php * @param $recursive int|bool 是否包含子目录 * @param array $list + * * @return array - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * @throws FileNotFoundException */ public static function getFilesInfo($path, $ext = null, $recursive = 0, &$list = []): array @@ -265,7 +299,7 @@ public static function getFilesInfo($path, $ext = null, $recursive = 0, &$list = throw new FileNotFoundException("directory not exists! DIR: $path"); } - $ext = \is_array($ext) ? implode('|', $ext) : trim($ext); + $ext = is_array($ext) ? implode('|', $ext) : trim($ext); static $id = 0; @@ -288,9 +322,11 @@ public static function getFilesInfo($path, $ext = null, $recursive = 0, &$list = /** * 支持层级目录的创建 + * * @param $path * @param int|string $mode * @param bool $recursive + * * @return bool */ public static function create($path, $mode = 0775, $recursive = true): bool @@ -300,8 +336,10 @@ public static function create($path, $mode = 0775, $recursive = true): bool /** * 复制目录内容 + * * @param $oldDir * @param $newDir + * * @return bool * @throws FileNotFoundException */ @@ -337,8 +375,10 @@ public static function copy($oldDir, $newDir): bool /** * 删除目录及里面的文件 + * * @param $path - * @param boolean $delSelf 默认最后删掉自己 + * @param boolean $delSelf 默认最后删掉自己 + * * @return bool */ public static function delete($path, $delSelf = true): bool diff --git a/libs/file-utils/src/Exception/FileNotFoundException.php b/libs/file-utils/src/Exception/FileNotFoundException.php index 703b10d..473ba29 100644 --- a/libs/file-utils/src/Exception/FileNotFoundException.php +++ b/libs/file-utils/src/Exception/FileNotFoundException.php @@ -8,11 +8,14 @@ namespace Toolkit\File\Exception; +use RuntimeException; + /** * Class FileNotFoundException + * * @package Toolkit\File\Exception */ -class FileNotFoundException extends \RuntimeException +class FileNotFoundException extends RuntimeException { } diff --git a/libs/file-utils/src/Exception/FileReadException.php b/libs/file-utils/src/Exception/FileReadException.php index d474bfe..2a4dd9e 100644 --- a/libs/file-utils/src/Exception/FileReadException.php +++ b/libs/file-utils/src/Exception/FileReadException.php @@ -10,6 +10,7 @@ /** * Class FileReadException + * * @package Toolkit\File\Exception */ class FileReadException extends FileSystemException diff --git a/libs/file-utils/src/Exception/FileSystemException.php b/libs/file-utils/src/Exception/FileSystemException.php index 0de2af6..5c8f0d9 100644 --- a/libs/file-utils/src/Exception/FileSystemException.php +++ b/libs/file-utils/src/Exception/FileSystemException.php @@ -8,11 +8,14 @@ namespace Toolkit\File\Exception; +use Exception; + /** * Class FileSystemException + * * @package Toolkit\File\Exception */ -class FileSystemException extends \Exception +class FileSystemException extends Exception { } diff --git a/libs/file-utils/src/Exception/IOException.php b/libs/file-utils/src/Exception/IOException.php index 1063424..9833da9 100644 --- a/libs/file-utils/src/Exception/IOException.php +++ b/libs/file-utils/src/Exception/IOException.php @@ -10,6 +10,7 @@ /** * Class IOException + * * @package Toolkit\File\Exception */ class IOException extends FileSystemException diff --git a/libs/file-utils/src/File.php b/libs/file-utils/src/File.php index d7e918c..442b9c6 100644 --- a/libs/file-utils/src/File.php +++ b/libs/file-utils/src/File.php @@ -10,13 +10,23 @@ namespace Toolkit\File; +use InvalidArgumentException; use Toolkit\File\Exception\FileNotFoundException; use Toolkit\File\Exception\FileReadException; use Toolkit\File\Exception\FileSystemException; use Toolkit\File\Exception\IOException; +use function dirname; +use function file_put_contents; +use function function_exists; +use function in_array; +use function is_array; +use function is_string; +use function stat; +use function strlen; /** * Class File + * * @package Toolkit\File */ abstract class File extends FileSystem @@ -31,8 +41,10 @@ abstract class File extends FileSystem /** * 获得文件名称 + * * @param string $file * @param bool $clearExt 是否去掉文件名中的后缀,仅保留名字 + * * @return string */ public static function getName($file, $clearExt = false): string @@ -44,8 +56,10 @@ public static function getName($file, $clearExt = false): string /** * 获得文件扩展名、后缀名 + * * @param $filename * @param bool $clearPoint 是否带点 + * * @return string */ public static function getSuffix($filename, $clearPoint = false): string @@ -57,8 +71,10 @@ public static function getSuffix($filename, $clearPoint = false): string /** * 获得文件扩展名、后缀名 + * * @param $path * @param bool $clearPoint 是否带点 + * * @return string */ public static function getExtension($path, $clearPoint = false): string @@ -70,6 +86,7 @@ public static function getExtension($path, $clearPoint = false): string /** * @param string $file + * * @return string eg: image/gif */ public static function mimeType($file): string @@ -80,9 +97,10 @@ public static function mimeType($file): string /** * @param string $filename * @param bool $check + * * @return array * @throws FileNotFoundException - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public static function info(string $filename, $check = true): array { @@ -101,27 +119,31 @@ public static function info(string $filename, $check = true): array /** * @param $filename + * * @return array */ public static function getStat($filename): array { - return \stat($filename); + return stat($filename); } /** * save description - * @param mixed $data string array(仅一维数组) 或者是 stream 资源 - * @param string $filename [description], LOCK_EX + * + * @param mixed $data string array(仅一维数组) 或者是 stream 资源 + * @param string $filename [description], LOCK_EX + * * @return bool */ public static function save(string $filename, string $data): bool { - return \file_put_contents($filename, $data) !== false; + return file_put_contents($filename, $data) !== false; } /** * @param $content * @param $path + * * @throws IOException */ public static function write($content, $path): void @@ -135,6 +157,7 @@ public static function write($content, $path): void /** * @param string $path + * * @return resource * @throws IOException */ @@ -149,14 +172,16 @@ public static function openHandler(string $path) /** * Attempts to write $content to the file specified by $handler. $path is used for printing exceptions. + * * @param resource $handler The resource to write to. * @param string $content The content to write. - * @param string $path The path to the file (for exception printing only). + * @param string $path The path to the file (for exception printing only). + * * @throws IOException */ public static function writeToFile($handler, string $content, string $path = ''): void { - if (($result = @fwrite($handler, $content)) === false || ($result < \strlen($content))) { + if (($result = @fwrite($handler, $content)) === false || ($result < strlen($content))) { throw new IOException('The file "' . $path . '" could not be written to. Check your disk space and file permissions.'); } } @@ -164,19 +189,20 @@ public static function writeToFile($handler, string $content, string $path = '') /** * ********************** 创建多级目录和多个文件 ********************** * 结合上两个函数 + * * @param $fileData - 数组:要创建的多个文件名组成,含文件的完整路径 - * @param $append - 是否以追加的方式写入数据 默认false - * @param $mode =0777 - 权限,默认0775 - * eg: $fileData = array( - * 'file_name' => 'content', - * 'case.html' => 'content' , - * ); + * @param $append - 是否以追加的方式写入数据 默认false + * @param $mode =0777 - 权限,默认0775 + * eg: $fileData = array( + * 'file_name' => 'content', + * 'case.html' => 'content' , + * ); **/ public static function createAndWrite(array $fileData = [], $append = false, $mode = 0664): void { foreach ($fileData as $file => $content) { //检查目录是否存在,不存在就先创建(多级)目录 - Directory::create(\dirname($file), $mode); + Directory::create(dirname($file), $mode); //$fileName = basename($file); //文件名 @@ -196,6 +222,7 @@ public static function createAndWrite(array $fileData = [], $append = false, $mo * @param bool|false $useIncludePath * @param null|resource $streamContext * @param int $curlTimeout + * * @return bool|mixed|string * @throws FileNotFoundException * @throws FileReadException @@ -212,7 +239,7 @@ public static function getContents( $streamContext = @stream_context_create(['http' => ['timeout' => $curlTimeout]]); } - if ($isUrl && \in_array(ini_get('allow_url_fopen'), ['On', 'on', '1'], true)) { + if ($isUrl && in_array(ini_get('allow_url_fopen'), ['On', 'on', '1'], true)) { if (!file_exists($file)) { throw new FileNotFoundException("File [{$file}] don't exists!"); } @@ -225,7 +252,7 @@ public static function getContents( } // fetch remote content by url - if (\function_exists('curl_init')) { + if (function_exists('curl_init')) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_URL, $file); @@ -258,13 +285,14 @@ public static function getContents( /** * @param string $file * @param string $target + * * @throws FileNotFoundException * @throws FileSystemException * @throws IOException */ public static function move(string $file, string $target): void { - Directory::mkdir(\dirname($target)); + Directory::mkdir(dirname($target)); if (static::copy($file, $target)) { unlink($file); @@ -273,8 +301,9 @@ public static function move(string $file, string $target): void /** * @param $filename + * * @return bool - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * @throws FileNotFoundException */ public static function delete($filename): bool @@ -286,6 +315,7 @@ public static function delete($filename): bool * @param $source * @param $destination * @param null $streamContext + * * @return bool|int * @throws FileSystemException * @throws FileNotFoundException @@ -306,8 +336,9 @@ public static function copy($source, $destination, $streamContext = null) /** * @param $inFile * @param $outFile + * * @return mixed - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * @throws FileNotFoundException */ public static function combine($inFile, $outFile) @@ -315,7 +346,7 @@ public static function combine($inFile, $outFile) self::check($inFile); $data = ''; - if (\is_array($inFile)) { + if (is_array($inFile)) { foreach ($inFile as $value) { if (is_file($value)) { $data .= trim(file_get_contents($value)); @@ -351,20 +382,22 @@ public static function combine($inFile, $outFile) /** * Removes whitespace from a PHP source string while preserving line numbers. + * * @param string $source A PHP string + * * @return string The PHP string with the whitespace removed */ public static function stripPhpCode(string $source): string { - if (!\function_exists('token_get_all')) { + if (!function_exists('token_get_all')) { return $source; } $output = ''; foreach (token_get_all($source) as $token) { - if (\is_string($token)) { + if (is_string($token)) { $output .= $token; - } elseif (\in_array($token[0], [T_COMMENT, T_DOC_COMMENT], true)) { + } elseif (in_array($token[0], [T_COMMENT, T_DOC_COMMENT], true)) { $output .= str_repeat("\n", substr_count($token[1], "\n")); } elseif (T_WHITESPACE === $token[0]) { // reduce wide spaces @@ -373,7 +406,7 @@ public static function stripPhpCode(string $source): string $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace); // trim leading spaces $whitespace = preg_replace('{\n +}', "\n", $whitespace); - $output .= $whitespace; + $output .= $whitespace; } else { $output .= $token[1]; } @@ -385,6 +418,7 @@ public static function stripPhpCode(string $source): string /** * If you want to download files from a linux server with * a filesize bigger than 2GB you can use the following + * * @param string $file * @param string $as */ diff --git a/libs/file-utils/src/FileFinder.php b/libs/file-utils/src/FileFinder.php index 88efc5a..d6809a9 100644 --- a/libs/file-utils/src/FileFinder.php +++ b/libs/file-utils/src/FileFinder.php @@ -8,6 +8,32 @@ namespace Toolkit\File; +use AppendIterator; +use ArrayIterator; +use Closure; +use Countable; +use FilterIterator; +use InvalidArgumentException; +use Iterator; +use IteratorAggregate; +use LogicException; +use RecursiveArrayIterator; +use RecursiveDirectoryIterator; +use RecursiveIterator; +use RecursiveIteratorIterator; +use RuntimeException; +use SplFileInfo; +use Traversable; +use UnexpectedValueException; +use function array_flip; +use function array_merge; +use function closedir; +use function count; +use function fnmatch; +use function is_array; +use function iterator_count; +use function stream_get_meta_data; + /** * Class FileFinder * @@ -23,10 +49,11 @@ * // something ...... * } * ``` + * * @package Toolkit\File * @ref \Symfony\Component\Finder\Finder */ -final class FileFinder implements \IteratorAggregate, \Countable +final class FileFinder implements IteratorAggregate, Countable { public const ONLY_FILE = 1; public const ONLY_DIR = 2; @@ -82,11 +109,12 @@ public static function create(): self /** * @param array $config + * * @return FileFinder */ public static function fromArray(array $config): self { - $finder = new self(); + $finder = new self(); $allowed = [ 'names' => 'addNames', 'notNames' => 'addNotNames', @@ -149,6 +177,7 @@ public function files(): self * $finder->name('test.php') * * @param string $pattern + * * @return FileFinder */ public function name(string $pattern): self @@ -160,12 +189,13 @@ public function name(string $pattern): self /** * @param string|array $patterns + * * @return FileFinder */ public function addNames($patterns): self { if ($patterns) { - $this->names = \array_merge($this->names, (array)$patterns); + $this->names = array_merge($this->names, (array)$patterns); } return $this; @@ -173,6 +203,7 @@ public function addNames($patterns): self /** * @param string $pattern + * * @return FileFinder */ public function notName(string $pattern): self @@ -184,12 +215,13 @@ public function notName(string $pattern): self /** * @param string|array $patterns + * * @return FileFinder */ public function addNotNames($patterns): self { if ($patterns) { - $this->notNames = \array_merge($this->notNames, (array)$patterns); + $this->notNames = array_merge($this->notNames, (array)$patterns); } return $this; @@ -199,6 +231,7 @@ public function addNotNames($patterns): self * $finder->path('some/special/dir') * * @param string $pattern + * * @return FileFinder */ public function path(string $pattern): self @@ -210,12 +243,13 @@ public function path(string $pattern): self /** * @param string|array $patterns + * * @return FileFinder */ public function addPaths($patterns): self { if ($patterns) { - $this->paths = \array_merge($this->paths, (array)$patterns); + $this->paths = array_merge($this->paths, (array)$patterns); } return $this; @@ -223,6 +257,7 @@ public function addPaths($patterns): self /** * @param string $pattern + * * @return FileFinder */ public function notPath(string $pattern): self @@ -234,12 +269,13 @@ public function notPath(string $pattern): self /** * @param string|array $patterns + * * @return FileFinder */ public function addNotPaths($patterns): self { if ($patterns) { - $this->notPaths = \array_merge($this->notPaths, (array)$patterns); + $this->notPaths = array_merge($this->notPaths, (array)$patterns); } return $this; @@ -247,12 +283,13 @@ public function addNotPaths($patterns): self /** * @param $dirs + * * @return FileFinder */ public function exclude($dirs): self { if ($dirs) { - $this->excludes = \array_merge($this->excludes, (array)$dirs); + $this->excludes = array_merge($this->excludes, (array)$dirs); } return $this; @@ -260,6 +297,7 @@ public function exclude($dirs): self /** * @param bool $ignoreVCS + * * @return self */ public function ignoreVCS($ignoreVCS): self @@ -275,6 +313,7 @@ public function ignoreVCS($ignoreVCS): self /** * @param bool $ignoreDotFiles + * * @return FileFinder */ public function ignoreDotFiles($ignoreDotFiles): self @@ -289,6 +328,7 @@ public function ignoreDotFiles($ignoreDotFiles): self /** * @param bool $followLinks + * * @return FileFinder */ public function followLinks($followLinks = true): self @@ -299,10 +339,11 @@ public function followLinks($followLinks = true): self } /** - * @param \Closure $closure + * @param Closure $closure + * * @return FileFinder */ - public function filter(\Closure $closure): self + public function filter(Closure $closure): self { $this->filters[] = $closure; @@ -311,6 +352,7 @@ public function filter(\Closure $closure): self /** * @param string|array $dirs + * * @return $this */ public function in($dirs): self @@ -320,13 +362,15 @@ public function in($dirs): self /** * alias of the `in()` + * * @param string|array $dirs + * * @return FileFinder */ public function inDir($dirs): self { if ($dirs) { - $this->dirs = \array_merge($this->dirs, (array)$dirs); + $this->dirs = array_merge($this->dirs, (array)$dirs); } return $this; @@ -334,23 +378,24 @@ public function inDir($dirs): self /** * @param mixed $iterator + * * @return $this - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function append($iterator): self { - if ($iterator instanceof \IteratorAggregate) { + if ($iterator instanceof IteratorAggregate) { $this->iterators[] = $iterator->getIterator(); - } elseif ($iterator instanceof \Iterator) { + } elseif ($iterator instanceof Iterator) { $this->iterators[] = $iterator; - } elseif ($iterator instanceof \Traversable || \is_array($iterator)) { - $it = new \ArrayIterator(); + } elseif ($iterator instanceof Traversable || is_array($iterator)) { + $it = new ArrayIterator(); foreach ($iterator as $file) { - $it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file)); + $it->append($file instanceof SplFileInfo ? $file : new SplFileInfo($file)); } $this->iterators[] = $it; } else { - throw new \InvalidArgumentException('The argument type is error'); + throw new InvalidArgumentException('The argument type is error'); } return $this; @@ -361,7 +406,7 @@ public function append($iterator): self */ public function count(): int { - return \iterator_count($this->getIterator()); + return iterator_count($this->getIterator()); } /** @@ -374,18 +419,19 @@ public function isFollowLinks(): bool /** * Retrieve an external iterator + * * @link http://php.net/manual/en/iteratoraggregate.getiterator.php - * @return \Iterator|\SplFileInfo[] An iterator - * @throws \LogicException + * @return Iterator|SplFileInfo[] An iterator + * @throws LogicException */ - public function getIterator(): \Traversable + public function getIterator(): Traversable { - if (0 === \count($this->dirs) && 0 === \count($this->iterators)) { - throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.'); + if (0 === count($this->dirs) && 0 === count($this->iterators)) { + throw new LogicException('You must call one of in() or append() methods before iterating over a Finder.'); } if (!$this->ignoreVcsAdded && self::IGNORE_VCS_FILES === (self::IGNORE_VCS_FILES & $this->ignore)) { - $this->excludes = array_merge($this->excludes, self::$vcsPatterns); + $this->excludes = array_merge($this->excludes, self::$vcsPatterns); $this->ignoreVcsAdded = true; } @@ -393,11 +439,11 @@ public function getIterator(): \Traversable $this->notNames[] = '.*'; } - if (1 === \count($this->dirs) && 0 === \count($this->iterators)) { + if (1 === count($this->dirs) && 0 === count($this->iterators)) { return $this->findInDirectory($this->dirs[0]); } - $iterator = new \AppendIterator(); + $iterator = new AppendIterator(); foreach ($this->dirs as $dir) { $iterator->append($this->findInDirectory($dir)); } @@ -411,17 +457,18 @@ public function getIterator(): \Traversable /** * @param string $dir - * @return \Iterator + * + * @return Iterator */ - private function findInDirectory(string $dir): \Iterator + private function findInDirectory(string $dir): Iterator { - $flags = \RecursiveDirectoryIterator::SKIP_DOTS; + $flags = RecursiveDirectoryIterator::SKIP_DOTS; if ($this->followLinks) { - $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS; + $flags |= RecursiveDirectoryIterator::FOLLOW_SYMLINKS; } - $iterator = new class ($dir, $flags) extends \RecursiveDirectoryIterator + $iterator = new class ($dir, $flags) extends RecursiveDirectoryIterator { private $rootPath; private $subPath; @@ -432,10 +479,10 @@ private function findInDirectory(string $dir): \Iterator public function __construct(string $path, int $flags, bool $ignoreUnreadableDirs = false) { if ($flags & (self::CURRENT_AS_PATHNAME | self::CURRENT_AS_SELF)) { - throw new \RuntimeException('This iterator only support returning current as fileInfo.'); + throw new RuntimeException('This iterator only support returning current as fileInfo.'); } - $this->rootPath = $path; + $this->rootPath = $path; $this->ignoreUnreadableDirs = $ignoreUnreadableDirs; parent::__construct($path, $flags); @@ -457,8 +504,8 @@ public function current() $subPathname .= $this->getFilename(); // $fileInfo = new \SplFileInfo($this->getPathname()); - $fileInfo = new \SplFileInfo($this->rootPath . $this->directorySeparator . $subPathname); - $fileInfo->relativePath = $this->subPath; + $fileInfo = new SplFileInfo($this->rootPath . $this->directorySeparator . $subPathname); + $fileInfo->relativePath = $this->subPath; $fileInfo->relativePathname = $subPathname; return $fileInfo; @@ -470,18 +517,18 @@ public function getChildren() $children = parent::getChildren(); if ($children instanceof self) { - $children->rootPath = $this->rootPath; - $children->rewindable = &$this->rewindable; + $children->rootPath = $this->rootPath; + $children->rewindable = &$this->rewindable; $children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs; } return $children; - } catch (\UnexpectedValueException $e) { + } catch (UnexpectedValueException $e) { if ($this->ignoreUnreadableDirs) { - return new \RecursiveArrayIterator([]); + return new RecursiveArrayIterator([]); } - throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); + throw new RuntimeException($e->getMessage(), $e->getCode(), $e); } } @@ -501,8 +548,8 @@ public function isRewindable() } if (false !== $stream = @opendir($this->getPath())) { - $infoS = \stream_get_meta_data($stream); - \closedir($stream); + $infoS = stream_get_meta_data($stream); + closedir($stream); if ($infoS['seekable']) { return $this->rewindable = true; @@ -515,14 +562,14 @@ public function isRewindable() // exclude directories if ($this->excludes) { - $iterator = new class ($iterator, $this->excludes) extends \FilterIterator implements \RecursiveIterator + $iterator = new class ($iterator, $this->excludes) extends FilterIterator implements RecursiveIterator { private $excludes; private $iterator; - public function __construct(\RecursiveIterator $iterator, array $excludes) + public function __construct(RecursiveIterator $iterator, array $excludes) { - $this->excludes = \array_flip($excludes); + $this->excludes = array_flip($excludes); $this->iterator = $iterator; parent::__construct($iterator); @@ -541,7 +588,7 @@ public function hasChildren(): bool public function getChildren() { - $children = new self($this->iterator->getChildren(), []); + $children = new self($this->iterator->getChildren(), []); $children->excludes = $this->excludes; return $children; @@ -550,15 +597,15 @@ public function getChildren() } // create recursive iterator - $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST); + $iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST); // mode: find files or dirs if ($this->mode) { - $iterator = new class ($iterator, $this->mode) extends \FilterIterator + $iterator = new class ($iterator, $this->mode) extends FilterIterator { private $mode; - public function __construct(\Iterator $iterator, int $mode) + public function __construct(Iterator $iterator, int $mode) { $this->mode = $mode; parent::__construct($iterator); @@ -581,15 +628,15 @@ public function accept(): bool } if ($this->names || $this->notNames) { - $iterator = new class ($iterator, $this->names, $this->notNames) extends \FilterIterator + $iterator = new class ($iterator, $this->names, $this->notNames) extends FilterIterator { private $names; private $notNames; - public function __construct(\Iterator $iterator, array $names, array $notNames) + public function __construct(Iterator $iterator, array $names, array $notNames) { parent::__construct($iterator); - $this->names = $names; + $this->names = $names; $this->notNames = $notNames; } @@ -598,14 +645,14 @@ public function accept(): bool $pathname = $this->current()->getFilename(); foreach ($this->notNames as $not) { - if (\fnmatch($not, $pathname)) { + if (fnmatch($not, $pathname)) { return false; } } if ($this->names) { foreach ($this->names as $need) { - if (\fnmatch($need, $pathname)) { + if (fnmatch($need, $pathname)) { return true; } } @@ -619,11 +666,11 @@ public function accept(): bool } if ($this->filters) { - $iterator = new class ($iterator, $this->filters) extends \FilterIterator + $iterator = new class ($iterator, $this->filters) extends FilterIterator { private $filters; - public function __construct(\Iterator $iterator, array $filters) + public function __construct(Iterator $iterator, array $filters) { parent::__construct($iterator); $this->filters = $filters; @@ -644,15 +691,15 @@ public function accept(): bool } if ($this->paths || $this->notPaths) { - $iterator = new class ($iterator, $this->paths, $this->notPaths) extends \FilterIterator + $iterator = new class ($iterator, $this->paths, $this->notPaths) extends FilterIterator { private $paths; private $notPaths; - public function __construct(\Iterator $iterator, array $paths, array $notPaths) + public function __construct(Iterator $iterator, array $paths, array $notPaths) { parent::__construct($iterator); - $this->paths = $paths; + $this->paths = $paths; $this->notPaths = $notPaths; } @@ -665,14 +712,14 @@ public function accept(): bool } foreach ($this->notPaths as $not) { - if (\fnmatch($not, $pathname)) { + if (fnmatch($not, $pathname)) { return false; } } if ($this->paths) { foreach ($this->paths as $need) { - if (\fnmatch($need, $pathname)) { + if (fnmatch($need, $pathname)) { return true; } } diff --git a/libs/file-utils/src/FileSystem.php b/libs/file-utils/src/FileSystem.php index fcc6b10..9d640a0 100644 --- a/libs/file-utils/src/FileSystem.php +++ b/libs/file-utils/src/FileSystem.php @@ -10,29 +10,46 @@ namespace Toolkit\File; +use FilesystemIterator; +use InvalidArgumentException; +use RecursiveCallbackFilterIterator; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; use Toolkit\ArrUtil\Arr; use Toolkit\File\Exception\FileNotFoundException; use Toolkit\File\Exception\IOException; +use Traversable; +use function count; +use function file_exists; +use function function_exists; +use function is_array; +use function is_string; +use function preg_match; +use function str_ireplace; +use function strlen; +use function strpos; +use function substr; /** * Class FileSystem + * * @package Toolkit\File */ abstract class FileSystem { /** * @param $path + * * @return bool */ public static function isAbsPath(string $path): bool { - if (!$path || !\is_string($path)) { + if (!$path || !is_string($path)) { return false; } - if ( - \strpos($path, '/') === 0 || // linux/mac - 1 === \preg_match('#^[a-z]:[\/|\\\]{1}.+#i', $path) // windows + if (strpos($path, '/') === 0 || // linux/mac + 1 === preg_match('#^[a-z]:[\/|\\\]{1}.+#i', $path) // windows ) { return true; } @@ -42,34 +59,37 @@ public static function isAbsPath(string $path): bool /** * Returns whether the file path is an absolute path. + * * @from Symfony-filesystem + * * @param string $file A file path + * * @return bool */ public static function isAbsolutePath(string $file): bool { - return strspn($file, '/\\', 0, 1) - || (\strlen($file) > 3 && ctype_alpha($file[0]) - && $file[1] === ':' - && strspn($file, '/\\', 2, 1) - ) - || null !== parse_url($file, PHP_URL_SCHEME); + return strspn($file, '/\\', 0, + 1) || (strlen($file) > 3 && ctype_alpha($file[0]) && $file[1] === ':' && strspn($file, '/\\', 2, + 1)) || null !== parse_url($file, PHP_URL_SCHEME); } /** * 转换为标准的路径结构 - * @param string $dirName + * + * @param string $dirName + * * @return string */ public static function pathFormat(string $dirName): string { - $dirName = (string)\str_ireplace('\\', '/', trim($dirName)); + $dirName = (string)str_ireplace('\\', '/', trim($dirName)); - return \substr($dirName, -1) === '/' ? $dirName : $dirName . '/'; + return substr($dirName, -1) === '/' ? $dirName : $dirName . '/'; } /** * @param string $path e.g phar://E:/workenv/xxx/yyy/app.phar/web + * * @return string */ public function clearPharPath(string $path): string @@ -87,8 +107,10 @@ public function clearPharPath(string $path): string /** * 检查文件/夹/链接是否存在 + * * @param string $file 要检查的目标 * @param null|string $type + * * @return array|string */ public static function exists(string $file, $type = null) @@ -113,8 +135,9 @@ public static function exists(string $file, $type = null) /** * @param string $file * @param null|string|array $ext eg: 'jpg|gif' + * * @throws FileNotFoundException - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public static function check(string $file, $ext = null): void { @@ -123,22 +146,25 @@ public static function check(string $file, $ext = null): void } if ($ext) { - if (\is_array($ext)) { + if (is_array($ext)) { $ext = implode('|', $ext); } if (preg_match("/\.($ext)$/i", $file)) { - throw new \InvalidArgumentException("{$file} extension is not match: {$ext}"); + throw new InvalidArgumentException("{$file} extension is not match: {$ext}"); } } } /** * Renames a file or a directory. + * * @from Symfony-filesystem - * @param string $origin The origin filename or directory - * @param string $target The new filename or directory + * + * @param string $origin The origin filename or directory + * @param string $target The new filename or directory * @param bool $overwrite Whether to overwrite the target if it already exists + * * @throws IOException When target file or directory already exists * @throws IOException When origin cannot be renamed */ @@ -156,14 +182,17 @@ public static function rename(string $origin, string $target, bool $overwrite = /** * Tells whether a file exists and is readable. + * * @from Symfony-filesystem + * * @param string $filename Path to the file + * * @return bool * @throws IOException When windows path is longer than 258 characters */ public static function isReadable(string $filename): bool { - if ('\\' === DIRECTORY_SEPARATOR && \strlen($filename) > 258) { + if ('\\' === DIRECTORY_SEPARATOR && strlen($filename) > 258) { throw new IOException('Could not check if file is readable because path length exceeds 258 characters.'); } @@ -172,8 +201,10 @@ public static function isReadable(string $filename): bool /** * Creates a directory recursively. - * @param string|array|\Traversable $dirs The directory path - * @param int $mode The directory mode + * + * @param string|array|Traversable $dirs The directory path + * @param int $mode The directory mode + * * @throws IOException On any directory creation failure */ public static function mkdir($dirs, $mode = 0777): void @@ -200,11 +231,14 @@ public static function mkdir($dirs, $mode = 0777): void /** * Change mode for an array of files or directories. + * * @from Symfony-filesystem - * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change mode - * @param int $mode The new mode (octal) - * @param int $umask The mode mask (octal) - * @param bool $recursive Whether change the mod recursively or not + * + * @param string|array|Traversable $files A filename, an array of files, or a \Traversable instance to change mode + * @param int $mode The new mode (octal) + * @param int $umask The mode mask (octal) + * @param bool $recursive Whether change the mod recursively or not + * * @throws IOException When the change fail */ public static function chmod($files, $mode, $umask = 0000, $recursive = false): void @@ -215,27 +249,30 @@ public static function chmod($files, $mode, $umask = 0000, $recursive = false): } if ($recursive && is_dir($file) && !is_link($file)) { - self::chmod(new \FilesystemIterator($file), $mode, $umask, true); + self::chmod(new FilesystemIterator($file), $mode, $umask, true); } } } /** * Change the owner of an array of files or directories. + * * @from Symfony-filesystem - * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change owner - * @param string $user The new owner user name - * @param bool $recursive Whether change the owner recursively or not + * + * @param string|array|Traversable $files A filename, an array of files, or a \Traversable instance to change owner + * @param string $user The new owner user name + * @param bool $recursive Whether change the owner recursively or not + * * @throws IOException When the change fail */ public static function chown($files, string $user, $recursive = false): void { foreach (Arr::toIterator($files) as $file) { if ($recursive && is_dir($file) && !is_link($file)) { - self::chown(new \FilesystemIterator($file), $user, true); + self::chown(new FilesystemIterator($file), $user, true); } - if (is_link($file) && \function_exists('lchown')) { + if (is_link($file) && function_exists('lchown')) { if (true !== lchown($file, $user)) { throw new IOException(sprintf('Failed to chown file "%s".', $file)); } @@ -248,24 +285,26 @@ public static function chown($files, string $user, $recursive = false): void /** * @param string $srcDir * @param callable $filter - * @return \RecursiveIteratorIterator - * @throws \InvalidArgumentException + * + * @return RecursiveIteratorIterator + * @throws InvalidArgumentException */ - public static function getIterator(string $srcDir, callable $filter): \RecursiveIteratorIterator + public static function getIterator(string $srcDir, callable $filter): RecursiveIteratorIterator { - if (!$srcDir || !\file_exists($srcDir)) { - throw new \InvalidArgumentException('Please provide a exists source directory.'); + if (!$srcDir || !file_exists($srcDir)) { + throw new InvalidArgumentException('Please provide a exists source directory.'); } - $directory = new \RecursiveDirectoryIterator($srcDir); - $filterIterator = new \RecursiveCallbackFilterIterator($directory, $filter); + $directory = new RecursiveDirectoryIterator($srcDir); + $filterIterator = new RecursiveCallbackFilterIterator($directory, $filter); - return new \RecursiveIteratorIterator($filterIterator); + return new RecursiveIteratorIterator($filterIterator); } /** * @param $path * @param int $mode + * * @return bool */ public static function chmodDir(string $path, $mode = 0664): bool @@ -299,14 +338,15 @@ public static function chmodDir(string $path, $mode = 0664): bool /** * @param string $dir + * * @return string */ public static function availableSpace(string $dir = '.'): string { - $base = 1024; - $bytes = disk_free_space($dir); + $base = 1024; + $bytes = disk_free_space($dir); $suffix = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - $class = min((int)log($bytes, $base), \count($suffix) - 1); + $class = min((int)log($bytes, $base), count($suffix) - 1); //echo $bytes . '
'; @@ -316,14 +356,15 @@ public static function availableSpace(string $dir = '.'): string /** * @param string $dir + * * @return string */ public static function countSpace(string $dir = '.'): string { - $base = 1024; - $bytes = disk_total_space($dir); + $base = 1024; + $bytes = disk_total_space($dir); $suffix = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - $class = min((int)log($bytes, $base), \count($suffix) - 1); + $class = min((int)log($bytes, $base), count($suffix) - 1); // pow($base, $class) return sprintf('%1.2f', $bytes / ($base ** $class)) . ' ' . $suffix[$class]; @@ -331,9 +372,12 @@ public static function countSpace(string $dir = '.'): string /** * 文件或目录权限检查函数 - * @from web + * + * @from web * @access public - * @param string $file_path 文件路径 + * + * @param string $file_path 文件路径 + * * @return int 返回值的取值范围为{0 <= x <= 15},每个值表示的含义可由四位二进制数组合推出。 * 返回值在二进制计数法中,四位由高到低分别代表 * 可执行rename()函数权限 |可对文件追加内容权限 |可写入文件权限|可读取文件权限。 diff --git a/libs/file-utils/src/ModifyWatcher.php b/libs/file-utils/src/ModifyWatcher.php index f4e07c2..d3c724c 100644 --- a/libs/file-utils/src/ModifyWatcher.php +++ b/libs/file-utils/src/ModifyWatcher.php @@ -8,10 +8,14 @@ namespace Toolkit\File; +use RuntimeException; use Toolkit\Sys\Sys; +use function in_array; +use function json_encode; /** * Class FilesWatcher - Check Dir's files modified by md5_file() + * * @package Inhere\Server\Components */ final class ModifyWatcher @@ -57,6 +61,7 @@ final class ModifyWatcher /** * ModifyWatcher constructor. + * * @param string|null $idFile */ public function __construct(string $idFile = null) @@ -68,6 +73,7 @@ public function __construct(string $idFile = null) /** * @param string $idFile + * * @return $this */ public function setIdFile(string $idFile): self @@ -79,6 +85,7 @@ public function setIdFile(string $idFile): self /** * @param string|array $notNames + * * @return ModifyWatcher */ public function name($notNames): self @@ -90,6 +97,7 @@ public function name($notNames): self /** * @param string|array $notNames + * * @return ModifyWatcher */ public function notName($notNames): self @@ -101,6 +109,7 @@ public function notName($notNames): self /** * @param string|array $excludeDirs + * * @return ModifyWatcher */ public function exclude($excludeDirs): self @@ -112,6 +121,7 @@ public function exclude($excludeDirs): self /** * @param bool $ignoreDotDirs + * * @return ModifyWatcher */ public function ignoreDotDirs($ignoreDotDirs): ModifyWatcher @@ -123,6 +133,7 @@ public function ignoreDotDirs($ignoreDotDirs): ModifyWatcher /** * @param bool $ignoreDotFiles + * * @return ModifyWatcher */ public function ignoreDotFiles($ignoreDotFiles): ModifyWatcher @@ -133,6 +144,7 @@ public function ignoreDotFiles($ignoreDotFiles): ModifyWatcher /** * @param string|array $dirs + * * @return $this */ public function watch($dirs): self @@ -144,7 +156,9 @@ public function watch($dirs): self /** * alias of the watch() + * * @param string|array $dirs + * * @return $this */ public function watchDir($dirs): self @@ -168,7 +182,7 @@ public function isModified(): bool public function isChanged(): bool { if (!$this->idFile) { - $this->idFile = Sys::getTempDir() . '/' . md5(\json_encode($this->watchDirs)) . '.id'; + $this->idFile = Sys::getTempDir() . '/' . md5(json_encode($this->watchDirs)) . '.id'; } // get old hash id @@ -205,14 +219,14 @@ public function getMd5ByIdFile() public function calcMd5Hash(): string { if (!$this->watchDirs) { - throw new \RuntimeException('Please setting want to watched directories before run.'); + throw new RuntimeException('Please setting want to watched directories before run.'); } foreach ($this->watchDirs as $dir) { $this->collectDirMd5($dir); } - $this->dirMd5 = md5($this->md5String); + $this->dirMd5 = md5($this->md5String); $this->md5String = null; if ($this->idFile) { @@ -242,7 +256,7 @@ private function collectDirMd5(string $watchDir): void continue; } - if (\in_array($f, $this->excludes, true)) { + if (in_array($f, $this->excludes, true)) { continue; } diff --git a/libs/file-utils/src/ReadTrait.php b/libs/file-utils/src/ReadTrait.php index af3bdfd..60ad167 100644 --- a/libs/file-utils/src/ReadTrait.php +++ b/libs/file-utils/src/ReadTrait.php @@ -9,15 +9,24 @@ namespace Toolkit\File; +use Exception; +use SplFileObject; +use Throwable; use Toolkit\File\Exception\FileNotFoundException; use Toolkit\File\Exception\FileReadException; use Toolkit\File\Exception\FileSystemException; use Toolkit\File\Parser\IniParser; use Toolkit\File\Parser\JsonParser; use Toolkit\File\Parser\YmlParser; +use function array_slice; +use function assert; +use function class_exists; +use function count; +use function is_array; /** * Class Read + * * @package Toolkit\File */ trait ReadTrait @@ -25,6 +34,7 @@ trait ReadTrait /** * @param string $src 要解析的 文件 或 字符串内容。 * @param string $format + * * @return array|bool * @throws FileNotFoundException */ @@ -56,8 +66,10 @@ public static function load($src, $format = self::FORMAT_PHP) /** * load array data form file. + * * @param string $file * @param bool $throwError + * * @return array * @throws FileNotFoundException */ @@ -68,7 +80,7 @@ public static function loadPhp($file, $throwError = true): array if (is_file($file)) { $ary = require $file; - if (!\is_array($ary)) { + if (!is_array($ary)) { $ary = []; } } elseif ($throwError) { @@ -80,6 +92,7 @@ public static function loadPhp($file, $throwError = true): array /** * @param string $file + * * @return array */ public static function loadJson($file): array @@ -89,6 +102,7 @@ public static function loadJson($file): array /** * @param string $ini 要解析的 ini 文件名 或 字符串内容。 + * * @return array|bool */ public static function loadIni($ini) @@ -98,6 +112,7 @@ public static function loadIni($ini) /** * @param string $yml 要解析的 yml 文件名 或 字符串内容。 + * * @return array|bool */ public static function loadYml($yml) @@ -108,6 +123,7 @@ public static function loadYml($yml) /** * @param $file * @param bool|true $filter + * * @return array|string * @throws FileNotFoundException * @throws FileReadException @@ -127,16 +143,18 @@ public static function readAllLine($file, $filter = true) /** * getLines 获取文件一定范围内的内容 - * @param string $fileName 含完整路径的文件 - * @param integer $startLine 开始行数 默认第1行 - * @param integer $endLine 结束行数 默认第50行 - * @param string $mode 打开文件方式 - * @throws FileSystemException + * + * @param string $fileName 含完整路径的文件 + * @param integer $startLine 开始行数 默认第1行 + * @param integer $endLine 结束行数 默认第50行 + * @param string $mode 打开文件方式 + * * @return array 返回内容 + * @throws FileSystemException */ public static function readLines(string $fileName, int $startLine = 1, int $endLine = 10, $mode = 'rb'): array { - $content = []; + $content = []; $startLine = $startLine <= 0 ? 1 : $startLine; if ($endLine <= $startLine) { @@ -144,18 +162,18 @@ public static function readLines(string $fileName, int $startLine = 1, int $endL } // 判断php版本(因为要用到SplFileObject,PHP>=5.1.0) - if (\class_exists('SplFileObject', false)) { + if (class_exists('SplFileObject', false)) { $count = $endLine - $startLine; try { - $objFile = new \SplFileObject($fileName, $mode); + $objFile = new SplFileObject($fileName, $mode); $objFile->seek($startLine - 1); // 转到第N行, seek方法参数从0开始计数 for ($i = 0; $i <= $count; ++$i) { $content[] = $objFile->current(); // current()获取当前行内容 $objFile->next(); // 下一行 } - } catch (\Throwable $e) { + } catch (Throwable $e) { throw new FileSystemException("Error on read the file '{$fileName}'. ERR: " . $e->getMessage()); } @@ -182,20 +200,22 @@ public static function readLines(string $fileName, int $startLine = 1, int $endL /** * symmetry 得到当前行对称上下几($lineNum)行的内容 - * @param string $fileName 含完整路径的文件 - * @param integer $current [当前行数] - * @param integer $lineNum [获取行数] = $lineNum*2+1 - * @throws FileSystemException + * + * @param string $fileName 含完整路径的文件 + * @param integer $current [当前行数] + * @param integer $lineNum [获取行数] = $lineNum*2+1 + * * @return array + * @throws FileSystemException */ public static function readSymmetry($fileName, $current = 1, $lineNum = 3): array { $startLine = $current - $lineNum; - $endLine = $current + $lineNum; + $endLine = $current + $lineNum; if ((int)$current < ($lineNum + 1)) { $startLine = 1; - $endLine = 9; + $endLine = 9; } return self::readLines($fileName, $startLine, $endLine); @@ -206,21 +226,24 @@ public static function readSymmetry($fileName, $current = 1, $lineNum = 3): arra * @param int $baseLine * @param int $prevLines * @param int $nextLines + * * @return array * @throws FileSystemException */ public static function readRangeLines(string $file, int $baseLine, int $prevLines = 3, int $nextLines = 3): array { $startLine = $baseLine - $prevLines; - $endLine = $baseLine + $nextLines; + $endLine = $baseLine + $nextLines; return self::readLines($file, $startLine, $endLine); } /** * 得到基准行数上5行下3行的内容, lines up and down + * * @param string $file * @param int $baseLine 基准行数 + * * @return array * @throws FileSystemException */ @@ -231,23 +254,26 @@ public static function getLines5u3d(string $file, int $baseLine = 1): array /** * 读取文件的最后几行(支持大文件读取) + * * @link http://www.jb51.net/article/81909.htm + * * @param resource $fp e.g fopen("access.log", "r+") * @param int $n * @param int $base + * * @return array */ public static function tail($fp, int $n, int $base = 5): array { - \assert($n > 0); + assert($n > 0); - $pos = $n + 1; + $pos = $n + 1; $lines = []; - while (\count($lines) <= $n) { + while (count($lines) <= $n) { try { fseek($fp, -$pos, SEEK_END); - } catch (\Exception $e) { + } catch (Exception $e) { fclose($fp); break; } @@ -259,6 +285,6 @@ public static function tail($fp, int $n, int $base = 5): array } } - return \array_slice($lines, 0, $n); + return array_slice($lines, 0, $n); } } diff --git a/libs/obj-utils/src/Configurable.php b/libs/obj-utils/src/Configurable.php index e84d100..f6d8176 100644 --- a/libs/obj-utils/src/Configurable.php +++ b/libs/obj-utils/src/Configurable.php @@ -12,6 +12,7 @@ /** * Class Configurable + * * @package Toolkit\ObjUtil */ class Configurable @@ -20,6 +21,7 @@ class Configurable /** * Configurable constructor. + * * @param array $config */ public function __construct(array $config = []) diff --git a/libs/obj-utils/src/Exception/GetPropertyException.php b/libs/obj-utils/src/Exception/GetPropertyException.php index 9ce5d5a..b829696 100644 --- a/libs/obj-utils/src/Exception/GetPropertyException.php +++ b/libs/obj-utils/src/Exception/GetPropertyException.php @@ -8,10 +8,13 @@ namespace Toolkit\ObjUtil\Exception; +use RuntimeException; + /** * Class GetPropertyException + * * @package Toolkit\ObjUtil\Exception */ -class GetPropertyException extends \RuntimeException +class GetPropertyException extends RuntimeException { } diff --git a/libs/obj-utils/src/Exception/PropertyException.php b/libs/obj-utils/src/Exception/PropertyException.php index 79dc69d..bb40124 100644 --- a/libs/obj-utils/src/Exception/PropertyException.php +++ b/libs/obj-utils/src/Exception/PropertyException.php @@ -8,10 +8,13 @@ namespace Toolkit\ObjUtil\Exception; +use RuntimeException; + /** * Class PropertyException + * * @package Toolkit\ObjUtil\Exception */ -class PropertyException extends \RuntimeException +class PropertyException extends RuntimeException { } diff --git a/libs/obj-utils/src/Exception/SetPropertyException.php b/libs/obj-utils/src/Exception/SetPropertyException.php index be51526..89ad784 100644 --- a/libs/obj-utils/src/Exception/SetPropertyException.php +++ b/libs/obj-utils/src/Exception/SetPropertyException.php @@ -8,10 +8,13 @@ namespace Toolkit\ObjUtil\Exception; +use RuntimeException; + /** * Class SetPropertyException + * * @package Toolkit\ObjUtil\Exception */ -class SetPropertyException extends \RuntimeException +class SetPropertyException extends RuntimeException { } diff --git a/libs/obj-utils/src/Obj.php b/libs/obj-utils/src/Obj.php index bb235cc..29697e7 100644 --- a/libs/obj-utils/src/Obj.php +++ b/libs/obj-utils/src/Obj.php @@ -8,11 +8,13 @@ namespace Toolkit\ObjUtil; +use ArrayAccess; use Toolkit\ObjUtil\Traits\ObjectPoolTrait; /** * Class Obj * alias of the ObjectHelper + * * @package Toolkit\ObjUtil */ class Obj extends ObjectHelper @@ -26,6 +28,7 @@ class Obj extends ObjectHelper /** * @param string $class + * * @return mixed */ public static function singleton(string $class) @@ -39,6 +42,7 @@ public static function singleton(string $class) /** * @param string $class + * * @return mixed */ public static function factory(string $class) @@ -52,10 +56,11 @@ public static function factory(string $class) /** * @param $object + * * @return bool */ public static function isArrayable($object): bool { - return $object instanceof \ArrayAccess || method_exists($object, 'toArray'); + return $object instanceof ArrayAccess || method_exists($object, 'toArray'); } } diff --git a/libs/obj-utils/src/ObjectHelper.php b/libs/obj-utils/src/ObjectHelper.php index 8f6adf4..3a52d7b 100644 --- a/libs/obj-utils/src/ObjectHelper.php +++ b/libs/obj-utils/src/ObjectHelper.php @@ -9,8 +9,32 @@ namespace Toolkit\ObjUtil; +use Closure; +use ReflectionClass; +use ReflectionException; +use ReflectionMethod; +use RuntimeException; +use Traversable; +use function base64_decode; +use function base64_encode; +use function gzcompress; +use function gzuncompress; +use function is_array; +use function is_numeric; +use function is_object; +use function is_string; +use function iterator_to_array; +use function md5; +use function method_exists; +use function property_exists; +use function serialize; +use function spl_object_hash; +use function ucfirst; +use function unserialize; + /** * Class ObjectHelper + * * @package Toolkit\ObjUtil */ class ObjectHelper @@ -19,23 +43,25 @@ class ObjectHelper * 给对象设置属性值 * - 会先尝试用 setter 方法设置属性 * - 再尝试直接设置属性 + * * @param mixed $object An object instance * @param array $options + * * @return mixed */ public static function init($object, array $options) { foreach ($options as $property => $value) { - if (\is_numeric($property)) { + if (is_numeric($property)) { continue; } - $setter = 'set' . \ucfirst($property); + $setter = 'set' . ucfirst($property); // has setter - if (\method_exists($object, $setter)) { + if (method_exists($object, $setter)) { $object->$setter($value); - } elseif (\property_exists($object, $property)) { + } elseif (property_exists($object, $property)) { $object->$property = $value; } } @@ -45,13 +71,14 @@ public static function init($object, array $options) /** * 给对象设置属性值 + * * @param $object * @param array $options */ public static function configure($object, array $options): void { foreach ($options as $property => $value) { - if (\property_exists($object, $property)) { + if (property_exists($object, $property)) { $object->$property = $value; } } @@ -59,6 +86,7 @@ public static function configure($object, array $options): void /** * 给对象设置属性值 + * * @param $object * @param array $options */ @@ -69,29 +97,35 @@ public static function setAttrs($object, array $options): void /** * 定义一个用来序列化数据的函数 + * * @param mixed $obj + * * @return string */ public static function encode($obj): string { - return \base64_encode(\gzcompress(\serialize($obj))); + return base64_encode(gzcompress(serialize($obj))); } /** * 反序列化 + * * @param string $txt * @param bool|array $allowedClasses + * * @return mixed */ public static function decode(string $txt, $allowedClasses = false) { - return \unserialize(\gzuncompress(\base64_decode($txt)), ['allowed_classes' => $allowedClasses]); + return unserialize(gzuncompress(base64_decode($txt)), ['allowed_classes' => $allowedClasses]); } /** * php对象转换成为数组 - * @param iterable|array|\Traversable $data - * @param bool $recursive + * + * @param iterable|array|Traversable $data + * @param bool $recursive + * * @return array|bool */ public static function toArray($data, bool $recursive = false) @@ -99,10 +133,10 @@ public static function toArray($data, bool $recursive = false) $arr = []; // Ensure the input data is an array. - if (\is_object($data)) { - if ($data instanceof \Traversable) { - $arr = \iterator_to_array($data); - } elseif (\method_exists($data, 'toArray')) { + if (is_object($data)) { + if ($data instanceof Traversable) { + $arr = iterator_to_array($data); + } elseif (method_exists($data, 'toArray')) { $arr = $data->toArray(); } } else { @@ -111,7 +145,7 @@ public static function toArray($data, bool $recursive = false) if ($recursive) { foreach ($arr as $key => $value) { - if (\is_array($value) || \is_object($value)) { + if (is_array($value) || is_object($value)) { $arr[$key] = static::toArray($value, $recursive); } } @@ -123,34 +157,37 @@ public static function toArray($data, bool $recursive = false) /** * @param mixed $object * @param bool $unique + * * @return string */ public static function hash($object, $unique = true): string { - if (\is_object($object)) { - $hash = \spl_object_hash($object); + if (is_object($object)) { + $hash = spl_object_hash($object); if ($unique) { - $hash = \md5($hash); + $hash = md5($hash); } return $hash; } // a class - return \is_string($object) ? \md5($object) : ''; + return is_string($object) ? md5($object) : ''; } /** * @from https://github.com/ventoviro/windwalker * Build an array of constructor parameters. - * @param \ReflectionMethod $method Method for which to build the argument array. - * @param array $extraArgs + * + * @param ReflectionMethod $method Method for which to build the argument array. + * @param array $extraArgs + * * @return array - * @throws \RuntimeException - * @throws \ReflectionException + * @throws RuntimeException + * @throws ReflectionException */ - public static function getMethodArgs(\ReflectionMethod $method, array $extraArgs = []): array + public static function getMethodArgs(ReflectionMethod $method, array $extraArgs = []): array { $methodArgs = []; @@ -164,8 +201,8 @@ public static function getMethodArgs(\ReflectionMethod $method, array $extraArgs $dependencyClass = $param->getClass(); // If we have a dependency, that means it has been type-hinted. - if ($dependencyClass && ($depClass = $dependencyClass->getName()) !== \Closure::class) { - $depClass = $dependencyClass->getName(); + if ($dependencyClass && ($depClass = $dependencyClass->getName()) !== Closure::class) { + $depClass = $dependencyClass->getName(); $depObject = self::create($depClass); if ($depObject instanceof $depClass) { @@ -182,11 +219,8 @@ public static function getMethodArgs(\ReflectionMethod $method, array $extraArgs // $dependencyVarName = $param->getName(); // Couldn't resolve dependency, and no default was provided. - throw new \RuntimeException(sprintf( - 'Could not resolve dependency: %s for the %dth parameter', - $param->getPosition(), - $param->getName() - )); + throw new RuntimeException(sprintf('Could not resolve dependency: %s for the %dth parameter', + $param->getPosition(), $param->getName())); } return $methodArgs; @@ -194,16 +228,19 @@ public static function getMethodArgs(\ReflectionMethod $method, array $extraArgs /** * 从类名创建服务实例对象,会尽可能自动补完构造函数依赖 + * * @from windWalker https://github.com/ventoviro/windwalker + * * @param string $class a className + * * @return mixed - * @throws \RuntimeException + * @throws RuntimeException */ public static function create(string $class) { try { - $reflection = new \ReflectionClass($class); - } catch (\ReflectionException $e) { + $reflection = new ReflectionClass($class); + } catch (ReflectionException $e) { return false; } @@ -222,17 +259,18 @@ public static function create(string $class) /** * @param string|array $config + * * @return mixed */ public static function smartCreate($config) { - if (\is_string($config)) { + if (is_string($config)) { return new $config; } - if (\is_array($config) && !empty($config['class'])) { + if (is_array($config) && !empty($config['class'])) { $class = $config['class']; - $args = $config[0] ?? []; + $args = $config[0] ?? []; $obj = new $class(...$args); diff --git a/libs/obj-utils/src/Traits/ArrayAccessByGetterSetterTrait.php b/libs/obj-utils/src/Traits/ArrayAccessByGetterSetterTrait.php index 4415916..c23bed0 100644 --- a/libs/obj-utils/src/Traits/ArrayAccessByGetterSetterTrait.php +++ b/libs/obj-utils/src/Traits/ArrayAccessByGetterSetterTrait.php @@ -8,8 +8,12 @@ namespace Toolkit\ObjUtil\Traits; +use function method_exists; +use function property_exists; + /** * Class TraitArrayAccess + * * @package Toolkit\ObjUtil\Traits * ``` * class A implements \ArrayAccess @@ -22,24 +26,28 @@ trait ArrayAccessByGetterSetterTrait { /** * Checks whether an offset exists in the iterator. - * @param mixed $offset The array offset. + * + * @param mixed $offset The array offset. + * * @return boolean True if the offset exists, false otherwise. */ public function offsetExists($offset): bool { - return \property_exists($this, $offset); + return property_exists($this, $offset); } /** * Gets an offset in the iterator. - * @param mixed $offset The array offset. + * + * @param mixed $offset The array offset. + * * @return mixed The array value if it exists, null otherwise. */ public function offsetGet($offset) { $getter = 'get' . ucfirst($offset); - if (\method_exists($this, $getter)) { + if (method_exists($this, $getter)) { $this->$getter(); } @@ -48,21 +56,24 @@ public function offsetGet($offset) /** * Sets an offset in the iterator. - * @param mixed $offset The array offset. - * @param mixed $value The array value. + * + * @param mixed $offset The array offset. + * @param mixed $value The array value. */ public function offsetSet($offset, $value): void { $setter = 'set' . ucfirst($offset); - if (\method_exists($this, $setter)) { + if (method_exists($this, $setter)) { $this->$setter($value); } } /** * Unset an offset in the iterator. - * @param mixed $offset The array offset. + * + * @param mixed $offset The array offset. + * * @return void */ public function offsetUnset($offset): void diff --git a/libs/obj-utils/src/Traits/ArrayAccessByPropertyTrait.php b/libs/obj-utils/src/Traits/ArrayAccessByPropertyTrait.php index d7aada3..dfb8194 100644 --- a/libs/obj-utils/src/Traits/ArrayAccessByPropertyTrait.php +++ b/libs/obj-utils/src/Traits/ArrayAccessByPropertyTrait.php @@ -8,8 +8,11 @@ namespace Toolkit\ObjUtil\Traits; +use function property_exists; + /** * Class TraitArrayAccess + * * @package Toolkit\ObjUtil\Traits * ``` * class A implements \ArrayAccess @@ -22,17 +25,21 @@ trait ArrayAccessByPropertyTrait { /** * Checks whether an offset exists in the iterator. - * @param mixed $offset The array offset. + * + * @param mixed $offset The array offset. + * * @return boolean True if the offset exists, false otherwise. */ public function offsetExists($offset): bool { - return \property_exists($this, $offset); + return property_exists($this, $offset); } /** * Gets an offset in the iterator. - * @param mixed $offset The array offset. + * + * @param mixed $offset The array offset. + * * @return mixed The array value if it exists, null otherwise. */ public function offsetGet($offset) @@ -42,8 +49,10 @@ public function offsetGet($offset) /** * Sets an offset in the iterator. - * @param mixed $offset The array offset. - * @param mixed $value The array value. + * + * @param mixed $offset The array offset. + * @param mixed $value The array value. + * * @return void */ public function offsetSet($offset, $value): void @@ -53,7 +62,9 @@ public function offsetSet($offset, $value): void /** * Unset an offset in the iterator. - * @param mixed $offset The array offset. + * + * @param mixed $offset The array offset. + * * @return void */ public function offsetUnset($offset): void diff --git a/libs/obj-utils/src/Traits/ObjectPoolTrait.php b/libs/obj-utils/src/Traits/ObjectPoolTrait.php index 1f8139e..d91c041 100644 --- a/libs/obj-utils/src/Traits/ObjectPoolTrait.php +++ b/libs/obj-utils/src/Traits/ObjectPoolTrait.php @@ -8,19 +8,29 @@ namespace Toolkit\ObjUtil\Traits; +use Closure; +use InvalidArgumentException; +use SplStack; +use stdClass; +use function count; +use function get_class; +use function is_string; + /** * Class ObjectPoolTrait + * * @package Toolkit\ObjUtil\Traits */ trait ObjectPoolTrait { /** - * @var \SplStack[] [class => \SplStack] + * @var SplStack[] [class => \SplStack] */ private static $pool = []; /** * @param string $class + * * @return mixed */ public static function get(string $class) @@ -35,11 +45,11 @@ public static function get(string $class) } /** - * @param \stdClass|string $object + * @param stdClass|string $object */ public static function put($object): void { - if (\is_string($object)) { + if (is_string($object)) { $object = new $object; } @@ -47,11 +57,12 @@ public static function put($object): void } /** - * @param string $class - * @param \Closure $handler + * @param string $class + * @param Closure $handler + * * @return mixed */ - public static function use($class, \Closure $handler) + public static function use($class, Closure $handler) { $obj = self::get($class); @@ -63,15 +74,16 @@ public static function use($class, \Closure $handler) } /** - * @param string|\stdClass $class - * @return \SplStack + * @param string|stdClass $class + * + * @return SplStack */ - public static function getStack($class): \SplStack + public static function getStack($class): SplStack { - $class = \is_string($class) ? $class : \get_class($class); + $class = is_string($class) ? $class : get_class($class); if (!isset(self::$pool[$class])) { - self::$pool[$class] = new \SplStack(); + self::$pool[$class] = new SplStack(); } return self::$pool[$class]; @@ -79,31 +91,33 @@ public static function getStack($class): \SplStack /** * @param null $class + * * @return int - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public static function count($class = null): int { if ($class) { if (!isset(self::$pool[$class])) { - throw new \InvalidArgumentException("The object is never created of the class: $class"); + throw new InvalidArgumentException("The object is never created of the class: $class"); } return self::$pool[$class]->count(); } - return \count(self::$pool); + return count(self::$pool); } /** * @param null $class - * @throws \InvalidArgumentException + * + * @throws InvalidArgumentException */ public static function destroy($class = null): void { if ($class) { if (!isset(self::$pool[$class])) { - throw new \InvalidArgumentException("The object is never created of the class: $class"); + throw new InvalidArgumentException("The object is never created of the class: $class"); } unset(self::$pool[$class]); diff --git a/libs/obj-utils/src/Traits/PropertyAccessByGetterSetterTrait.php b/libs/obj-utils/src/Traits/PropertyAccessByGetterSetterTrait.php index 714924b..f709109 100644 --- a/libs/obj-utils/src/Traits/PropertyAccessByGetterSetterTrait.php +++ b/libs/obj-utils/src/Traits/PropertyAccessByGetterSetterTrait.php @@ -11,9 +11,12 @@ use Toolkit\ObjUtil\Exception\GetPropertyException; use Toolkit\ObjUtil\Exception\PropertyException; use Toolkit\ObjUtil\Exception\SetPropertyException; +use function get_class; +use function method_exists; /** * trait PropertyAccessByGetterSetterTrait + * * @package Toolkit\ObjUtil\Traits * ``` * class A @@ -26,53 +29,58 @@ trait PropertyAccessByGetterSetterTrait { /** * @reference yii2 yii\base\Object::__set() + * * @param $name * @param $value + * * @throws SetPropertyException */ public function __set($name, $value) { $setter = 'set' . ucfirst($name); - if (\method_exists($this, $setter)) { + if (method_exists($this, $setter)) { $this->$setter($value); - } elseif (\method_exists($this, 'get' . ucfirst($name))) { - throw new SetPropertyException('Setting a Read-only property! ' . \get_class($this) . "::{$name}"); + } elseif (method_exists($this, 'get' . ucfirst($name))) { + throw new SetPropertyException('Setting a Read-only property! ' . get_class($this) . "::{$name}"); } else { - throw new SetPropertyException('Setting a Unknown property! ' . \get_class($this) . "::{$name}"); + throw new SetPropertyException('Setting a Unknown property! ' . get_class($this) . "::{$name}"); } } /** * @reference yii2 yii\base\Object::__set() + * * @param $name - * @throws GetPropertyException + * * @return mixed + * @throws GetPropertyException */ public function __get($name) { $getter = 'get' . ucfirst($name); - if (\method_exists($this, $getter)) { + if (method_exists($this, $getter)) { return $this->$getter(); } - if (\method_exists($this, 'set' . ucfirst($name))) { - throw new GetPropertyException('Getting a Write-only property! ' . \get_class($this) . "::{$name}"); + if (method_exists($this, 'set' . ucfirst($name))) { + throw new GetPropertyException('Getting a Write-only property! ' . get_class($this) . "::{$name}"); } - throw new GetPropertyException('Getting a Unknown property! ' . \get_class($this) . "::{$name}"); + throw new GetPropertyException('Getting a Unknown property! ' . get_class($this) . "::{$name}"); } /** * @param $name + * * @return bool */ public function __isset($name) { $getter = 'get' . ucfirst($name); - if (\method_exists($this, $getter)) { + if (method_exists($this, $getter)) { return $this->$getter() !== null; } @@ -81,19 +89,20 @@ public function __isset($name) /** * @param $name - * @throws \Toolkit\ObjUtil\Exception\PropertyException + * + * @throws PropertyException */ public function __unset($name) { $setter = 'set' . ucfirst($name); - if (\method_exists($this, $setter)) { + if (method_exists($this, $setter)) { $this->$setter(null); return; } - throw new PropertyException('Unset an unknown or read-only property: ' . \get_class($this) . '::' . $name); + throw new PropertyException('Unset an unknown or read-only property: ' . get_class($this) . '::' . $name); } } diff --git a/libs/obj-utils/src/Traits/SingletonTrait.php b/libs/obj-utils/src/Traits/SingletonTrait.php index d3cd264..68e282a 100644 --- a/libs/obj-utils/src/Traits/SingletonTrait.php +++ b/libs/obj-utils/src/Traits/SingletonTrait.php @@ -12,6 +12,7 @@ /** * Trait SingletonTrait + * * @package Toolkit\ObjUtil\Traits */ trait SingletonTrait diff --git a/libs/obj-utils/src/Traits/StdObjectTrait.php b/libs/obj-utils/src/Traits/StdObjectTrait.php index 403efe7..74683fd 100644 --- a/libs/obj-utils/src/Traits/StdObjectTrait.php +++ b/libs/obj-utils/src/Traits/StdObjectTrait.php @@ -8,16 +8,25 @@ namespace Toolkit\ObjUtil\Traits; +use InvalidArgumentException; use Toolkit\ObjUtil\Obj; +use function basename; +use function call_user_func_array; +use function dirname; +use function get_class; +use function str_replace; +use function strpos; /** * Class StdObjectTrait + * * @package Toolkit\ObjUtil\Traits */ trait StdObjectTrait { /** * get called class full name + * * @return string */ final public static function fullName(): string @@ -27,32 +36,37 @@ final public static function fullName(): string /** * get called class namespace + * * @param null|string $fullName + * * @return string */ final public static function spaceName(string $fullName = null): string { $fullName = $fullName ?: self::fullName(); - $fullName = \str_replace('\\', '/', $fullName); + $fullName = str_replace('\\', '/', $fullName); - return \strpos($fullName, '/') ? \dirname($fullName) : null; + return strpos($fullName, '/') ? dirname($fullName) : null; } /** * get called class name + * * @param null|string $fullName + * * @return string */ final public static function className(string $fullName = null): string { $fullName = $fullName ?: self::fullName(); - $fullName = \str_replace('\\', '/', $fullName); + $fullName = str_replace('\\', '/', $fullName); - return \basename($fullName); + return basename($fullName); } /** * StdObject constructor. + * * @param array $config */ public function __construct(array $config = []) @@ -73,8 +87,9 @@ protected function init(): void /** * @param string $method * @param $args - * @throws \InvalidArgumentException + * * @return mixed + * @throws InvalidArgumentException */ public function __call($method, array $args) { @@ -82,21 +97,22 @@ public function __call($method, array $args) // return call_user_func_array( array($this, $method), (array) $args); // } - throw new \InvalidArgumentException('Called a Unknown method! ' . \get_class($this) . "->{$method}()"); + throw new InvalidArgumentException('Called a Unknown method! ' . get_class($this) . "->{$method}()"); } /** * @param string $method * @param $args + * * @return mixed - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public static function __callStatic(string $method, $args) { if (method_exists(self::class, $method)) { - return \call_user_func_array([self::class, $method], (array)$args); + return call_user_func_array([self::class, $method], (array)$args); } - throw new \InvalidArgumentException('Called a Unknown static method! [ ' . self::class . "::{$method}()]"); + throw new InvalidArgumentException('Called a Unknown static method! [ ' . self::class . "::{$method}()]"); } } diff --git a/libs/php-utils/src/AutoLoader.php b/libs/php-utils/src/AutoLoader.php index f3d3b10..a19099d 100644 --- a/libs/php-utils/src/AutoLoader.php +++ b/libs/php-utils/src/AutoLoader.php @@ -9,8 +9,20 @@ namespace Toolkit\PhpUtil; +use InvalidArgumentException; +use function array_merge; +use function file_exists; +use function spl_autoload_register; +use function spl_autoload_unregister; +use function str_replace; +use function strlen; +use function strpos; +use function substr; +use const DIRECTORY_SEPARATOR; + /** * Class AutoLoader + * * @package Toolkit\PhpUtil * ```php * AutoLoader::addFiles([ @@ -65,6 +77,7 @@ class AutoLoader /** * @param array $files + * * @return self */ public static function getLoader(array $files = []): self @@ -114,7 +127,7 @@ public static function setFiles(array $files): void public static function addFiles(array $files): void { if (self::$files) { - self::$files = \array_merge(self::$files, $files); + self::$files = array_merge(self::$files, $files); } else { self::$files = $files; } @@ -139,7 +152,7 @@ public function addPsr0(string $prefix, string $path): void public function addPsr0Map(array $psr0Map): void { if ($this->psr0Map) { - $this->psr0Map = \array_merge($this->psr0Map, $psr0Map); + $this->psr0Map = array_merge($this->psr0Map, $psr0Map); } else { $this->psr0Map = $psr0Map; } @@ -148,15 +161,16 @@ public function addPsr0Map(array $psr0Map): void /** * @param string $prefix * @param string $path - * @throws \InvalidArgumentException + * + * @throws InvalidArgumentException */ public function addPsr4(string $prefix, string $path): void { // Register directories for a new namespace. - $length = \strlen($prefix); + $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { - throw new \InvalidArgumentException('A non-empty PSR-4 prefix must end with a namespace separator.'); + throw new InvalidArgumentException('A non-empty PSR-4 prefix must end with a namespace separator.'); } $this->psr4Map[$prefix] = $path; @@ -168,7 +182,7 @@ public function addPsr4(string $prefix, string $path): void public function addPsr4Map(array $psr4Map): void { if ($this->psr4Map) { - $this->psr4Map = \array_merge($this->psr4Map, $psr4Map); + $this->psr4Map = array_merge($this->psr4Map, $psr4Map); } else { $this->psr4Map = $psr4Map; } @@ -212,7 +226,7 @@ public function setClassMap(array $classMap): void public function addClassMap(array $classMap): void { if ($this->classMap) { - $this->classMap = \array_merge($this->classMap, $classMap); + $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } @@ -220,11 +234,12 @@ public function addClassMap(array $classMap): void /** * Registers this instance as an autoloader. + * * @param bool $prepend Whether to prepend the autoloader or not */ public function register(bool $prepend = false): void { - \spl_autoload_register([$this, 'loadClass'], true, $prepend); + spl_autoload_register([$this, 'loadClass'], true, $prepend); } /** @@ -232,12 +247,14 @@ public function register(bool $prepend = false): void */ public function unRegister(): void { - \spl_autoload_unregister([$this, 'loadClass']); + spl_autoload_unregister([$this, 'loadClass']); } /** * Loads the given class or interface. - * @param string $class The name of the class + * + * @param string $class The name of the class + * * @return bool|null True if loaded, null otherwise */ public function loadClass(string $class): ?bool @@ -252,14 +269,16 @@ public function loadClass(string $class): ?bool /** * Finds the path to the file where the class is defined. + * * @param string $class The name of the class + * * @return string|false The path if found, false otherwise */ public function findFile(string $class) { // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 if ('\\' === $class[0]) { - $class = (string)\substr($class, 1); + $class = (string)substr($class, 1); } // class map lookup @@ -280,32 +299,33 @@ public function findFile(string $class) /** * @param string $class * @param string $ext + * * @return bool|string */ private function findFileWithExtension(string $class, string $ext) { // PSR-4 lookup - $logicalPathPsr4 = \str_replace('\\', \DIRECTORY_SEPARATOR, $class) . $ext; + $logicalPathPsr4 = str_replace('\\', DIRECTORY_SEPARATOR, $class) . $ext; // PSR-4 foreach ($this->psr4Map as $prefix => $dir) { - if (0 === \strpos($class, $prefix)) { - $length = \strlen($prefix); + if (0 === strpos($class, $prefix)) { + $length = strlen($prefix); - if (\file_exists($file = $dir . \DIRECTORY_SEPARATOR . \substr($logicalPathPsr4, $length))) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) { return $file; } } } // PEAR-like class name - $logicalPathPsr0 = \str_replace('_', \DIRECTORY_SEPARATOR, $class) . $ext; + $logicalPathPsr0 = str_replace('_', DIRECTORY_SEPARATOR, $class) . $ext; foreach ($this->psr0Map as $prefix => $dir) { - if (0 === \strpos($class, $prefix)) { - $file = $dir . \DIRECTORY_SEPARATOR . $logicalPathPsr0; + if (0 === strpos($class, $prefix)) { + $file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0; - if (\file_exists($file)) { + if (file_exists($file)) { return $file; } } @@ -335,6 +355,7 @@ function _globalIncludeFile($fileIdentifier, $file) /** * Scope isolated include. * Prevents access to $this/self from included files. + * * @param $file */ function _includeClassFile($file) diff --git a/libs/php-utils/src/Php.php b/libs/php-utils/src/Php.php index af9e59a..8edec73 100644 --- a/libs/php-utils/src/Php.php +++ b/libs/php-utils/src/Php.php @@ -10,6 +10,7 @@ /** * Class Php - alias of the class PhpHelper + * * @package Toolkit\PhpUtil */ class Php extends PhpHelper diff --git a/libs/php-utils/src/PhpDoc.php b/libs/php-utils/src/PhpDoc.php index 9e77b3f..08d5314 100644 --- a/libs/php-utils/src/PhpDoc.php +++ b/libs/php-utils/src/PhpDoc.php @@ -8,8 +8,21 @@ namespace Toolkit\PhpUtil; +use function array_merge; +use function in_array; +use function is_array; +use function preg_match; +use function preg_replace; +use function preg_split; +use function str_replace; +use function substr; +use function trim; +use const PREG_OFFSET_CAPTURE; +use const PREG_SPLIT_NO_EMPTY; + /** * Class PhpDoc + * * @package Toolkit\PhpUtil */ class PhpDoc @@ -20,21 +33,23 @@ class PhpDoc /** * Parses the comment block into tags. + * * @param string $comment The comment block text * @param array $options - * - 'allow' // only allowed tags - * - 'ignore' // ignored tags - * - 'default' => 'description', // default tag name, first line text will attach to it. + * - 'allow' // only allowed tags + * - 'ignore' // ignored tags + * - 'default' => 'description', // default tag name, first line text will attach to it. * @param array $defaults + * * @return array The parsed tags */ public static function getTags(string $comment, array $options = [], array $defaults = []): array { - if (!$comment = \trim($comment, "/ \n")) { + if (!$comment = trim($comment, "/ \n")) { return []; } - $options = \array_merge([ + $options = array_merge([ 'allow' => [], // only allowed tags 'ignore' => ['param', 'return'], // ignore tags 'default' => 'description', // default tag name, first line text will attach to it. @@ -44,34 +59,31 @@ public static function getTags(string $comment, array $options = [], array $defa $ignored = (array)$options['ignore']; $default = (string)$options['default']; - $comment = \str_replace("\r\n", "\n", $comment); - $comment = "@{$default} \n" . - \str_replace("\r", '', - \trim(\preg_replace('/^\s*\**( |\t)?/m', '', $comment)) - ); + $comment = str_replace("\r\n", "\n", $comment); + $comment = "@{$default} \n" . str_replace("\r", '', trim(preg_replace('/^\s*\**( |\t)?/m', '', $comment))); $tags = []; - $parts = \preg_split('/^\s*@/m', $comment, -1, \PREG_SPLIT_NO_EMPTY); + $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY); foreach ($parts as $part) { - if (\preg_match('/^(\w+)(.*)/ms', \trim($part), $matches)) { + if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) { $name = $matches[1]; - if (!$name || \in_array($name, $ignored, true)) { + if (!$name || in_array($name, $ignored, true)) { continue; } - if (!$value = \trim($matches[2])) { + if (!$value = trim($matches[2])) { continue; } // always allow default tag - if ($default !== $name && $allow && !\in_array($name, $allow, true)) { + if ($default !== $name && $allow && !in_array($name, $allow, true)) { continue; } if (!isset($tags[$name])) { $tags[$name] = $value; - } elseif (\is_array($tags[$name])) { + } elseif (is_array($tags[$name])) { $tags[$name][] = $value; } else { $tags[$name] = [$tags[$name], $value]; @@ -79,20 +91,22 @@ public static function getTags(string $comment, array $options = [], array $defa } } - return $defaults ? \array_merge($defaults, $tags) :$tags; + return $defaults ? array_merge($defaults, $tags) : $tags; } /** * Returns the first line of docBlock. + * * @param string $comment + * * @return string */ public static function firstLine(string $comment): string { - $docLines = \preg_split('~\R~u', $comment); + $docLines = preg_split('~\R~u', $comment); if (isset($docLines[1])) { - return \trim($docLines[1], "/\t *"); + return trim($docLines[1], "/\t *"); } return ''; @@ -101,15 +115,17 @@ public static function firstLine(string $comment): string /** * Returns full description from the doc-block. * If have multi line text, will return multi line. + * * @param string $comment + * * @return string */ public static function description(string $comment): string { - $comment = \str_replace("\r", '', \trim(\preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/')))); + $comment = str_replace("\r", '', trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/')))); - if (\preg_match('/^\s*@\w+/m', $comment, $matches, \PREG_OFFSET_CAPTURE)) { - $comment = \trim(\substr($comment, 0, $matches[0][1])); + if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) { + $comment = trim(substr($comment, 0, $matches[0][1])); } return $comment; diff --git a/libs/php-utils/src/PhpDotEnv.php b/libs/php-utils/src/PhpDotEnv.php index ff9309e..bf3a170 100644 --- a/libs/php-utils/src/PhpDotEnv.php +++ b/libs/php-utils/src/PhpDotEnv.php @@ -8,8 +8,25 @@ namespace Toolkit\PhpUtil; +use function array_flip; +use function array_keys; +use function constant; +use function defined; +use function explode; +use function getenv; +use function implode; +use function is_file; +use function is_int; +use function is_readable; +use function is_string; +use function parse_ini_file; +use function putenv; +use function strpos; +use function strtoupper; + /** * Class PhpDotEnv - local env read + * * @package Toolkit\PhpUtil * * in local config file `.env` (must is 'ini' format): @@ -35,6 +52,7 @@ final class PhpDotEnv /** * @param string $fileDir * @param string $fileName + * * @return static */ public static function load(string $fileDir, string $fileName = '.env') @@ -44,6 +62,7 @@ public static function load(string $fileDir, string $fileName = '.env') /** * constructor. + * * @param string $fileDir * @param string $fileName */ @@ -59,27 +78,28 @@ public function __construct(string $fileDir, string $fileName = '.env') */ public function add(string $file): void { - if (\is_file($file) && \is_readable($file)) { - $this->settingEnv(\parse_ini_file($file)); + if (is_file($file) && is_readable($file)) { + $this->settingEnv(parse_ini_file($file)); } } /** * setting env data + * * @param array $data */ private function settingEnv(array $data): void { - $loadedVars = \array_flip(\explode(',', \getenv(self::FULL_KEY))); + $loadedVars = array_flip(explode(',', getenv(self::FULL_KEY))); unset($loadedVars['']); foreach ($data as $name => $value) { - if (\is_int($name) || !\is_string($value)) { + if (is_int($name) || !is_string($value)) { continue; } - $name = \strtoupper($name); - $notHttpName = 0 !== \strpos($name, 'HTTP_'); + $name = strtoupper($name); + $notHttpName = 0 !== strpos($name, 'HTTP_'); // don't check existence with getenv() because of thread safety issues if ((isset($_ENV[$name]) || (isset($_SERVER[$name]) && $notHttpName)) && !isset($loadedVars[$name])) { @@ -87,12 +107,12 @@ private function settingEnv(array $data): void } // is a constant var - if ($value && \defined($value)) { - $value = \constant($value); + if ($value && defined($value)) { + $value = constant($value); } // eg: "FOO=BAR" - \putenv("$name=$value"); + putenv("$name=$value"); $_ENV[$name] = $value; if ($notHttpName) { @@ -103,9 +123,9 @@ private function settingEnv(array $data): void } if ($loadedVars) { - $loadedVars = \implode(',', \array_keys($loadedVars)); - \putenv(self::FULL_KEY . "=$loadedVars"); - $_ENV[self::FULL_KEY] = $loadedVars; + $loadedVars = implode(',', array_keys($loadedVars)); + putenv(self::FULL_KEY . "=$loadedVars"); + $_ENV[self::FULL_KEY] = $loadedVars; $_SERVER[self::FULL_KEY] = $loadedVars; } } diff --git a/libs/php-utils/src/PhpEnv.php b/libs/php-utils/src/PhpEnv.php index e643caa..a072333 100644 --- a/libs/php-utils/src/PhpEnv.php +++ b/libs/php-utils/src/PhpEnv.php @@ -8,8 +8,17 @@ namespace Toolkit\PhpUtil; +use RuntimeException; +use function defined; +use function error_reporting; +use function extension_loaded; +use function function_exists; +use function get_loaded_extensions; +use function in_array; + /** * Class PhpEnv + * * @package Toolkit\PhpUtil */ class PhpEnv @@ -20,15 +29,17 @@ class PhpEnv /** * Get PHP version + * * @return string */ public static function getVersion(): string { - return \defined('HHVM_VERSION') ? HHVM_VERSION : PHP_VERSION; + return defined('HHVM_VERSION') ? HHVM_VERSION : PHP_VERSION; } /** * isEmbed + * * @return boolean */ public static function isEmbed(): bool @@ -46,6 +57,7 @@ public static function isCgi(): bool /** * is Cli + * * @return boolean */ public static function isCli(): bool @@ -56,6 +68,7 @@ public static function isCli(): bool /** * is Build In Server * run server use like: `php -S 127.0.0.1:8085` + * * @return boolean */ public static function isBuiltInServer(): bool @@ -73,11 +86,12 @@ public static function isDevServer(): bool /** * isWeb + * * @return boolean */ public static function isWeb(): bool { - return \in_array(PHP_SAPI, [ + return in_array(PHP_SAPI, [ 'apache', 'cgi', 'fast-cgi', @@ -90,15 +104,17 @@ public static function isWeb(): bool /** * isHHVM + * * @return boolean */ public static function isHHVM(): bool { - return \defined('HHVM_VERSION'); + return defined('HHVM_VERSION'); } /** * isPHP + * * @return boolean */ public static function isPHP(): bool @@ -108,6 +124,7 @@ public static function isPHP(): bool /** * setStrict + * * @return void */ public static function setStrict(): void @@ -117,29 +134,32 @@ public static function setStrict(): void /** * setMuted + * * @return void */ public static function setMuted(): void { - \error_reporting(0); + error_reporting(0); } /** * @param string $name + * * @return bool */ public static function hasExtension(string $name): bool { - return \extension_loaded($name); + return extension_loaded($name); } /** * Returns true when the runtime used is PHP and Xdebug is loaded. + * * @return boolean */ public static function hasXDebug(): bool { - return static::isPHP() && \extension_loaded('xdebug'); + return static::isPHP() && extension_loaded('xdebug'); } /** @@ -147,7 +167,7 @@ public static function hasXDebug(): bool */ public static function hasPcntl(): bool { - return \function_exists('pcntl_fork'); + return function_exists('pcntl_fork'); } /** @@ -155,21 +175,22 @@ public static function hasPcntl(): bool */ public static function hasPosix(): bool { - return \function_exists('posix_kill'); + return function_exists('posix_kill'); } /** * @param $name * @param bool|false $throwException + * * @return bool - * @throws \RuntimeException + * @throws RuntimeException */ public static function extIsLoaded(string $name, $throwException = false): bool { - $result = \extension_loaded($name); + $result = extension_loaded($name); if (!$result && $throwException) { - throw new \RuntimeException("Extension [$name] is not loaded."); + throw new RuntimeException("Extension [$name] is not loaded."); } return $result; @@ -177,7 +198,9 @@ public static function extIsLoaded(string $name, $throwException = false): bool /** * 检查多个扩展加载情况 + * * @param array $extensions + * * @return array|bool */ public static function checkExtList(array $extensions = []) @@ -185,7 +208,7 @@ public static function checkExtList(array $extensions = []) $allTotal = []; foreach ($extensions as $extension) { - if (!\extension_loaded($extension)) { + if (!extension_loaded($extension)) { $allTotal['no'][] = $extension; } else { $allTotal['yes'][] = $extension; @@ -197,11 +220,13 @@ public static function checkExtList(array $extensions = []) /** * 返回加载的扩展 + * * @param bool $zend_extensions + * * @return array */ public static function getLoadedExtension($zend_extensions = false): array { - return \get_loaded_extensions($zend_extensions); + return get_loaded_extensions($zend_extensions); } } diff --git a/libs/php-utils/src/PhpError.php b/libs/php-utils/src/PhpError.php index e3fbffa..ba532cc 100644 --- a/libs/php-utils/src/PhpError.php +++ b/libs/php-utils/src/PhpError.php @@ -8,25 +8,44 @@ namespace Toolkit\PhpUtil; +use const E_COMPILE_ERROR; +use const E_COMPILE_WARNING; +use const E_CORE_ERROR; +use const E_CORE_WARNING; +use const E_DEPRECATED; +use const E_ERROR; +use const E_NOTICE; +use const E_PARSE; +use const E_RECOVERABLE_ERROR; +use const E_STRICT; +use const E_USER_DEPRECATED; +use const E_USER_ERROR; +use const E_USER_NOTICE; +use const E_USER_WARNING; +use const E_WARNING; + /** * Class PhpError + * * @package Toolkit\PhpUtil */ class PhpError { /** @var array */ - public static $fatalErrors = [\E_ERROR, \E_PARSE, \E_CORE_ERROR, \E_COMPILE_ERROR, \E_USER_ERROR]; + public static $fatalErrors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; /** * $lastError = error_get_last(); + * * @param array $lastError * @param null|string $catcher + * * @return array */ public static function toArray(array $lastError, $catcher = null): array { $digest = 'Fatal Error (' . self::codeToString($lastError['type']) . '): ' . $lastError['message']; - $data = [ + $data = [ 'code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], @@ -43,40 +62,41 @@ public static function toArray(array $lastError, $catcher = null): array /** * @param int $code + * * @return string */ public static function codeToString(int $code): string { switch ($code) { - case \E_ERROR: + case E_ERROR: return 'E_ERROR'; - case \E_WARNING: + case E_WARNING: return 'E_WARNING'; - case \E_PARSE: + case E_PARSE: return 'E_PARSE'; - case \E_NOTICE: + case E_NOTICE: return 'E_NOTICE'; - case \E_CORE_ERROR: + case E_CORE_ERROR: return 'E_CORE_ERROR'; - case \E_CORE_WARNING: + case E_CORE_WARNING: return 'E_CORE_WARNING'; - case \E_COMPILE_ERROR: + case E_COMPILE_ERROR: return 'E_COMPILE_ERROR'; - case \E_COMPILE_WARNING: + case E_COMPILE_WARNING: return 'E_COMPILE_WARNING'; - case \E_USER_ERROR: + case E_USER_ERROR: return 'E_USER_ERROR'; - case \E_USER_WARNING: + case E_USER_WARNING: return 'E_USER_WARNING'; - case \E_USER_NOTICE: + case E_USER_NOTICE: return 'E_USER_NOTICE'; - case \E_STRICT: + case E_STRICT: return 'E_STRICT'; - case \E_RECOVERABLE_ERROR: + case E_RECOVERABLE_ERROR: return 'E_RECOVERABLE_ERROR'; - case \E_DEPRECATED: + case E_DEPRECATED: return 'E_DEPRECATED'; - case \E_USER_DEPRECATED: + case E_USER_DEPRECATED: return 'E_USER_DEPRECATED'; } diff --git a/libs/php-utils/src/PhpException.php b/libs/php-utils/src/PhpException.php index 30d939e..a63c072 100644 --- a/libs/php-utils/src/PhpException.php +++ b/libs/php-utils/src/PhpException.php @@ -8,8 +8,15 @@ namespace Toolkit\PhpUtil; +use Exception; +use Throwable; +use function get_class; +use function json_encode; +use function strip_tags; + /** * Class PhpException + * * @package Toolkit\PhpUtil */ class PhpException @@ -25,10 +32,12 @@ public static function toString($e, $getTrace = true, $catcher = null): string /** * Converts an exception into a simple string. - * @param \Exception|\Throwable $e the exception being converted - * @param bool $clearHtml - * @param bool $getTrace - * @param null|string $catcher + * + * @param Exception|Throwable $e the exception being converted + * @param bool $clearHtml + * @param bool $getTrace + * @param null|string $catcher + * * @return string the string representation of the exception. */ public static function toHtml($e, bool $getTrace = true, string $catcher = null, bool $clearHtml = false): string @@ -36,32 +45,27 @@ public static function toHtml($e, bool $getTrace = true, string $catcher = null, if (!$getTrace) { $message = "Error: {$e->getMessage()}"; } else { - $message = sprintf( - "

%s(%d): %s

\n
File: %s(Line %d)%s \n\n%s
", - \get_class($e), - $e->getCode(), - $e->getMessage(), - $e->getFile(), - $e->getLine(), - $catcher ? "\nCatch By: $catcher" : '', - $e->getTraceAsString() - ); + $message = sprintf("

%s(%d): %s

\n
File: %s(Line %d)%s \n\n%s
", + get_class($e), $e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(), + $catcher ? "\nCatch By: $catcher" : '', $e->getTraceAsString()); } - return $clearHtml ? \strip_tags($message) : "
{$message}
"; + return $clearHtml ? strip_tags($message) : "
{$message}
"; } /** * Converts an exception into a simple array. - * @param \Exception|\Throwable $e the exception being converted - * @param bool $getTrace - * @param null|string $catcher + * + * @param Exception|Throwable $e the exception being converted + * @param bool $getTrace + * @param null|string $catcher + * * @return array */ public static function toArray($e, bool $getTrace = true, string $catcher = null): array { $data = [ - 'class' => \get_class($e), + 'class' => get_class($e), 'message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile() . ':' . $e->getLine(), @@ -80,27 +84,23 @@ public static function toArray($e, bool $getTrace = true, string $catcher = null /** * Converts an exception into a json string. - * @param \Exception|\Throwable $e the exception being converted - * @param bool $getTrace - * @param null|string $catcher + * + * @param Exception|Throwable $e the exception being converted + * @param bool $getTrace + * @param null|string $catcher + * * @return string the string representation of the exception. */ public static function toJson($e, bool $getTrace = true, string $catcher = null): string { if (!$getTrace) { - return \json_encode(['msg' => "Error: {$e->getMessage()}"]); + return json_encode(['msg' => "Error: {$e->getMessage()}"]); } $map = [ 'code' => $e->getCode() ?: 500, - 'msg' => sprintf( - '%s(%d): %s, File: %s(Line %d)', - \get_class($e), - $e->getCode(), - $e->getMessage(), - $e->getFile(), - $e->getLine() - ), + 'msg' => sprintf('%s(%d): %s, File: %s(Line %d)', get_class($e), $e->getCode(), $e->getMessage(), + $e->getFile(), $e->getLine()), 'data' => $e->getTrace() ]; @@ -112,6 +112,6 @@ public static function toJson($e, bool $getTrace = true, string $catcher = null) $map['trace'] = $e->getTrace(); } - return \json_encode($map); + return json_encode($map); } } diff --git a/libs/php-utils/src/PhpHelper.php b/libs/php-utils/src/PhpHelper.php index afc571f..0314a69 100644 --- a/libs/php-utils/src/PhpHelper.php +++ b/libs/php-utils/src/PhpHelper.php @@ -1,26 +1,47 @@ 0) { + $cb = explode('::', $cb, 2); + // function + } elseif (function_exists($cb)) { return $cb(...$args); } - - // ClassName::method - $cb = \explode('::', $cb, 2); - } elseif (\is_object($cb) && \method_exists($cb, '__invoke')) { + } elseif (is_object($cb) && method_exists($cb, '__invoke')) { return $cb(...$args); } - if (\is_array($cb)) { + if (is_array($cb)) { [$obj, $mhd] = $cb; - return \is_object($obj) ? $obj->$mhd(...$args) : $obj::$mhd(...$args); + return is_object($obj) ? $obj->$mhd(...$args) : $obj::$mhd(...$args); } return $cb(...$args); @@ -56,6 +78,7 @@ public static function call($cb, ...$args) /** * @param callable $cb * @param array $args + * * @return mixed */ public static function callByArray(callable $cb, array $args) @@ -67,23 +90,25 @@ public static function callByArray(callable $cb, array $args) * 给对象设置属性值 * - 会先尝试用 setter 方法设置属性 * - 再尝试直接设置属性 + * * @param mixed $object An object instance * @param array $options + * * @return mixed */ public static function initObject($object, array $options) { foreach ($options as $property => $value) { - if (\is_numeric($property)) { + if (is_numeric($property)) { continue; } - $setter = 'set' . \ucfirst($property); + $setter = 'set' . ucfirst($property); // has setter - if (\method_exists($object, $setter)) { + if (method_exists($object, $setter)) { $object->$setter($value); - } elseif (\property_exists($object, $property)) { + } elseif (property_exists($object, $property)) { $object->$property = $value; } } @@ -93,31 +118,33 @@ public static function initObject($object, array $options) /** * 获取资源消耗 + * * @param int $startTime * @param int|float $startMem * @param array $info * @param bool $realUsage + * * @return array */ public static function runtime($startTime, $startMem, array $info = [], $realUsage = false): array { $info['startTime'] = $startTime; - $info['endTime'] = \microtime(true); - $info['endMemory'] = \memory_get_usage($realUsage); + $info['endTime'] = microtime(true); + $info['endMemory'] = memory_get_usage($realUsage); // 计算运行时间 - $info['runtime'] = \number_format(($info['endTime'] - $startTime) * 1000, 3) . 'ms'; + $info['runtime'] = number_format(($info['endTime'] - $startTime) * 1000, 3) . 'ms'; if ($startMem) { - $startMem = \array_sum(\explode(' ', $startMem)); - $endMem = \array_sum(\explode(' ', $info['endMemory'])); + $startMem = array_sum(explode(' ', $startMem)); + $endMem = array_sum(explode(' ', $info['endMemory'])); - $info['memory'] = \number_format(($endMem - $startMem) / 1024, 3) . 'kb'; + $info['memory'] = number_format(($endMem - $startMem) / 1024, 3) . 'kb'; } - $peakMem = \memory_get_peak_usage(true) / 1024 / 1024; + $peakMem = memory_get_peak_usage(true) / 1024 / 1024; // record - $info['peakMemory'] = \number_format($peakMem, 3) . 'Mb'; + $info['peakMemory'] = number_format($peakMem, 3) . 'Mb'; return $info; } @@ -127,28 +154,32 @@ public static function runtime($startTime, $startMem, array $info = [], $realUsa */ public static function getUserConstants(): array { - $const = \get_defined_constants(true); + $const = get_defined_constants(true); return $const['user'] ?? []; } /** * dump vars + * * @param array ...$args + * * @return string */ public static function dumpVars(...$args): string { - \ob_start(); - \var_dump(...$args); - $string = \ob_get_clean(); + ob_start(); + var_dump(...$args); + $string = ob_get_clean(); - return \preg_replace("/=>\n\s+/", '=> ', $string); + return preg_replace("/=>\n\s+/", '=> ', $string); } /** * print vars + * * @param array ...$args + * * @return string */ public static function printVars(...$args): string @@ -159,18 +190,19 @@ public static function printVars(...$args): string $string .= print_r($arg, 1) . PHP_EOL; } - return \preg_replace("/Array\n\s+\(/", 'Array (', $string); + return preg_replace("/Array\n\s+\(/", 'Array (', $string); } /** * @param mixed $var + * * @return string */ public static function exportVar($var): string { - $string = \var_export($var, true); + $string = var_export($var, true); - return \preg_replace('/=>\s+\n\s+array \(/', '=> array (', $string); + return preg_replace('/=>\s+\n\s+array \(/', '=> array (', $string); } } diff --git a/libs/php-utils/src/Type.php b/libs/php-utils/src/Type.php index a07691f..452ee20 100644 --- a/libs/php-utils/src/Type.php +++ b/libs/php-utils/src/Type.php @@ -10,6 +10,7 @@ /** * Class Type - php data type + * * @package Toolkit\PhpUtil */ final class Type diff --git a/libs/php-utils/test/PhpDocTest.php b/libs/php-utils/test/PhpDocTest.php index 5316e1f..b4dbc80 100644 --- a/libs/php-utils/test/PhpDocTest.php +++ b/libs/php-utils/test/PhpDocTest.php @@ -7,6 +7,7 @@ /** * Class PhpDocTest + * * @package Toolkit\PhpUtilTest */ class PhpDocTest extends TestCase @@ -24,7 +25,7 @@ public function testGetTags(): void * {fullCmd}:stop Stop the http server */ DOC; - $ret = PhpDoc::getTags($comment); + $ret = PhpDoc::getTags($comment); $this->assertCount(3, $ret); $this->assertArrayHasKey('since', $ret); $this->assertArrayHasKey('example', $ret); diff --git a/libs/str-utils/src/HtmlHelper.php b/libs/str-utils/src/HtmlHelper.php index c9be2f5..55da156 100644 --- a/libs/str-utils/src/HtmlHelper.php +++ b/libs/str-utils/src/HtmlHelper.php @@ -8,54 +8,73 @@ namespace Toolkit\StrUtil; +use function array_key_exists; +use function html_entity_decode; +use function htmlentities; +use function htmlspecialchars; +use function htmlspecialchars_decode; +use function is_array; +use function is_string; +use function preg_match_all; +use function preg_replace; +use function strpos; +use const ENT_QUOTES; + /** * Class HtmlHelper + * * @package Toolkit\StrUtil */ class HtmlHelper { /** * Encodes special characters into HTML entities. + * * @param string $text data to be encoded * @param string $charset + * * @return string the encoded data * @see http://www.php.net/manual/en/function.htmlspecialchars.php */ public static function encode($text, $charset = 'utf-8'): string { - return \htmlspecialchars($text, ENT_QUOTES, $charset); + return htmlspecialchars($text, ENT_QUOTES, $charset); } /** * This is the opposite of {@link encode()}. + * * @param string $text data to be decoded + * * @return string the decoded data * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php */ public static function decode($text): string { - return \htmlspecialchars_decode($text, ENT_QUOTES); + return htmlspecialchars_decode($text, ENT_QUOTES); } /** * @form yii1 + * * @param array $data data to be encoded * @param string $charset + * * @return array the encoded data - * @see http://www.php.net/manual/en/function.htmlspecialchars.php + * @see http://www.php.net/manual/en/function.htmlspecialchars.php */ public static function encodeArray($data, $charset = 'utf-8'): array { $d = []; foreach ($data as $key => $value) { - if (\is_string($key)) { - $key = \htmlspecialchars($key, ENT_QUOTES, $charset); + if (is_string($key)) { + $key = htmlspecialchars($key, ENT_QUOTES, $charset); } - if (\is_string($value)) { - $value = \htmlspecialchars($value, ENT_QUOTES, $charset); - } elseif (\is_array($value)) { + if (is_string($value)) { + $value = htmlspecialchars($value, ENT_QUOTES, $charset); + } elseif (is_array($value)) { $value = static::encodeArray($value); } @@ -74,14 +93,16 @@ public static function encodeArray($data, $charset = 'utf-8'): array * htmlentities() <--> html_entity_decode() — 将特殊的 HTML 实体转换回普通字符 * htmlspecialchars() <--> htmlspecialchars_decode() — 将特殊的 HTML 实体转换回普通字符 * ENT_COMPAT ENT_QUOTES ENT_NOQUOTES ENT_HTML401 ENT_XML1 ENT_XHTML ENT_HTML5 + * * @param $data * @param int $type * @param string $encoding + * * @return array|mixed|string */ public static function escape($data, int $type = 0, $encoding = 'UTF-8') { - if (\is_array($data)) { + if (is_array($data)) { foreach ($data as $k => $v) { $data[$k] = self::escape($data, $type, $encoding); } @@ -91,14 +112,14 @@ public static function escape($data, int $type = 0, $encoding = 'UTF-8') // 默认使用 htmlspecialchars() if (!$type) { - $data = \htmlspecialchars($data, \ENT_QUOTES, $encoding); + $data = htmlspecialchars($data, ENT_QUOTES, $encoding); } else { - $data = \htmlentities($data, \ENT_QUOTES, $encoding); + $data = htmlentities($data, ENT_QUOTES, $encoding); } //如‘志’这样的16进制的html字符,为了防止这样的字符被错误转译,使用正则进行匹配,把这样的字符又转换回来。 - if (\strpos($data, '&#')) { - $data = \preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $data); + if (strpos($data, '&#')) { + $data = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $data); } return $data; @@ -106,22 +127,24 @@ public static function escape($data, int $type = 0, $encoding = 'UTF-8') /** * 去掉html转义 + * * @param $data * @param int $type * @param string $encoding + * * @return array|string */ public static function unescap($data, $type = 0, $encoding = 'UTF-8') { - if (\is_array($data)) { + if (is_array($data)) { foreach ($data as $k => $v) { $data[$k] = self::unescap($data, $type, $encoding); } } elseif (!$type) {//默认使用 htmlspecialchars_decode() - $data = \htmlspecialchars_decode($data, \ENT_QUOTES); + $data = htmlspecialchars_decode($data, ENT_QUOTES); } else { - $data = \html_entity_decode($data, \ENT_QUOTES, $encoding); + $data = html_entity_decode($data, ENT_QUOTES, $encoding); } return $data; @@ -129,7 +152,9 @@ public static function unescap($data, $type = 0, $encoding = 'UTF-8') /** * Strip img-tags from string - * @param string $string Sting to be cleaned. + * + * @param string $string Sting to be cleaned. + * * @return string Cleaned string */ public static function stripImages(string $string): string @@ -139,37 +164,44 @@ public static function stripImages(string $string): string /** * Strip iframe-tags from string - * @param string $string Sting to be cleaned. + * + * @param string $string Sting to be cleaned. + * * @return string Cleaned string */ public static function stripIframes(string $string): string { - return \preg_replace('#(<[/]?iframe.*>)#U', '', $string); + return preg_replace('#(<[/]?iframe.*>)#U', '', $string); } /** * stripScript + * * @param string $string + * * @return string */ public static function stripScript(string $string): string { - return \preg_replace('/]*>.*?/si', '', $string); + return preg_replace('/]*>.*?/si', '', $string); } /** * stripStyle + * * @param string $string + * * @return string */ public static function stripStyle(string $string): string { - return \preg_replace('/]*>.*?/si', '', $string); + return preg_replace('/]*>.*?/si', '', $string); } /** * @param string $html * @param bool|true $onlySrc + * * @return array */ public static function matchImages(string $html, bool $onlySrc = true): array @@ -177,12 +209,12 @@ public static function matchImages(string $html, bool $onlySrc = true): array // $preg = '//i'; $preg = '//i'; - if (!\preg_match_all($preg, trim($html), $images)) { + if (!preg_match_all($preg, trim($html), $images)) { return []; } if ($onlySrc) { - return \array_key_exists(1, $images) ? $images[1] : []; + return array_key_exists(1, $images) ? $images[1] : []; } return $images; @@ -190,6 +222,7 @@ public static function matchImages(string $html, bool $onlySrc = true): array /** * @param string $html + * * @return string */ public static function minify(string $html): string @@ -203,6 +236,6 @@ public static function minify(string $html): string ]; $replace = [' ', ' ', '>', '<', '\\1']; - return \preg_replace($search, $replace, $html); + return preg_replace($search, $replace, $html); } } diff --git a/libs/str-utils/src/Json.php b/libs/str-utils/src/Json.php index 9bfc1fc..fccc524 100644 --- a/libs/str-utils/src/Json.php +++ b/libs/str-utils/src/Json.php @@ -10,6 +10,7 @@ /** * Class Json + * * @package Toolkit\StrUtil */ final class Json extends JsonHelper diff --git a/libs/str-utils/src/JsonHelper.php b/libs/str-utils/src/JsonHelper.php index 9102e52..934a1f8 100644 --- a/libs/str-utils/src/JsonHelper.php +++ b/libs/str-utils/src/JsonHelper.php @@ -8,8 +8,28 @@ namespace Toolkit\StrUtil; +use InvalidArgumentException; +use RuntimeException; +use stdClass; +use function array_merge; +use function basename; +use function dirname; +use function file_exists; +use function file_get_contents; +use function file_put_contents; +use function is_file; +use function is_string; +use function json_decode; +use function json_encode; +use function preg_replace; +use function trim; +use const JSON_PRETTY_PRINT; +use const JSON_UNESCAPED_SLASHES; +use const JSON_UNESCAPED_UNICODE; + /** * Class JsonHelper + * * @package Toolkit\StrUtil */ class JsonHelper @@ -17,30 +37,34 @@ class JsonHelper /** * @param mixed $data * @param int $flags + * * @return false|string */ public static function prettyJSON( $data, - int $flags = \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES + int $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) { - return \json_encode($data, $flags); + return json_encode($data, $flags); } /** * encode data to json + * * @param $data + * * @return string */ public static function encode($data): string { - return \json_encode($data, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE); + return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } /** * @param string $data * @param bool $toArray - * @return array|mixed|null|\stdClass|string - * @throws \InvalidArgumentException + * + * @return array|mixed|null|stdClass|string + * @throws InvalidArgumentException */ public static function parse(string $data, bool $toArray = true) { @@ -54,16 +78,17 @@ public static function parse(string $data, bool $toArray = true) /** * @param string $file * @param bool|true $toArray + * * @return mixed|null|string - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public static function parseFile(string $file, $toArray = true) { - if (!\is_file($file)) { - throw new \InvalidArgumentException("File not found or does not exist resources: {$file}"); + if (!is_file($file)) { + throw new InvalidArgumentException("File not found or does not exist resources: {$file}"); } - $string = \file_get_contents($file); + $string = file_get_contents($file); return self::parseString($string, $toArray); } @@ -71,15 +96,16 @@ public static function parseFile(string $file, $toArray = true) /** * @param string $string * @param bool $toArray - * @return array|mixed|\stdClass + * + * @return array|mixed|stdClass */ public static function parseString(string $string, bool $toArray = true) { if (!$string) { - return $toArray ? [] : new \stdClass(); + return $toArray ? [] : new stdClass(); } - $string = (string)\preg_replace([ + $string = (string)preg_replace([ // 去掉所有多行注释/* .... */ '/\/\*.*?\*\/\s*/is', // 去掉所有单行注释//.... @@ -89,36 +115,37 @@ public static function parseString(string $string, bool $toArray = true) ], ['', '', ' '], trim($string)); // json_last_error() === JSON_ERROR_NONE - return \json_decode($string, $toArray); + return json_decode($string, $toArray); } /** - * @param string $input 文件 或 数据 - * @param bool $output 是否输出到文件, 默认返回格式化的数据 + * @param string $input 文件 或 数据 + * @param bool $output 是否输出到文件, 默认返回格式化的数据 * @param array $options 当 $output=true,此选项有效 - * $options = [ - * 'type' => 'min' // 输出数据类型 min 压缩过的 raw 正常的 - * 'file' => 'xx.json' // 输出文件路径;仅是文件名,则会取输入路径 - * ] + * $options = [ + * 'type' => 'min' // 输出数据类型 min 压缩过的 raw 正常的 + * 'file' => 'xx.json' // 输出文件路径;仅是文件名,则会取输入路径 + * ] + * * @return string | bool */ public static function format($input, $output = false, array $options = []) { - if (!\is_string($input)) { + if (!is_string($input)) { return false; } - $data = \trim($input); + $data = trim($input); - if (\file_exists($input)) { - $data = \file_get_contents($input); + if (file_exists($input)) { + $data = file_get_contents($input); } if (!$data) { return false; } - $data = \preg_replace([ + $data = preg_replace([ // 去掉所有多行注释/* .... */ '/\/\*.*?\*\/\s*/is', // 去掉所有单行注释//.... @@ -132,11 +159,11 @@ public static function format($input, $output = false, array $options = []) } $default = ['type' => 'min']; - $options = \array_merge($default, $options); + $options = array_merge($default, $options); - if (\file_exists($input) && (empty($options['file']) || !\is_file($options['file']))) { - $dir = \dirname($input); - $name = \basename($input, '.json'); + if (file_exists($input) && (empty($options['file']) || !is_file($options['file']))) { + $dir = dirname($input); + $name = basename($input, '.json'); $file = $dir . '/' . $name . '.' . $options['type'] . '.json'; // save to options $options['file'] = $file; @@ -150,26 +177,27 @@ public static function format($input, $output = false, array $options = []) * @param string $data * @param string $output * @param array $options + * * @return bool|int */ public static function saveAs(string $data, string $output, array $options = []) { $default = ['type' => 'min', 'file' => '']; $options = array_merge($default, $options); - $saveDir = \dirname($output); + $saveDir = dirname($output); - if (!\file_exists($saveDir)) { - throw new \RuntimeException('设置的json文件输出' . $saveDir . '目录不存在!'); + if (!file_exists($saveDir)) { + throw new RuntimeException('设置的json文件输出' . $saveDir . '目录不存在!'); } - $name = \basename($output, '.json'); + $name = basename($output, '.json'); $file = $saveDir . '/' . $name . '.' . $options['type'] . '.json'; // 去掉空白 if ($options['type '] === 'min') { - $data = \preg_replace('/(?!\w)\s*?(?!\w)/i', '', $data); + $data = preg_replace('/(?!\w)\s*?(?!\w)/i', '', $data); } - return \file_put_contents($file, $data); + return file_put_contents($file, $data); } } diff --git a/libs/str-utils/src/Str.php b/libs/str-utils/src/Str.php index c350135..e24b930 100644 --- a/libs/str-utils/src/Str.php +++ b/libs/str-utils/src/Str.php @@ -10,6 +10,7 @@ /** * Class Str alias of the StringHelper + * * @package Toolkit\StrUtil */ final class Str extends StringHelper diff --git a/libs/str-utils/src/StrBuffer.php b/libs/str-utils/src/StrBuffer.php index 9067aea..e2b4f47 100644 --- a/libs/str-utils/src/StrBuffer.php +++ b/libs/str-utils/src/StrBuffer.php @@ -10,6 +10,7 @@ /** * Class StrBuffer + * * @package Toolkit\StrUtil */ final class StrBuffer diff --git a/libs/str-utils/src/StringHelper.php b/libs/str-utils/src/StringHelper.php index 50b4498..27d7959 100644 --- a/libs/str-utils/src/StringHelper.php +++ b/libs/str-utils/src/StringHelper.php @@ -2,8 +2,72 @@ namespace Toolkit\StrUtil; +use Exception; +use Inhere\Exceptions\InvalidArgumentException; +use function array_map; +use function array_merge; +use function array_shift; +use function array_slice; +use function array_values; +use function base64_encode; +use function count; +use function explode; +use function func_get_arg; +use function func_num_args; +use function function_exists; +use function hash; +use function hex2bin; +use function html_entity_decode; +use function implode; +use function in_array; +use function is_array; +use function is_int; +use function is_string; +use function lcfirst; +use function mb_convert_case; +use function mb_convert_encoding; +use function mb_convert_variables; +use function mb_detect_encoding; +use function mb_internal_encoding; +use function mb_strlen; +use function mb_strpos; +use function mb_strrpos; +use function mb_strtolower; +use function mb_strtoupper; +use function mb_strwidth; +use function mb_substr; +use function preg_match; +use function preg_match_all; +use function preg_replace; +use function preg_replace_callback; +use function preg_split; +use function random_token; +use function str_pad; +use function str_replace; +use function str_split; +use function strip_tags; +use function stripos; +use function strlen; +use function strpos; +use function strrpos; +use function strtolower; +use function strtoupper; +use function substr; +use function trim; +use function ucfirst; +use function ucwords; +use function uniqid; +use function utf8_decode; +use function utf8_encode; +use const ENT_COMPAT; +use const MB_CASE_TITLE; +use const PREG_SPLIT_NO_EMPTY; +use const STR_PAD_LEFT; +use const STR_PAD_RIGHT; + /** * Class StringHelper + * * @package Toolkit\StrUtil */ abstract class StringHelper @@ -16,6 +80,7 @@ abstract class StringHelper * @param string $string * @param string $prefix * @param string $suffix + * * @return string */ public static function optional(string $string, string $prefix = ' ', string $suffix = ''): string @@ -30,6 +95,7 @@ public static function optional(string $string, string $prefix = ' ', string $su /** * @param string $string * @param string|array $needle + * * @return bool */ public static function contains(string $string, $needle): bool @@ -40,17 +106,18 @@ public static function contains(string $string, $needle): bool /** * @param string $string * @param string|array $needle + * * @return bool */ public static function has(string $string, $needle): bool { - if (\is_string($needle)) { - return \stripos($string, $needle) !== false; + if (is_string($needle)) { + return stripos($string, $needle) !== false; } - if (\is_array($needle)) { + if (is_array($needle)) { foreach ((array)$needle as $item) { - if (\stripos($string, $item) !== false) { + if (stripos($string, $item) !== false) { return true; } } @@ -64,13 +131,12 @@ public static function has(string $string, $needle): bool * @param $find * @param int $offset * @param string $encoding + * * @return bool|int */ public static function strpos(string $str, string $find, int $offset = 0, string $encoding = 'UTF-8') { - return \function_exists('mb_strpos') ? - \mb_strpos($str, $find, $offset, $encoding) : - \strpos($str, $find, $offset); + return function_exists('mb_strpos') ? mb_strpos($str, $find, $offset, $encoding) : strpos($str, $find, $offset); } /** @@ -78,20 +144,23 @@ public static function strpos(string $str, string $find, int $offset = 0, string * @param string $find * @param int $offset * @param string $encoding + * * @return bool|int */ public static function strrpos(string $str, string $find, int $offset = 0, string $encoding = 'utf-8') { - return \function_exists('mb_strrpos') ? - \mb_strrpos($str, $find, $offset, $encoding) : - \strrpos($str, $find, $offset); + return function_exists('mb_strrpos') ? mb_strrpos($str, $find, $offset, $encoding) : + strrpos($str, $find, $offset); } /** * 使用正则验证数据 + * * @access public + * * @param string $value 要验证的数据 - * @param string $rule 验证规则 require email url currency number integer english + * @param string $rule 验证规则 require email url currency number integer english + * * @return boolean */ public static function regexMatch(string $value, string $rule): bool @@ -110,15 +179,15 @@ public static function regexMatch(string $value, string $rule): bool 'english' => '/^[A-Za-z]+$/', ]; - $value = \trim($value); - $name = \strtolower($rule); + $value = trim($value); + $name = strtolower($rule); // 检查是否有内置的正则表达式 if (isset($validate[$name])) { $rule = $validate[$name]; } - return \preg_match($rule, $value) === 1; + return preg_match($rule, $value) === 1; } //////////////////////////////////////////////////////////////////////// @@ -127,27 +196,30 @@ public static function regexMatch(string $value, string $rule): bool /** * from Symfony + * * @param string $string + * * @return int */ public static function len(string $string): int { - if (false === $encoding = \mb_detect_encoding($string, null, true)) { - return \strlen($string); + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return strlen($string); } - return \mb_strwidth($string, $encoding); + return mb_strwidth($string, $encoding); } public static function strlen(string $str, string $encoding = 'UTF-8'): int { - $str = \html_entity_decode($str, \ENT_COMPAT, 'UTF-8'); + $str = html_entity_decode($str, ENT_COMPAT, 'UTF-8'); - return \function_exists('mb_strlen') ? \mb_strlen($str, $encoding) : \strlen($str); + return function_exists('mb_strlen') ? mb_strlen($str, $encoding) : strlen($str); } /** * @param string $string + * * @return int */ public static function utf8Len(string $string): int @@ -155,12 +227,14 @@ public static function utf8Len(string $string): int // strlen: one chinese is 3 char. // mb_strlen: one chinese is 1 char. // mb_strwidth: one chinese is 2 char. - return \mb_strlen($string, 'utf-8'); + return mb_strlen($string, 'utf-8'); } /** * 计算字符长度 - * @param string $str + * + * @param string $str + * * @return int */ public static function length(string $str): int @@ -169,21 +243,23 @@ public static function length(string $str): int return 0; } - if (\function_exists('mb_strlen')) { - return \mb_strlen($str, 'utf-8'); + if (function_exists('mb_strlen')) { + return mb_strlen($str, 'utf-8'); } - \preg_match_all('/./u', $str, $arr); + preg_match_all('/./u', $str, $arr); - return \count($arr[0]); + return count($arr[0]); } /** - * @from web + * @from web * 可以统计中文字符串长度的函数 + * * @param string $str 要计算长度的字符串 - * @internal param bool $type 计算长度类型,0(默认)表示一个中文算一个字符,1表示一个中文算两个字符 + * * @return int + * @internal param bool $type 计算长度类型,0(默认)表示一个中文算一个字符,1表示一个中文算两个字符 */ public static function absLen(string $str): int { @@ -191,17 +267,17 @@ public static function absLen(string $str): int return 0; } - if (\function_exists('mb_strwidth')) { - return \mb_strwidth($str, 'utf-8'); + if (function_exists('mb_strwidth')) { + return mb_strwidth($str, 'utf-8'); } - if (\function_exists('mb_strlen')) { - return \mb_strlen($str, 'utf-8'); + if (function_exists('mb_strlen')) { + return mb_strlen($str, 'utf-8'); } - \preg_match_all('/./u', $str, $ar); + preg_match_all('/./u', $str, $ar); - return \count($ar[0]); + return count($ar[0]); } //////////////////////////////////////////////////////////// @@ -210,22 +286,24 @@ public static function absLen(string $str): int /** * ********************** 生成一定长度的随机字符串函数 ********************** - * @param int $length - 随机字符串长度 - * @param array|string $param - - * @internal param string $chars + * + * @param int $length - 随机字符串长度 + * @param array|string $param - + * * @return string - * @throws \Exception + * @throws Exception + * @internal param string $chars */ public static function random(int $length, array $param = []): string { - $param = \array_merge([ + $param = array_merge([ 'prefix' => '', 'suffix' => '', 'chars' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' ], $param); $chars = $param['chars']; - $max = \strlen($chars) - 1; //strlen($chars) 计算字符串的长度 + $max = strlen($chars) - 1; //strlen($chars) 计算字符串的长度 $str = ''; for ($i = 0; $i < $length; $i++) { @@ -237,28 +315,26 @@ public static function random(int $length, array $param = []): string /** * @param int $length + * * @return string */ public static function genSalt(int $length = 32): string { - return \substr( - \str_replace('+', '.', \base64_encode(\hex2bin(\random_token($length)))), - 0, - 44 - ); + return substr(str_replace('+', '.', base64_encode(hex2bin(random_token($length)))), 0, 44); } /** * @param int $length + * * @return bool|string */ public static function genUid(int $length = 7): string { - if (!\is_int($length) || $length > 32 || $length < 1) { + if (!is_int($length) || $length > 32 || $length < 1) { $length = 7; } - return \substr(\hash('md5', \uniqid('', true)), 0, $length); + return substr(hash('md5', uniqid('', true)), 0, $length); } /** @@ -266,30 +342,33 @@ public static function genUid(int $length = 7): string * @param int $padLen * @param string $padStr * @param int $padType + * * @return string */ - public static function pad(string $string, int $padLen, string $padStr = ' ', int $padType = \STR_PAD_RIGHT): string + public static function pad(string $string, int $padLen, string $padStr = ' ', int $padType = STR_PAD_RIGHT): string { - return $padLen > 0 ? \str_pad($string, $padLen, $padStr, $padType) : $string; + return $padLen > 0 ? str_pad($string, $padLen, $padStr, $padType) : $string; } public static function padLeft(string $string, int $padLen, string $padStr = ' '): string { - return $padLen > 0 ? \str_pad($string, $padLen, $padStr, \STR_PAD_LEFT) : $string; + return $padLen > 0 ? str_pad($string, $padLen, $padStr, STR_PAD_LEFT) : $string; } public static function padRight(string $string, int $padLen, string $padStr = ' '): string { - return $padLen > 0 ? \str_pad($string, $padLen, $padStr) : $string; + return $padLen > 0 ? str_pad($string, $padLen, $padStr) : $string; } /** * gen UUID + * * @param int $version * @param null $node * @param null $ns + * * @return UUID - * @throws \Inhere\Exceptions\InvalidArgumentException + * @throws InvalidArgumentException */ // public static function genUUID($version = 1, $node = null, $ns = null) // { @@ -302,12 +381,14 @@ public static function padRight(string $string, int $padLen, string $padStr = ' /** * Convert \n and \r\n and \r to
+ * * @param string $str String to transform + * * @return string New string */ public static function nl2br(string $str): string { - return \str_replace(["\r\n", "\r", "\n"], '
', $str); + return str_replace(["\r\n", "\r", "\n"], '
', $str); } public static function lower(string $str): string @@ -317,11 +398,12 @@ public static function lower(string $str): string /** * @param string $str + * * @return bool|string */ public static function strtolower(string $str): string { - return \function_exists('mb_strtolower') ? \mb_strtolower($str, 'utf-8') : \strtolower($str); + return function_exists('mb_strtolower') ? mb_strtolower($str, 'utf-8') : strtolower($str); } public static function upper(string $str): string @@ -331,19 +413,21 @@ public static function upper(string $str): string /** * @param $str + * * @return bool|string */ public static function strtoupper(string $str) { - if (!\is_string($str)) { + if (!is_string($str)) { return $str; } - return \function_exists('mb_strtoupper') ? \mb_strtoupper($str, 'utf-8') : \strtoupper($str); + return function_exists('mb_strtoupper') ? mb_strtoupper($str, 'utf-8') : strtoupper($str); } /** * @param $str + * * @return string */ public static function ucfirst(string $str): string @@ -353,18 +437,19 @@ public static function ucfirst(string $str): string /** * @param $str + * * @return string */ public static function ucwords(string $str): string { - return \function_exists('mb_convert_case') ? - \mb_convert_case($str, \MB_CASE_TITLE) : - \ucwords(self::strtolower($str)); + return function_exists('mb_convert_case') ? mb_convert_case($str, MB_CASE_TITLE) : + ucwords(self::strtolower($str)); } /** * @param string $str * @param bool $upperFirstChar + * * @return mixed */ public static function camel(string $str, bool $upperFirstChar = false): string @@ -375,6 +460,7 @@ public static function camel(string $str, bool $upperFirstChar = false): string /** * @param string $str * @param bool $upperFirstChar + * * @return mixed */ public static function toCamel(string $str, bool $upperFirstChar = false): string @@ -384,27 +470,31 @@ public static function toCamel(string $str, bool $upperFirstChar = false): strin /** * to camel + * * @param string $name * @param bool $upperFirst + * * @return string */ public static function camelCase(string $name, bool $upperFirst = false): string { - $name = \trim($name, '-_'); + $name = trim($name, '-_'); // convert 'first-second' to 'firstSecond' - if (\strpos($name, '-')) { - $name = \ucwords(\str_replace('-', ' ', $name)); - $name = \str_replace(' ', '', \lcfirst($name)); + if (strpos($name, '-')) { + $name = ucwords(str_replace('-', ' ', $name)); + $name = str_replace(' ', '', lcfirst($name)); } - return $upperFirst ? \ucfirst($name) : $name; + return $upperFirst ? ucfirst($name) : $name; } /** * Translates a string with underscores into camel case (e.g. first_name -> firstName) - * @param string $str - * @param bool $upperFirst + * + * @param string $str + * @param bool $upperFirst + * * @return mixed */ public static function toCamelCase(string $str, bool $upperFirst = false): string @@ -415,8 +505,8 @@ public static function toCamelCase(string $str, bool $upperFirst = false): strin $str = self::ucfirst($str); } - return \preg_replace_callback('/_+([a-z])/', function ($c) { - return \strtoupper($c[1]); + return preg_replace_callback('/_+([a-z])/', function ($c) { + return strtoupper($c[1]); }, $str); } @@ -432,47 +522,51 @@ public static function toSnake(string $str, string $sep = '_'): string /** * Transform a CamelCase string to underscore_case string + * * @param string $str * @param string $sep + * * @return string */ public static function toSnakeCase(string $str, string $sep = '_'): string { // 'CMSCategories' => 'cms_categories' // 'RangePrice' => 'range_price' - return self::lower(\trim(\preg_replace('/([A-Z][a-z])/', $sep . '$1', $str), $sep)); + return self::lower(trim(preg_replace('/([A-Z][a-z])/', $sep . '$1', $str), $sep)); } /** * 驼峰式 <=> 下划线式 - * @param string $str [description] - * @param bool $toCamelCase - * true : 驼峰式 => 下划线式 - * false : 驼峰式 <= 下划线式 + * + * @param string $str [description] + * @param bool $toCamelCase + * true : 驼峰式 => 下划线式 + * false : 驼峰式 <= 下划线式 + * * @return string */ public static function nameChange(string $str, bool $toCamelCase = true): string { - $str = \trim($str); + $str = trim($str); // 默认 :下划线式 =>驼峰式 if ($toCamelCase) { - if (\strpos($str, '_') === false) { + if (strpos($str, '_') === false) { return $str; } - $arr_char = \explode('_', \strtolower($str)); - $newString = \array_shift($arr_char); + $arr_char = explode('_', strtolower($str)); + $newString = array_shift($arr_char); foreach ($arr_char as $val) { - $newString .= \ucfirst($val); + $newString .= ucfirst($val); } return $newString; } // 驼峰式 => 下划线式 - return \strtolower(\preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $str)); + return strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $str)); } //////////////////////////////////////////////////////////////////////// @@ -481,33 +575,35 @@ public static function nameChange(string $str, bool $toCamelCase = true): string /** * var_dump(str2array('34,56,678, 678, 89, ')); + * * @param string $str * @param string $sep + * * @return array */ public static function str2array(string $str, string $sep = ','): array { - $str = \trim($str, "$sep "); + $str = trim($str, "$sep "); if (!$str) { return []; } - return \preg_split("/\s*$sep\s*/", $str, -1, \PREG_SPLIT_NO_EMPTY); + return preg_split("/\s*$sep\s*/", $str, -1, PREG_SPLIT_NO_EMPTY); } public static function toArray(string $string, string $delimiter = ',', int $limit = 0): array { - $string = \trim($string, "$delimiter "); + $string = trim($string, "$delimiter "); if ($string === '') { return []; } $values = []; - $rawList = $limit < 1 ? \explode($delimiter, $string) : \explode($delimiter, $string, $limit); + $rawList = $limit < 1 ? explode($delimiter, $string) : explode($delimiter, $string, $limit); foreach ($rawList as $val) { - if (($val = \trim($val)) !== '') { + if (($val = trim($val)) !== '') { $values[] = $val; } } @@ -524,28 +620,30 @@ public static function explode(string $str, string $separator = '.', int $limit * @param string $string * @param string $delimiter * @param int $limit + * * @return array */ public static function split2Array(string $string, string $delimiter = ',', int $limit = 0): array { - $string = \trim($string, "$delimiter "); + $string = trim($string, "$delimiter "); - if (!\strpos($string, $delimiter)) { + if (!strpos($string, $delimiter)) { return [$string]; } if ($limit < 1) { - $list = \explode($delimiter, $string); + $list = explode($delimiter, $string); } else { - $list = \explode($delimiter, $string, $limit); + $list = explode($delimiter, $string, $limit); } - return \array_values(array_filter(\array_map('trim', $list), 'strlen')); + return array_values(array_filter(array_map('trim', $list), 'strlen')); } /** * @param string $string * @param int $width + * * @return array */ public static function splitByWidth(string $string, int $width): array @@ -553,31 +651,31 @@ public static function splitByWidth(string $string, int $width): array // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly. // additionally, array_slice() is not enough as some character has doubled width. // we need a function to split string not by character count but by string width - if (false === $encoding = \mb_detect_encoding($string, null, true)) { - return \str_split($string, $width); + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return str_split($string, $width); } - $utf8String = \mb_convert_encoding($string, 'utf8', $encoding); + $utf8String = mb_convert_encoding($string, 'utf8', $encoding); $lines = []; $line = ''; - foreach (\preg_split('//u', $utf8String) as $char) { + foreach (preg_split('//u', $utf8String) as $char) { // test if $char could be appended to current line - if (\mb_strwidth($line . $char, 'utf8') <= $width) { + if (mb_strwidth($line . $char, 'utf8') <= $width) { $line .= $char; continue; } // if not, push current line to array and make new line - $lines[] = \str_pad($line, $width); + $lines[] = str_pad($line, $width); $line = $char; } if ('' !== $line) { - $lines[] = \count($lines) ? \str_pad($line, $width) : $line; + $lines[] = count($lines) ? str_pad($line, $width) : $line; } - \mb_convert_variables($encoding, 'utf8', $lines); + mb_convert_variables($encoding, 'utf8', $lines); return $lines; } @@ -591,23 +689,26 @@ public static function splitByWidth(string $string, int $width): array * @param int $start * @param int|null $length * @param string $encoding + * * @return bool|string */ public static function substr(string $str, int $start, int $length = null, string $encoding = 'utf-8') { - if (\function_exists('mb_substr')) { - return \mb_substr($str, $start, ($length === null ? self::strlen($str) : (int)$length), $encoding); + if (function_exists('mb_substr')) { + return mb_substr($str, $start, ($length === null ? self::strlen($str) : (int)$length), $encoding); } - return \substr($str, $start, ($length === null ? self::strlen($str) : (int)$length)); + return substr($str, $start, ($length === null ? self::strlen($str) : (int)$length)); } /** * @from web * utf-8编码下截取中文字符串,参数可以参照substr函数 - * @param string $str 要进行截取的字符串 + * + * @param string $str 要进行截取的字符串 * @param int $start 要进行截取的开始位置,负数为反向截取 - * @param int $end 要进行截取的长度 + * @param int $end 要进行截取的长度 + * * @return string */ public static function utf8SubStr(string $str, int $start = 0, int $end = null): string @@ -616,61 +717,63 @@ public static function utf8SubStr(string $str, int $start = 0, int $end = null): return false; } - if (\function_exists('mb_substr')) { - if (\func_num_args() >= 3) { - $end = \func_get_arg(2); + if (function_exists('mb_substr')) { + if (func_num_args() >= 3) { + $end = func_get_arg(2); - return \mb_substr($str, $start, $end, 'utf-8'); + return mb_substr($str, $start, $end, 'utf-8'); } - \mb_internal_encoding('UTF-8'); + mb_internal_encoding('UTF-8'); - return \mb_substr($str, $start); + return mb_substr($str, $start); } $null = ''; - \preg_match_all('/./u', $str, $ar); + preg_match_all('/./u', $str, $ar); - if (\func_num_args() >= 3) { - $end = \func_get_arg(2); - return \implode($null, \array_slice($ar[0], $start, $end)); + if (func_num_args() >= 3) { + $end = func_get_arg(2); + return implode($null, array_slice($ar[0], $start, $end)); } - return \implode($null, \array_slice($ar[0], $start)); + return implode($null, array_slice($ar[0], $start)); } /** * @from web * 中文截取,支持gb2312,gbk,utf-8,big5 * - * @param string $str 要截取的字串 - * @param int $start 截取起始位置 - * @param int $length 截取长度 + * + * @param string $str 要截取的字串 + * @param int $start 截取起始位置 + * @param int $length 截取长度 * @param string $charset utf-8|gb2312|gbk|big5 编码 - * @param bool $suffix 是否加尾缀 + * @param bool $suffix 是否加尾缀 + * * @return string */ public static function zhSubStr($str, $start = 0, $length = 0, $charset = 'utf-8', $suffix = true): string { - if (\function_exists('mb_substr')) { - if (\mb_strlen($str, $charset) <= $length) { + if (function_exists('mb_substr')) { + if (mb_strlen($str, $charset) <= $length) { return $str; } - $slice = \mb_substr($str, $start, $length, $charset); + $slice = mb_substr($str, $start, $length, $charset); } else { $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; - \preg_match_all($re[$charset], $str, $match); - if (\count($match[0]) <= $length) { + preg_match_all($re[$charset], $str, $match); + if (count($match[0]) <= $length) { return $str; } - $slice = \implode('', \array_slice($match[0], $start, $length)); + $slice = implode('', array_slice($match[0], $start, $length)); } return (bool)$suffix ? $slice . '…' : $slice; @@ -678,9 +781,11 @@ public static function zhSubStr($str, $start = 0, $length = 0, $charset = 'utf-8 /** * Truncate strings + * * @param string $str * @param int $maxLength Max length - * @param string $suffix Suffix optional + * @param string $suffix Suffix optional + * * @return string $str truncated */ /* CAUTION : Use it only on module hookEvents. @@ -691,16 +796,18 @@ public static function truncate(string $str, $maxLength, $suffix = '...'): strin return $str; } - $str = \utf8_decode($str); + $str = utf8_decode($str); - return \utf8_encode(\substr($str, 0, $maxLength - self::strlen($suffix)) . $suffix); + return utf8_encode(substr($str, 0, $maxLength - self::strlen($suffix)) . $suffix); } /** * 字符截断输出 + * * @param string $str * @param int $start * @param null|int $length + * * @return string */ public static function truncate2(string $str, int $start, int $length = null): string @@ -710,14 +817,14 @@ public static function truncate2(string $str, int $start, int $length = null): s $start = 0; } - if (\strlen($str) <= $length) { + if (strlen($str) <= $length) { return $str; } - if (\function_exists('mb_substr')) { - $str = \mb_substr(\strip_tags($str), $start, $length, 'utf-8'); + if (function_exists('mb_substr')) { + $str = mb_substr(strip_tags($str), $start, $length, 'utf-8'); } else { - $str = \substr($str, $start, $length) . '...'; + $str = substr($str, $start, $length) . '...'; } return $str; @@ -725,9 +832,11 @@ public static function truncate2(string $str, int $start, int $length = null): s /** * Copied from CakePHP String utility file + * * @param string $text * @param int $length * @param array $options + * * @return bool|string */ public static function truncate3(string $text, int $length = 120, array $options = []) @@ -749,11 +858,11 @@ public static function truncate3(string $text, int $length = 120, array $options * @var bool $html */ if ($html) { - if (self::strlen(\preg_replace('/<.*?>/', '', $text)) <= $length) { + if (self::strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } - $total_length = self::strlen(\strip_tags($ellipsis)); + $total_length = self::strlen(strip_tags($ellipsis)); $open_tags = $tags = []; $truncate = ''; preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER); @@ -778,7 +887,8 @@ public static function truncate3(string $text, int $length = 120, array $options $entities_length = 0; if (preg_match_all('/&[0-9a-z]{2,8};|&#[\d]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, - PREG_OFFSET_CAPTURE)) { + PREG_OFFSET_CAPTURE) + ) { foreach ((array)$entities[0] as $entity) { if ($entity[1] + 1 - $entities_length <= $left) { $left--; @@ -830,7 +940,7 @@ public static function truncate3(string $text, int $length = 120, array $options if (!empty($dropped_tags)) { if (!empty($open_tags)) { foreach ($dropped_tags as $closing_tag) { - if (!\in_array($closing_tag[1], $open_tags, true)) { + if (!in_array($closing_tag[1], $open_tags, true)) { array_unshift($open_tags, $closing_tag[1]); } } @@ -862,41 +972,43 @@ public static function truncate3(string $text, int $length = 120, array $options /** * [format description] + * * @param $str * @param array $replaceParams 用于 str_replace('search','replace',$str ) + * @param array $pregParams 用于 preg_replace('pattern','replace',$str) + * + * @return string [type] [description] * @example - * $replaceParams = [ + * $pregParams = [ + * 'xx', //'pattern' + * 'yy', //'replace' + * ] + * * $pregParams = [ + * ['xx','xx2'], //'pattern' + * ['yy','yy2'], //'replace' + * ] + * @example + * $replaceParams = [ * 'xx', //'search' * 'yy', //'replace' - * ] - * $replaceParams = [ + * ] + * $replaceParams = [ * ['xx','xx2'], //'search' * ['yy','yy2'], //'replace' - * ] - * @param array $pregParams 用于 preg_replace('pattern','replace',$str) - * @example - * $pregParams = [ - * 'xx', //'pattern' - * 'yy', //'replace' - * ] - * * $pregParams = [ - * ['xx','xx2'], //'pattern' - * ['yy','yy2'], //'replace' - * ] - * @return string [type] [description] + * ] */ public static function format($str, array $replaceParams = [], array $pregParams = []): string { - if (!\is_string($str) || !$str || (!$replaceParams && !$pregParams)) { + if (!is_string($str) || !$str || (!$replaceParams && !$pregParams)) { return $str; } - if ($replaceParams && \count($replaceParams) === 2) { + if ($replaceParams && count($replaceParams) === 2) { [$search, $replace] = $replaceParams; $str = str_replace($search, $replace, $str); } - if ($pregParams && \count($pregParams) === 2) { + if ($pregParams && count($pregParams) === 2) { [$pattern, $replace] = $pregParams; $str = preg_replace($pattern, $replace, $str); } @@ -906,7 +1018,9 @@ public static function format($str, array $replaceParams = [], array $pregParams /** * 格式化,用空格分隔各个词组 - * @param string $keyword 字符串 + * + * @param string $keyword 字符串 + * * @return string 格式化后的字符串 */ public static function wordFormat($keyword): string @@ -924,8 +1038,10 @@ public static function wordFormat($keyword): string /** * 缩进格式化内容,去空白/注释 + * * @param $fileName * @param int $type + * * @return mixed */ public static function deleteStripSpace($fileName, $type = 0) diff --git a/libs/str-utils/src/Token.php b/libs/str-utils/src/Token.php index 9773d97..b4de0a7 100644 --- a/libs/str-utils/src/Token.php +++ b/libs/str-utils/src/Token.php @@ -8,6 +8,19 @@ namespace Toolkit\StrUtil; +use RuntimeException; +use function array_merge; +use function crypt; +use function hash_equals; +use function md5; +use function mt_rand; +use function openssl_random_pseudo_bytes; +use function password_hash; +use function password_verify; +use function serialize; +use function sha1; +use function substr; + /** * Usage: * $user = $db->query(['name' => $_POST['name'] ]); @@ -29,6 +42,7 @@ class Token * $2a BLOWFISH算法。 * $5 SHA-256 * $6 SHA-512 + * * @var string */ private static $algo = '$2y'; @@ -36,19 +50,22 @@ class Token /** * cost parameter 就是成本参数 * $10 这是以2为底的对数,指示计算循环迭代的次数(10 => 2^10 = 1024),取值可以从04到31。 + * * @var string */ private static $cost = '$10'; /** * *******生成唯一序列号******* + * * @param $var array || obj + * * @return string */ public static function md5($var): string { //serialize()序列化,串行化 - return \md5(\md5(\serialize($var))); + return md5(md5(serialize($var))); } /** @@ -56,70 +73,78 @@ public static function md5($var): string */ public static function uniqueSalt(): string { - return (string)\substr(\sha1(\mt_rand()), 0, 22); + return (string)substr(sha1(mt_rand()), 0, 22); } /** * @param string $pwd * @param string $algo * @param array $opts + * * @return bool|string */ public static function pwdHash(string $pwd, string $algo, array $opts = []) { - $opts = \array_merge([ + $opts = array_merge([ 'cost' => 9 ], $opts); - return \password_hash($pwd, $algo, $opts); + return password_hash($pwd, $algo, $opts); } /** * @param string $pwd * @param string $hash + * * @return bool|string */ public static function pwdVerify(string $pwd, string $hash) { - return \password_verify($pwd, $hash); + return password_verify($pwd, $hash); } /** * this will be used to generate a hash + * * @param $password + * * @return string */ public static function gen(string $password): string { - return \crypt($password, self::$algo . self::$cost . '$' . self::uniqueSalt()); + return crypt($password, self::$algo . self::$cost . '$' . self::uniqueSalt()); } /** * this will be used to compare a password against a hash + * * @param string $hash * @param string $password the user input + * * @return bool */ public static function verify(string $hash, string $password): bool { - return \hash_equals($hash, \crypt($password, $hash)); + return hash_equals($hash, crypt($password, $hash)); } /** * 2 生成 - * @todo from php.net + * * @param $password * @param int $cost + * * @return string - * @throws \RuntimeException + * @throws RuntimeException + * @todo from php.net */ public static function hash(string $password, int $cost = 11): string { // $bytes = \random_bytes(17); - $bytes = \openssl_random_pseudo_bytes(17, $cStrong); + $bytes = openssl_random_pseudo_bytes(17, $cStrong); if (false === $bytes || false === $cStrong) { - throw new \RuntimeException('exec gen hash error!'); + throw new RuntimeException('exec gen hash error!'); } /* To generate the salt, first generate enough random bytes. Because @@ -151,8 +176,10 @@ public static function hash(string $password, int $cost = 11): string * 2 验证 * Check the password against a hash generated by the generate_hash * function. + * * @param $hash * @param $password + * * @return bool */ public static function verifyHash(string $hash, string $password): bool @@ -165,6 +192,7 @@ public static function verifyHash(string $hash, string $password): bool /** * 生成guid + * * @return string */ public static function GUID(): string @@ -173,11 +201,8 @@ public static function GUID(): string $charId = strtolower(md5(uniqid(mt_rand(), true))); // $hyphen = chr(45); - $uuid = substr($charId, 0, 8) . - substr($charId, 8, 4) . - substr($charId, 12, 4) . - substr($charId, 16, 4) . - substr($charId, 20, 12); + $uuid = substr($charId, 0, 8) . substr($charId, 8, 4) . substr($charId, 12, 4) . substr($charId, 16, + 4) . substr($charId, 20, 12); return $uuid; } diff --git a/libs/str-utils/src/UUID.php b/libs/str-utils/src/UUID.php index a068b97..d0198bd 100644 --- a/libs/str-utils/src/UUID.php +++ b/libs/str-utils/src/UUID.php @@ -8,8 +8,26 @@ namespace Toolkit\StrUtil; +use Exception; +use InvalidArgumentException; +use function base_convert; +use function bin2hex; +use function chr; +use function hexdec; +use function md5; +use function microtime; +use function ord; +use function pack; +use function preg_match; +use function preg_replace; +use function random_bytes; +use function sha1; +use function strlen; +use function substr; + /** * Class UUID + * * @link https://github.com/webpatser/laravel-uuid * * ```php @@ -66,6 +84,7 @@ class UUID /** * Time (in 100ns steps) between the start of the UTC and Unix epochs + * * @var int */ public const INTERVAL = 0x01b21dd213814000; @@ -99,9 +118,10 @@ class UUID * @param int $ver * @param string|null $node * @param string|null $ns + * * @return UUID - * @throws \InvalidArgumentException - * @throws \Exception + * @throws InvalidArgumentException + * @throws Exception */ public static function gen(int $ver = 1, string $node = null, string $ns = null): self { @@ -112,9 +132,10 @@ public static function gen(int $ver = 1, string $node = null, string $ns = null) * @param int $ver * @param string $node * @param string $ns + * * @return UUID - * @throws \InvalidArgumentException - * @throws \Exception + * @throws InvalidArgumentException + * @throws Exception */ public static function generate(int $ver = 1, string $node = null, string $ns = null): self { @@ -124,7 +145,7 @@ public static function generate(int $ver = 1, string $node = null, string $ns = return new static(static::mintTime($node)); case 2: // Version 2 is not supported - throw new \InvalidArgumentException('Version 2 is unsupported.'); + throw new InvalidArgumentException('Version 2 is unsupported.'); case 3: return new static(static::mintName(static::MD5, $node, $ns)); case 4: @@ -132,28 +153,26 @@ public static function generate(int $ver = 1, string $node = null, string $ns = case 5: return new static(static::mintName(static::SHA1, $node, $ns)); default: - throw new \InvalidArgumentException('Selected version is invalid or unsupported.'); + throw new InvalidArgumentException('Selected version is invalid or unsupported.'); } } /** * @param string $uuid - * @throws \InvalidArgumentException + * + * @throws InvalidArgumentException */ protected function __construct(string $uuid) { - if (!empty($uuid) && \strlen($uuid) !== 16) { - throw new \InvalidArgumentException('Input must be a 128-bit integer.'); + if (!empty($uuid) && strlen($uuid) !== 16) { + throw new InvalidArgumentException('Input must be a 128-bit integer.'); } $this->bytes = $uuid; // Optimize the most common use - $this->string = \bin2hex(\substr($uuid, 0, 4)) . '-' . - \bin2hex(\substr($uuid, 4, 2)) . '-' . - \bin2hex(\substr($uuid, 6, 2)) . '-' . - \bin2hex(\substr($uuid, 8, 2)) . '-' . - \bin2hex(\substr($uuid, 10, 6)); + $this->string = bin2hex(substr($uuid, 0, 4)) . '-' . bin2hex(substr($uuid, 4, 2)) . '-' . bin2hex(substr($uuid, + 6, 2)) . '-' . bin2hex(substr($uuid, 8, 2)) . '-' . bin2hex(substr($uuid, 10, 6)); } /** @@ -161,8 +180,9 @@ protected function __construct(string $uuid) * These are derived from the time at which they were generated. * * @param string $node + * * @return string - * @throws \Exception + * @throws Exception */ protected static function mintTime(string $node = null): string { @@ -171,17 +191,17 @@ protected static function mintTime(string $node = null): string * integer size limits. * Note that this will never be more accurate than to the microsecond. */ - $time = \microtime(1) * 10000000 + static::INTERVAL; + $time = microtime(1) * 10000000 + static::INTERVAL; // Convert to a string representation $time = sprintf('%F', $time); //strip decimal point - \preg_match("/^\d+/", $time, $time); + preg_match("/^\d+/", $time, $time); // And now to a 64-bit binary representation - $time = \base_convert($time[0], 10, 16); - $time = \pack('H*', str_pad($time, 16, '0', STR_PAD_LEFT)); + $time = base_convert($time[0], 10, 16); + $time = pack('H*', str_pad($time, 16, '0', STR_PAD_LEFT)); // Reorder bytes to their proper locations in the UUID $uuid = $time[4] . $time[5] . $time[6] . $time[7] . $time[2] . $time[3] . $time[0] . $time[1]; @@ -190,10 +210,10 @@ protected static function mintTime(string $node = null): string $uuid .= static::randomBytes(2); // set variant - $uuid[8] = \chr(\ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC); + $uuid[8] = chr(ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC); // set version - $uuid[6] = \chr(\ord($uuid[6]) & static::CLEAR_VER | static::VERSION_1); + $uuid[6] = chr(ord($uuid[6]) & static::CLEAR_VER | static::VERSION_1); // Set the final 'node' parameter, a MAC address if (null !== $node) { @@ -203,8 +223,8 @@ protected static function mintTime(string $node = null): string // If no node was provided or if the node was invalid, // generate a random MAC address and set the multicast bit if (null === $node) { - $node = static::randomBytes(6); - $node[0] = \pack('C', \ord($node[0]) | 1); + $node = static::randomBytes(6); + $node[0] = pack('C', ord($node[0]) | 1); } $uuid .= $node; @@ -215,12 +235,13 @@ protected static function mintTime(string $node = null): string * Randomness is returned as a string of bytes * * @param int $bytes + * * @return string - * @throws \Exception + * @throws Exception */ public static function randomBytes($bytes): string { - return \random_bytes($bytes); + return random_bytes($bytes); } /** @@ -229,6 +250,7 @@ public static function randomBytes($bytes): string * * @param string|self $str * @param integer $len + * * @return string|null */ protected static function makeBin($str, $len): ?string @@ -237,22 +259,22 @@ protected static function makeBin($str, $len): ?string return $str->bytes; } - if (\strlen($str) === $len) { + if (strlen($str) === $len) { return $str; } - $str = (string)\preg_replace([ + $str = (string)preg_replace([ // strip URN scheme and namespace '/^urn:uuid:/is', // strip non-hex characters '/[^a-f0-9]/is', ], '', $str); - if (\strlen($str) !== ($len * 2)) { + if (strlen($str) !== ($len * 2)) { return null; } - return \pack('H*', $str); + return pack('H*', $str); } /** @@ -262,19 +284,20 @@ protected static function makeBin($str, $len): ?string * @param int $ver * @param string $node * @param string|null $ns + * * @return string - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ protected static function mintName($ver, $node, $ns): string { if (empty($node)) { - throw new \InvalidArgumentException('A name-string is required for Version 3 or 5 UUIDs.'); + throw new InvalidArgumentException('A name-string is required for Version 3 or 5 UUIDs.'); } // if the namespace UUID isn't binary, make it so $ns = static::makeBin($ns, 16); if (null === $ns) { - throw new \InvalidArgumentException('A binary namespace is required for Version 3 or 5 UUIDs.'); + throw new InvalidArgumentException('A binary namespace is required for Version 3 or 5 UUIDs.'); } $version = $uuid = null; @@ -282,21 +305,21 @@ protected static function mintName($ver, $node, $ns): string switch ($ver) { case static::MD5: $version = static::VERSION_3; - $uuid = \md5($ns . $node, 1); + $uuid = md5($ns . $node, 1); break; case static::SHA1: $version = static::VERSION_5; - $uuid = \substr(\sha1($ns . $node, 1), 0, 16); + $uuid = substr(sha1($ns . $node, 1), 0, 16); break; default: // no default really required here } // set variant - $uuid[8] = \chr(\ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC); + $uuid[8] = chr(ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC); // set version - $uuid[6] = \chr(\ord($uuid[6]) & static::CLEAR_VER | $version); + $uuid[6] = chr(ord($uuid[6]) & static::CLEAR_VER | $version); return $uuid; } @@ -307,15 +330,15 @@ protected static function mintName($ver, $node, $ns): string * generate random fields * * @return string - * @throws \Exception + * @throws Exception */ protected static function mintRand(): string { $uuid = static::randomBytes(16); // set variant - $uuid[8] = \chr(\ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC); + $uuid[8] = chr(ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC); // set version - $uuid[6] = \chr(\ord($uuid[6]) & static::CLEAR_VER | static::VERSION_4); + $uuid[6] = chr(ord($uuid[6]) & static::CLEAR_VER | static::VERSION_4); return $uuid; } @@ -324,8 +347,9 @@ protected static function mintRand(): string * Import an existing UUID * * @param string $uuid + * * @return Uuid - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public static function import(string $uuid): UUID { @@ -339,6 +363,7 @@ public static function import(string $uuid): UUID * * @param string $a * @param string $b + * * @return string|string */ public static function compare(string $a, string $b): string @@ -350,12 +375,13 @@ public static function compare(string $a, string $b): string * Import and validate an UUID * * @param Uuid|string $uuid + * * @return boolean - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public static function validate(string $uuid): bool { - return (boolean)\preg_match('~' . static::VALID_UUID_REGEX . '~', static::import($uuid)->string); + return (boolean)preg_match('~' . static::VALID_UUID_REGEX . '~', static::import($uuid)->string); } public function __isset($var) @@ -370,6 +396,7 @@ public function __set($var, $val) /** * @param string $var + * * @return string|int|NULL */ public function __get(string $var) @@ -379,11 +406,11 @@ public function __get(string $var) return $this->bytes; break; case 'hex': - return \bin2hex($this->bytes); + return bin2hex($this->bytes); break; case 'node': - if (\ord($this->bytes[6]) >> 4 === 1) { - return \bin2hex(\substr($this->bytes, 10)); + if (ord($this->bytes[6]) >> 4 === 1) { + return bin2hex(substr($this->bytes, 10)); } return null; @@ -392,15 +419,14 @@ public function __get(string $var) return $this->__toString(); break; case 'time': - if (\ord($this->bytes[6]) >> 4 === 1) { + if (ord($this->bytes[6]) >> 4 === 1) { // Restore contiguous big-endian byte order - $time = \bin2hex($this->bytes[6] . $this->bytes[7] . $this->bytes[4] . $this->bytes[5] . - $this->bytes[0] . $this->bytes[1] . $this->bytes[2] . $this->bytes[3]); + $time = bin2hex($this->bytes[6] . $this->bytes[7] . $this->bytes[4] . $this->bytes[5] . $this->bytes[0] . $this->bytes[1] . $this->bytes[2] . $this->bytes[3]); // Clear version flag $time[0] = '0'; // Do some reverse arithmetic to get a Unix timestamp - return (\hexdec($time) - static::INTERVAL) / 10000000; + return (hexdec($time) - static::INTERVAL) / 10000000; } break; @@ -408,7 +434,7 @@ public function __get(string $var) return 'urn:uuid:' . $this->__toString(); break; case 'variant': - $byte = \ord($this->bytes[8]); + $byte = ord($this->bytes[8]); if ($byte >= static::VAR_RES) { return 3; } @@ -424,7 +450,7 @@ public function __get(string $var) return 0; break; case 'version': - return \ord($this->bytes[6]) >> 4; + return ord($this->bytes[6]) >> 4; break; default: return null; diff --git a/libs/str-utils/src/UrlHelper.php b/libs/str-utils/src/UrlHelper.php index 7d905e3..7450510 100644 --- a/libs/str-utils/src/UrlHelper.php +++ b/libs/str-utils/src/UrlHelper.php @@ -8,52 +8,78 @@ namespace Toolkit\StrUtil; +use function curl_exec; +use function curl_getinfo; +use function curl_init; +use function curl_setopt; +use function file_get_contents; +use function function_exists; +use function get_headers; +use function http_build_query; +use function mb_convert_encoding; +use function parse_url; +use function preg_match; +use function rawurlencode; +use function str_replace; +use function stream_context_create; +use function strpos; +use function trim; +use function urldecode; +use function urlencode; +use const CURLINFO_HTTP_CODE; +use const CURLOPT_CONNECTTIMEOUT; +use const CURLOPT_NOBODY; +use const CURLOPT_TIMEOUT; + /** * Class UrlHelper + * * @package Toolkit\StrUtil */ class UrlHelper { /** * @param string $url the URL to be checked + * * @return boolean whether the URL is relative */ public static function isRelative(string $url): bool { - return false === \strpos($url, '//') && strpos($url, '://') === false; + return false === strpos($url, '//') && strpos($url, '://') === false; } /** * @param $str + * * @return bool */ public static function isUrl(string $str): bool { $rule = '/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i'; - return \preg_match($rule, $str) === 1; + return preg_match($rule, $str) === 1; } /** * @param $url + * * @return bool */ public static function isFullUrl(string $url): bool { - return 0 === \strpos($url, 'http:') || - 0 === \strpos($url, 'https:') || - 0 === \strpos($url, '//'); + return 0 === strpos($url, 'http:') || 0 === strpos($url, 'https:') || 0 === strpos($url, '//'); } /** * @param string $url * @param mixed $data + * * @return string */ public static function build($url, $data = null): string { - if ($data && ($param = \http_build_query($data))) { - $url .= (\strpos($url, '?') ? '&' : '?') . $param; + if ($data && ($param = http_build_query($data))) { + $url .= (strpos($url, '?') ? '&' : '?') . $param; } return $url; @@ -62,33 +88,34 @@ public static function build($url, $data = null): string /** * @param $url + * * @return bool */ public static function canAccessed(string $url): bool { - $url = \trim($url); + $url = trim($url); - if (\function_exists('curl_init')) { + if (function_exists('curl_init')) { // use curl - $ch = \curl_init($url); - \curl_setopt($ch, \CURLOPT_NOBODY, true); - \curl_setopt($ch, \CURLOPT_CONNECTTIMEOUT, 5);//设置超时 - \curl_setopt($ch, \CURLOPT_TIMEOUT, 5); + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_NOBODY, true); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);//设置超时 + curl_setopt($ch, CURLOPT_TIMEOUT, 5); - if (false !== \curl_exec($ch)) { - $statusCode = (int)\curl_getinfo($ch, \CURLINFO_HTTP_CODE); + if (false !== curl_exec($ch)) { + $statusCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); return $statusCode === 200; } - } elseif (\function_exists('get_headers')) { - $headers = \get_headers($url, 1); + } elseif (function_exists('get_headers')) { + $headers = get_headers($url, 1); - return \strpos($headers[0], 200) > 0; + return strpos($headers[0], 200) > 0; } else { - $opts = [ + $opts = [ 'http' => ['timeout' => 5,] ]; - $context = \stream_context_create($opts); - $resource = \file_get_contents($url, false, $context); + $context = stream_context_create($opts); + $resource = file_get_contents($url, false, $context); return (bool)$resource; } @@ -143,15 +170,15 @@ public static function parseUrl(string $url): array // Create encoded URL with special URL characters decoded so it can be parsed // All other characters will be encoded - $encodedURL = \str_replace(self::$entities, self::$replacements, urlencode($url)); + $encodedURL = str_replace(self::$entities, self::$replacements, urlencode($url)); // Parse the encoded URL - $encodedParts = \parse_url($encodedURL); + $encodedParts = parse_url($encodedURL); // Now, decode each value of the resulting array if ($encodedParts) { foreach ((array)$encodedParts as $key => $value) { - $result[$key] = \urldecode(\str_replace(self::$replacements, self::$entities, $value)); + $result[$key] = urldecode(str_replace(self::$replacements, self::$entities, $value)); } } @@ -165,21 +192,23 @@ public static function parseUrl(string $url): array * //ftp://ud03:password@www.xxx.net/%E4%B8%AD%E6%96%87/%E4%B8%AD%E6%96%87.rar * $url2 = urldecode($url); * echo $url1.PHP_EOL.$url2.PHP_EOL; + * * @param $url + * * @return mixed|string [type] [description] */ public static function encode(string $url) { - $url = \trim($url); + $url = trim($url); if ($url === '') { return $url; } // 若已被编码的url,将被解码,再继续重新编码 - $url = \urldecode($url); - $encodeUrl = \urlencode($url); - $encodeUrl = \str_replace(self::$entities, self::$replacements, $encodeUrl); + $url = urldecode($url); + $encodeUrl = urlencode($url); + $encodeUrl = str_replace(self::$entities, self::$replacements, $encodeUrl); return $encodeUrl; } @@ -191,20 +220,22 @@ public static function encode(string $url) * //ftp://ud03:password@www.xxx.net/%C3%A4%C2%B8%C2%AD%C3%A6%C2%96%C2%87/%C3%A4%C2%B8%C2%AD%C3%A6%C2%96%C2%87.rar * $url2 = urldecode($url); * echo $url1.PHP_EOL.$url2; - * @param string $url [description] + * + * @param string $url [description] + * * @return mixed|string [type] [description] */ public static function encode2(string $url) { - if (!$url = \trim($url)) { + if (!$url = trim($url)) { return $url; } // 若已被编码的url,将被解码,再继续重新编码 - $url = \urldecode($url); - $encodeUrl = \rawurlencode(\mb_convert_encoding($url, 'utf-8')); + $url = urldecode($url); + $encodeUrl = rawurlencode(mb_convert_encoding($url, 'utf-8')); // $url = rawurlencode($url); - $encodeUrl = \str_replace(self::$entities, self::$replacements, $encodeUrl); + $encodeUrl = str_replace(self::$entities, self::$replacements, $encodeUrl); return $encodeUrl; } diff --git a/libs/sys-utils/src/ProcessUtil.php b/libs/sys-utils/src/ProcessUtil.php index c464a9c..7e110db 100644 --- a/libs/sys-utils/src/ProcessUtil.php +++ b/libs/sys-utils/src/ProcessUtil.php @@ -8,8 +8,43 @@ namespace Toolkit\Sys; +use Closure; +use RuntimeException; +use function array_merge; +use function cli_set_process_title; +use function error_get_last; +use function file_exists; +use function file_get_contents; +use function function_exists; +use function getmypid; +use function pcntl_alarm; +use function pcntl_async_signals; +use function pcntl_fork; +use function pcntl_signal; +use function pcntl_signal_dispatch; +use function pcntl_signal_get_handler; +use function pcntl_waitpid; +use function pcntl_wexitstatus; +use function posix_geteuid; +use function posix_getgrnam; +use function posix_getpid; +use function posix_getpwnam; +use function posix_getpwuid; +use function posix_getuid; +use function posix_kill; +use function posix_setgid; +use function posix_setuid; +use function setproctitle; +use function time; +use function unlink; +use function usleep; +use const PHP_OS; +use const SIGALRM; +use const SIGTERM; + /** * Class ProcessUtil + * * @package Toolkit\Sys */ class ProcessUtil @@ -26,11 +61,13 @@ class ProcessUtil /** * fork/create a child process. + * * @param callable|null $onStart Will running on the child process start. * @param callable|null $onError - * @param int $id The process index number. will use `forks()` + * @param int $id The process index number. will use `forks()` + * * @return array|false - * @throws \RuntimeException + * @throws RuntimeException */ public static function fork(callable $onStart = null, callable $onError = null, $id = 0) { @@ -39,14 +76,14 @@ public static function fork(callable $onStart = null, callable $onError = null, } $info = []; - $pid = \pcntl_fork(); + $pid = pcntl_fork(); // at parent, get forked child info if ($pid > 0) { $info = [ 'id' => $id, 'pid' => $pid, - 'startTime' => \time(), + 'startTime' => time(), ]; } elseif ($pid === 0) { // at child $pid = self::getPid(); @@ -59,19 +96,20 @@ public static function fork(callable $onStart = null, callable $onError = null, $onError($pid); } - throw new \RuntimeException('Fork child process failed! exiting.'); + throw new RuntimeException('Fork child process failed! exiting.'); } return $info; } /** - * @see ProcessUtil::fork() * @param callable|null $onStart * @param callable|null $onError * @param int $id + * * @return array|false - * @throws \RuntimeException + * @throws RuntimeException + * @see ProcessUtil::fork() */ public static function create(callable $onStart = null, callable $onError = null, $id = 0) { @@ -80,25 +118,27 @@ public static function create(callable $onStart = null, callable $onError = null /** * Daemon, detach and run in the background - * @param \Closure|null $beforeQuit + * + * @param Closure|null $beforeQuit + * * @return int Return new process PID - * @throws \RuntimeException + * @throws RuntimeException */ - public static function daemonRun(\Closure $beforeQuit = null): int + public static function daemonRun(Closure $beforeQuit = null): int { if (!self::hasPcntl()) { return 0; } // umask(0); - $pid = \pcntl_fork(); + $pid = pcntl_fork(); switch ($pid) { case 0: // at new process $pid = self::getPid(); if (posix_setsid() < 0) { - throw new \RuntimeException('posix_setsid() execute failed! exiting'); + throw new RuntimeException('posix_setsid() execute failed! exiting'); } // chdir('/'); @@ -106,7 +146,7 @@ public static function daemonRun(\Closure $beforeQuit = null): int break; case -1: // fork failed. - throw new \RuntimeException('Fork new process is failed! exiting'); + throw new RuntimeException('Fork new process is failed! exiting'); break; default: // at parent @@ -121,12 +161,13 @@ public static function daemonRun(\Closure $beforeQuit = null): int } /** - * @see ProcessUtil::forks() * @param int $number * @param callable|null $onStart * @param callable|null $onError + * * @return array|false - * @throws \RuntimeException + * @throws RuntimeException + * @see ProcessUtil::forks() */ public static function multi(int $number, callable $onStart = null, callable $onError = null) { @@ -135,11 +176,13 @@ public static function multi(int $number, callable $onStart = null, callable $on /** * fork/create multi child processes. + * * @param int $number * @param callable|null $onStart Will running on the child processes. * @param callable|null $onError + * * @return array|false - * @throws \RuntimeException + * @throws RuntimeException */ public static function forks(int $number, callable $onStart = null, callable $onError = null) { @@ -154,7 +197,7 @@ public static function forks(int $number, callable $onStart = null, callable $on $pidAry = []; for ($id = 0; $id < $number; $id++) { - $info = self::fork($onStart, $onError, $id); + $info = self::fork($onStart, $onError, $id); $pidAry[$info['pid']] = $info; } @@ -163,7 +206,9 @@ public static function forks(int $number, callable $onStart = null, callable $on /** * wait child exit. + * * @param callable $onExit Exit callback. will received args: (pid, exitCode, status) + * * @return bool */ public static function wait(callable $onExit): bool @@ -177,12 +222,12 @@ public static function wait(callable $onExit): bool // pid < 0:子进程都没了 // pid > 0:捕获到一个子进程退出的情况 // pid = 0:没有捕获到退出的子进程 - while (($pid = \pcntl_waitpid(-1, $status, WNOHANG)) >= 0) { + while (($pid = pcntl_waitpid(-1, $status, WNOHANG)) >= 0) { if ($pid) { // handler(pid, exitCode, status) - $onExit($pid, \pcntl_wexitstatus($status), $status); + $onExit($pid, pcntl_wexitstatus($status), $status); } else { - \usleep(50000); + usleep(50000); } } @@ -191,26 +236,28 @@ public static function wait(callable $onExit): bool /** * Stops all running children + * * @param array $children - * [ - * 'pid' => [ + * [ + * 'pid' => [ * 'id' => worker id - * ], - * ... ... - * ] + * ], + * ... ... + * ] * @param int $signal * @param array $events - * [ - * 'beforeStops' => function ($sigText) { + * [ + * 'beforeStops' => function ($sigText) { * echo "Stopping processes({$sigText}) ...\n"; - * }, - * 'beforeStop' => function ($pid, $info) { + * }, + * 'beforeStop' => function ($pid, $info) { * echo "Stopping process(PID:$pid)\n"; - * } - * ] + * } + * ] + * * @return bool */ - public static function stopWorkers(array $children, int $signal = \SIGTERM, array $events = []): bool + public static function stopWorkers(array $children, int $signal = SIGTERM, array $events = []): bool { if (!$children) { return false; @@ -220,7 +267,7 @@ public static function stopWorkers(array $children, int $signal = \SIGTERM, arra return false; } - $events = \array_merge([ + $events = array_merge([ 'beforeStops' => null, 'beforeStop' => null, ], $events); @@ -247,9 +294,11 @@ public static function stopWorkers(array $children, int $signal = \SIGTERM, arra /** * send kill signal to the process + * * @param int $pid * @param bool $force * @param int $timeout + * * @return bool */ public static function kill(int $pid, bool $force = false, int $timeout = 3): bool @@ -259,11 +308,13 @@ public static function kill(int $pid, bool $force = false, int $timeout = 3): bo /** * Do shutdown process and wait it exit. + * * @param int $pid Master Pid * @param bool $force * @param int $waitTime * @param null $error * @param string $name + * * @return bool */ public static function killAndWait( @@ -287,7 +338,7 @@ public static function killAndWait( return true; } - $startTime = \time(); + $startTime = time(); echo 'Stopping .'; // wait exit @@ -296,7 +347,7 @@ public static function killAndWait( break; } - if (\time() - $startTime > $waitTime) { + if (time() - $startTime > $waitTime) { $error = "Stop the $name(PID:$pid) failed(timeout)!"; break; } @@ -314,6 +365,7 @@ public static function killAndWait( /** * @param int $pid + * * @return bool */ public static function isRunning(int $pid): bool @@ -323,6 +375,7 @@ public static function isRunning(int $pid): bool /** * exit + * * @param int $code */ public static function quit($code = 0): void @@ -332,8 +385,10 @@ public static function quit($code = 0): void /** * 杀死所有进程 + * * @param $name * @param int $sigNo + * * @return string */ public static function killByName(string $name, int $sigNo = 9): string @@ -349,9 +404,11 @@ public static function killByName(string $name, int $sigNo = 9): string /** * send signal to the process + * * @param int $pid * @param int $signal * @param int $timeout + * * @return bool */ public static function sendSignal(int $pid, int $signal, int $timeout = 0): bool @@ -361,7 +418,7 @@ public static function sendSignal(int $pid, int $signal, int $timeout = 0): bool } // do send - if ($ret = \posix_kill($pid, $signal)) { + if ($ret = posix_kill($pid, $signal)) { return true; } @@ -371,8 +428,8 @@ public static function sendSignal(int $pid, int $signal, int $timeout = 0): bool } // failed, try again ... - $timeout = $timeout > 0 && $timeout < 10 ? $timeout : 3; - $startTime = \time(); + $timeout = $timeout > 0 && $timeout < 10 ? $timeout : 3; + $startTime = time(); // retry stop if not stopped. while (true) { @@ -382,13 +439,13 @@ public static function sendSignal(int $pid, int $signal, int $timeout = 0): bool } // have been timeout - if ((\time() - $startTime) >= $timeout) { + if ((time() - $startTime) >= $timeout) { return false; } // try again kill - $ret = \posix_kill($pid, $signal); - \usleep(10000); + $ret = posix_kill($pid, $signal); + usleep(10000); } return $ret; @@ -396,8 +453,10 @@ public static function sendSignal(int $pid, int $signal, int $timeout = 0): bool /** * install signal - * @param int $signal e.g: SIGTERM SIGINT(Ctrl+C) SIGUSR1 SIGUSR2 SIGHUP - * @param callable $handler + * + * @param int $signal e.g: SIGTERM SIGINT(Ctrl+C) SIGUSR1 SIGUSR2 SIGHUP + * @param callable $handler + * * @return bool */ public static function installSignal($signal, callable $handler): bool @@ -406,11 +465,12 @@ public static function installSignal($signal, callable $handler): bool return false; } - return \pcntl_signal($signal, $handler, false); + return pcntl_signal($signal, $handler, false); } /** * dispatch signal + * * @return bool */ public static function dispatchSignal(): bool @@ -420,31 +480,35 @@ public static function dispatchSignal(): bool } // receive and dispatch signal - return \pcntl_signal_dispatch(); + return pcntl_signal_dispatch(); } /** * get signal handler + * * @param int $signal + * * @return bool|string|mixed * @since 7.1 */ public static function getSignalHandler(int $signal) { - return \pcntl_signal_get_handler($signal); + return pcntl_signal_get_handler($signal); } /** * Enable/disable asynchronous signal handling or return the old setting + * * @param bool|null $on * - bool Enable or disable. * - null Return old setting. + * * @return bool * @since 7.1 */ public static function asyncSignal(bool $on = null): bool { - return \pcntl_async_signals($on); + return pcntl_async_signals($on); } /************************************************************************************** @@ -453,34 +517,37 @@ public static function asyncSignal(bool $on = null): bool /** * get current process id + * * @return int */ public static function getPid(): int { - if (\function_exists('posix_getpid')) { - return \posix_getpid(); + if (function_exists('posix_getpid')) { + return posix_getpid(); } - return \getmypid(); + return getmypid(); } /** * get PID by pid File + * * @param string $file * @param bool $checkLive + * * @return int */ public static function getPidByFile(string $file, bool $checkLive = false): int { - if ($file && \file_exists($file)) { - $pid = (int)\file_get_contents($file); + if ($file && file_exists($file)) { + $pid = (int)file_get_contents($file); // check live if ($checkLive && self::isRunning($pid)) { return $pid; } - \unlink($file); + unlink($file); } return 0; @@ -488,11 +555,12 @@ public static function getPidByFile(string $file, bool $checkLive = false): int /** * Get unix user of current process. + * * @return array */ public static function getCurrentUser(): array { - return \posix_getpwuid(\posix_getuid()); + return posix_getpwuid(posix_getuid()); } /** @@ -505,8 +573,10 @@ public static function getCurrentUser(): array * ProcessUtil::clearAlarm(); // close * } * }); + * * @param int $seconds * @param callable $handler + * * @return bool|int */ public static function afterDo(int $seconds, callable $handler) @@ -515,9 +585,9 @@ public static function afterDo(int $seconds, callable $handler) return false; } - self::installSignal(\SIGALRM, $handler); + self::installSignal(SIGALRM, $handler); - return \pcntl_alarm($seconds); + return pcntl_alarm($seconds); } /** @@ -525,15 +595,17 @@ public static function afterDo(int $seconds, callable $handler) */ public static function clearAlarm(): int { - return \pcntl_alarm(-1); + return pcntl_alarm(-1); } /** * run a command. it is support windows + * * @param string $command * @param string|null $cwd + * * @return array - * @throws \RuntimeException + * @throws RuntimeException * @deprecated Please use Sys::run() */ public static function run(string $command, string $cwd = null): array @@ -543,7 +615,9 @@ public static function run(string $command, string $cwd = null): array /** * Set process title. + * * @param string $title + * * @return bool */ public static function setName(string $title): bool @@ -553,23 +627,25 @@ public static function setName(string $title): bool /** * Set process title. + * * @param string $title + * * @return bool */ public static function setTitle(string $title): bool { - if (!$title || 'Darwin' === \PHP_OS) { + if (!$title || 'Darwin' === PHP_OS) { return false; } - if (\function_exists('cli_set_process_title')) { - \cli_set_process_title($title); - } elseif (\function_exists('setproctitle')) { - \setproctitle($title); + if (function_exists('cli_set_process_title')) { + cli_set_process_title($title); + } elseif (function_exists('setproctitle')) { + setproctitle($title); } - if ($error = \error_get_last()) { - throw new \RuntimeException($error['message']); + if ($error = error_get_last()) { + throw new RuntimeException($error['message']); } return false; @@ -577,24 +653,26 @@ public static function setTitle(string $title): bool /** * Set unix user and group for current process script. + * * @param string $user * @param string $group - * @throws \RuntimeException + * + * @throws RuntimeException */ public static function changeScriptOwner(string $user, string $group = ''): void { - $uInfo = \posix_getpwnam($user); + $uInfo = posix_getpwnam($user); if (!$uInfo || !isset($uInfo['uid'])) { - throw new \RuntimeException("User ({$user}) not found."); + throw new RuntimeException("User ({$user}) not found."); } $uid = (int)$uInfo['uid']; // Get gid. if ($group) { - if (!$gInfo = \posix_getgrnam($group)) { - throw new \RuntimeException("Group {$group} not exists", -300); + if (!$gInfo = posix_getgrnam($group)) { + throw new RuntimeException("Group {$group} not exists", -300); } $gid = (int)$gInfo['gid']; @@ -603,19 +681,19 @@ public static function changeScriptOwner(string $user, string $group = ''): void } if (!posix_initgroups($uInfo['name'], $gid)) { - throw new \RuntimeException("The user [{$user}] is not in the user group ID [GID:{$gid}]", -300); + throw new RuntimeException("The user [{$user}] is not in the user group ID [GID:{$gid}]", -300); } - \posix_setgid($gid); + posix_setgid($gid); - if (\posix_geteuid() !== $gid) { - throw new \RuntimeException("Unable to change group to {$user} (UID: {$gid}).", -300); + if (posix_geteuid() !== $gid) { + throw new RuntimeException("Unable to change group to {$user} (UID: {$gid}).", -300); } - \posix_setuid($uid); + posix_setuid($uid); - if (\posix_geteuid() !== $uid) { - throw new \RuntimeException("Unable to change user to {$user} (UID: {$uid}).", -300); + if (posix_geteuid() !== $uid) { + throw new RuntimeException("Unable to change user to {$user} (UID: {$uid}).", -300); } } @@ -624,7 +702,7 @@ public static function changeScriptOwner(string $user, string $group = ''): void */ public static function hasPcntl(): bool { - return !Sys::isWindows() && \function_exists('pcntl_fork'); + return !Sys::isWindows() && function_exists('pcntl_fork'); } /** @@ -632,6 +710,6 @@ public static function hasPcntl(): bool */ public static function hasPosix(): bool { - return !Sys::isWindows() && \function_exists('posix_kill'); + return !Sys::isWindows() && function_exists('posix_kill'); } } diff --git a/libs/sys-utils/src/Signal.php b/libs/sys-utils/src/Signal.php index cfb857c..64be458 100644 --- a/libs/sys-utils/src/Signal.php +++ b/libs/sys-utils/src/Signal.php @@ -10,8 +10,9 @@ /** * Class Signal + * * @package Toolkit\Sys - * @link http://php.net/manual/en/pcntl.constants.php + * @link http://php.net/manual/en/pcntl.constants.php */ final class Signal { diff --git a/libs/sys-utils/src/Sys.php b/libs/sys-utils/src/Sys.php index ef379f0..9321e69 100644 --- a/libs/sys-utils/src/Sys.php +++ b/libs/sys-utils/src/Sys.php @@ -8,8 +8,34 @@ namespace Toolkit\Sys; +use RuntimeException; +use function chdir; +use function exec; +use function fclose; +use function function_exists; +use function getcwd; +use function implode; +use function is_resource; +use function ob_end_clean; +use function ob_get_contents; +use function ob_start; +use function passthru; +use function pclose; +use function popen; +use function posix_getpwuid; +use function posix_getuid; +use function preg_match; +use function preg_replace; +use function proc_close; +use function proc_open; +use function shell_exec; +use function sys_get_temp_dir; +use function system; +use function trim; + /** * Class Sys + * * @package Toolkit\Sys */ class Sys extends SysEnv @@ -18,8 +44,9 @@ class Sys extends SysEnv * @param string $command * @param null|string $logfile * @param null|string $user + * * @return mixed - * @throws \RuntimeException + * @throws RuntimeException */ public static function exec($command, $logfile = null, $user = null) { @@ -37,7 +64,7 @@ public static function exec($command, $logfile = null, $user = null) exec("$suDo $command 1>> \"$logfile\" 2>&1", $dummy, $retVal); if ($retVal !== 0) { - throw new \RuntimeException("command exited with status '$retVal'."); + throw new RuntimeException("command exited with status '$retVal'."); } return $dummy; @@ -45,10 +72,12 @@ public static function exec($command, $logfile = null, $user = null) /** * run a command. it is support windows + * * @param string $command * @param string|null $cwd + * * @return array - * @throws \RuntimeException + * @throws RuntimeException */ public static function run(string $command, string $cwd = null): array { @@ -59,26 +88,26 @@ public static function run(string $command, string $cwd = null): array 3 => ['pipe', 'r'], // stdin - This is the pipe we can feed the password into ]; - $process = \proc_open($command, $descriptors, $pipes, $cwd); + $process = proc_open($command, $descriptors, $pipes, $cwd); - if (!\is_resource($process)) { - throw new \RuntimeException("Can't open resource with proc_open."); + if (!is_resource($process)) { + throw new RuntimeException("Can't open resource with proc_open."); } // Nothing to push to input. - \fclose($pipes[0]); + fclose($pipes[0]); $output = stream_get_contents($pipes[1]); - \fclose($pipes[1]); + fclose($pipes[1]); $error = stream_get_contents($pipes[2]); - \fclose($pipes[2]); + fclose($pipes[2]); // TODO: Write passphrase in pipes[3]. - \fclose($pipes[3]); + fclose($pipes[3]); // Close all pipes before proc_close! $code === 0 is success. - $code = \proc_close($process); + $code = proc_close($process); return [$code, $output, $error]; } @@ -90,9 +119,11 @@ public static function run(string $command, string $cwd = null): array * 2. passthru * 3. exec * 4. shell_exec + * * @param string $command * @param bool $returnStatus * @param string|null $cwd + * * @return array|string */ public static function execute(string $command, bool $returnStatus = true, string $cwd = null) @@ -100,47 +131,48 @@ public static function execute(string $command, bool $returnStatus = true, strin $exitStatus = 1; if ($cwd) { - \chdir($cwd); + chdir($cwd); } // system - if (\function_exists('system')) { - \ob_start(); - \system($command, $exitStatus); - $output = \ob_get_contents(); - \ob_end_clean(); + if (function_exists('system')) { + ob_start(); + system($command, $exitStatus); + $output = ob_get_contents(); + ob_end_clean(); // passthru - } elseif (\function_exists('passthru')) { - \ob_start(); - \passthru($command, $exitStatus); - $output = \ob_get_contents(); - \ob_end_clean(); + } elseif (function_exists('passthru')) { + ob_start(); + passthru($command, $exitStatus); + $output = ob_get_contents(); + ob_end_clean(); //exec - } elseif (\function_exists('exec')) { - \exec($command, $output, $exitStatus); - $output = \implode("\n", $output); + } elseif (function_exists('exec')) { + exec($command, $output, $exitStatus); + $output = implode("\n", $output); //shell_exec - } elseif (\function_exists('shell_exec')) { - $output = \shell_exec($command); + } elseif (function_exists('shell_exec')) { + $output = shell_exec($command); } else { - $output = 'Command execution not possible on this system'; + $output = 'Command execution not possible on this system'; $exitStatus = 0; } if ($returnStatus) { return [ - 'output' => \trim($output), + 'output' => trim($output), 'status' => $exitStatus ]; } - return \trim($output); + return trim($output); } /** * run a command in background + * * @param string $cmd */ public static function bgExec(string $cmd): void @@ -150,24 +182,26 @@ public static function bgExec(string $cmd): void /** * run a command in background + * * @param string $cmd */ public static function execInBackground(string $cmd): void { if (self::isWindows()) { - \pclose(\popen('start /B ' . $cmd, 'r')); + pclose(popen('start /B ' . $cmd, 'r')); } else { - \exec($cmd . ' > /dev/null &'); + exec($cmd . ' > /dev/null &'); } } /** * Get unix user of current process. + * * @return array */ public static function getCurrentUser(): array { - return \posix_getpwuid(\posix_getuid()); + return posix_getpwuid(posix_getuid()); } /** @@ -184,8 +218,8 @@ public static function tempDir(): string public static function getTempDir(): string { // @codeCoverageIgnoreStart - if (\function_exists('sys_get_temp_dir')) { - $tmp = \sys_get_temp_dir(); + if (function_exists('sys_get_temp_dir')) { + $tmp = sys_get_temp_dir(); } elseif (!empty($_SERVER['TMP'])) { $tmp = $_SERVER['TMP']; } elseif (!empty($_SERVER['TEMP'])) { @@ -193,7 +227,7 @@ public static function getTempDir(): string } elseif (!empty($_SERVER['TMPDIR'])) { $tmp = $_SERVER['TMPDIR']; } else { - $tmp = \getcwd(); + $tmp = getcwd(); } // @codeCoverageIgnoreEnd @@ -202,6 +236,7 @@ public static function getTempDir(): string /** * get bash is available + * * @return bool */ public static function shIsAvailable(): bool @@ -215,6 +250,7 @@ public static function shIsAvailable(): bool /** * get bash is available + * * @return bool */ public static function bashIsAvailable(): bool @@ -233,7 +269,7 @@ public static function getOutsideIP(): string { [$code, $output] = self::run('ip addr | grep eth0'); - if ($code === 0 && $output && \preg_match('#inet (.*)\/#', $output, $ms)) { + if ($code === 0 && $output && preg_match('#inet (.*)\/#', $output, $ms)) { return $ms[1]; } @@ -246,10 +282,13 @@ public static function getOutsideIP(): string * ```php * list($width, $height) = Sys::getScreenSize(); * ``` + * * @from Yii2 + * * @param boolean $refresh whether to force checking and not re-use cached size value. - * This is useful to detect changing window size while the application is running but may - * not get up to date values on every terminal. + * This is useful to detect changing window size while the application is running but may + * not get up to date values on every terminal. + * * @return array|boolean An array of ($width, $height) or false when it was not able to determine size. */ public static function getScreenSize(bool $refresh = false) @@ -263,9 +302,8 @@ public static function getScreenSize(bool $refresh = false) // try stty if available $stty = []; - if ( - \exec('stty -a 2>&1', $stty) && - \preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty), $matches) + if (exec('stty -a 2>&1', $stty) && preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty), + $matches) ) { return ($size = [$matches[2], $matches[1]]); } @@ -283,12 +321,12 @@ public static function getScreenSize(bool $refresh = false) if (self::isWindows()) { $output = []; - \exec('mode con', $output); + exec('mode con', $output); if (isset($output[1]) && strpos($output[1], 'CON') !== false) { return ($size = [ - (int)\preg_replace('~\D~', '', $output[3]), - (int)\preg_replace('~\D~', '', $output[4]) + (int)preg_replace('~\D~', '', $output[3]), + (int)preg_replace('~\D~', '', $output[4]) ]); } } @@ -298,6 +336,7 @@ public static function getScreenSize(bool $refresh = false) /** * @param string $program + * * @return int|string */ public static function getCpuUsage(string $program) @@ -306,13 +345,14 @@ public static function getCpuUsage(string $program) return -1; } - $info = \exec('ps aux | grep ' . $program . ' | grep -v grep | grep -v su | awk {"print $3"}'); + $info = exec('ps aux | grep ' . $program . ' | grep -v grep | grep -v su | awk {"print $3"}'); return $info; } /** * @param string $program + * * @return int|string */ public static function getMemUsage(string $program) @@ -321,7 +361,7 @@ public static function getMemUsage(string $program) return -1; } - $info = \exec('ps aux | grep ' . $program . ' | grep -v grep | grep -v su | awk {"print $4"}'); + $info = exec('ps aux | grep ' . $program . ' | grep -v grep | grep -v su | awk {"print $4"}'); return $info; } diff --git a/libs/sys-utils/src/SysEnv.php b/libs/sys-utils/src/SysEnv.php index 7498e5c..8db3479 100644 --- a/libs/sys-utils/src/SysEnv.php +++ b/libs/sys-utils/src/SysEnv.php @@ -8,8 +8,17 @@ namespace Toolkit\Sys; +use function defined; +use function function_exists; +use function getmyuid; +use function in_array; +use function php_uname; +use function posix_getuid; +use function stripos; + /** * Class EnvHelper + * * @package Toolkit\Sys */ class SysEnv @@ -25,7 +34,7 @@ public static function isUnix(): bool { $uNames = ['CYG', 'DAR', 'FRE', 'HP-', 'IRI', 'LIN', 'NET', 'OPE', 'SUN', 'UNI']; - return \in_array(strtoupper(substr(PHP_OS, 0, 3)), $uNames, true); + return in_array(strtoupper(substr(PHP_OS, 0, 3)), $uNames, true); } /** @@ -57,7 +66,7 @@ public static function isWindows(): bool */ public static function isMac(): bool { - return \stripos(PHP_OS, 'Darwin') !== false; + return stripos(PHP_OS, 'Darwin') !== false; } /** @@ -65,11 +74,11 @@ public static function isMac(): bool */ public static function isRoot(): bool { - if (\function_exists('posix_getuid')) { - return \posix_getuid() === 0; + if (function_exists('posix_getuid')) { + return posix_getuid() === 0; } - return \getmyuid() === 0; + return getmyuid() === 0; } /** @@ -77,7 +86,7 @@ public static function isRoot(): bool */ public static function getHostname(): string { - return \php_uname('n'); + return php_uname('n'); } /** @@ -104,20 +113,17 @@ public static function supportColor(): bool * Returns true if STDOUT supports colorization. * This code has been copied and adapted from * \Symfony\Component\Console\Output\OutputStream. + * * @return boolean */ public static function isSupportColor(): bool { if (DIRECTORY_SEPARATOR === '\\') { - return - '10.0.10586' === PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . '.' . PHP_WINDOWS_VERSION_BUILD - || false !== getenv('ANSICON') - || 'ON' === getenv('ConEmuANSI') - || 'xterm' === getenv('TERM')// || 'cygwin' === getenv('TERM') + return '10.0.10586' === PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . '.' . PHP_WINDOWS_VERSION_BUILD || false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI') || 'xterm' === getenv('TERM')// || 'cygwin' === getenv('TERM') ; } - if (!\defined('STDOUT')) { + if (!defined('STDOUT')) { return false; } @@ -126,12 +132,14 @@ public static function isSupportColor(): bool /** * Returns if the file descriptor is an interactive terminal or not. - * @param int|resource $fileDescriptor + * + * @param int|resource $fileDescriptor + * * @return boolean */ public static function isInteractive($fileDescriptor): bool { - return \function_exists('posix_isatty') && @posix_isatty($fileDescriptor); + return function_exists('posix_isatty') && @posix_isatty($fileDescriptor); } } diff --git a/toolkit b/toolkit index 561c767..b6a3bce 100644 --- a/toolkit +++ b/toolkit @@ -4,6 +4,9 @@ * entry file for CLI */ +use Inhere\Console\Application; +use Toolkit\Dev\Console\DevController; + define('BASE_PATH', __DIR__); define('TOOLKIT_DIR', __DIR__); @@ -14,7 +17,7 @@ if (file_exists(__DIR__ . '/vendor/autoload.php')) { } // create app instance -$app = new \Inhere\Console\Application([ +$app = new Application([ 'name' => 'php toolkit', 'debug' => true, 'version' => '1.0.0', @@ -30,7 +33,7 @@ $app->setLogo(" ", 'success'); // add commands -$app->addController(\Toolkit\Dev\Console\DevController::class); +$app->addController(DevController::class); // run $app->run();