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(
- "
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("
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) : "