'));
- }
-}
diff --git a/libs/cli-utils/test/ColorTest.php b/libs/cli-utils/test/ColorTest.php
deleted file mode 100644
index 5f5fb3d..0000000
--- a/libs/cli-utils/test/ColorTest.php
+++ /dev/null
@@ -1,43 +0,0 @@
-assertStringContainsString(Color::STYLES['info'], $text);
-
- $text = Color::render('text', [Color::RESET, Color::FG_CYAN]);
- $this->assertStringContainsString(Color::STYLES['cyan'], $text);
-
- $text = Color::render('text');
- $this->assertStringContainsString(Color::STYLES['info'], $text);
-
- $text = Color::render('text');
- $this->assertStringContainsString(Color::STYLES['light_blue'], $text);
-
- $text = Color::render('text');
- $this->assertStringContainsString(Color::STYLES['lightBlue'], $text);
- }
-
- public function testApply(): void
- {
- $text = Color::apply('info', 'text');
- $this->assertStringContainsString(Color::STYLES['info'], $text);
-
- foreach (Color::STYLES as $name => $code) {
- $text = Color::apply($name, 'text');
- $this->assertStringContainsString($code, $text);
- }
- }
-}
diff --git a/libs/cli-utils/test/FlagsTest.php b/libs/cli-utils/test/FlagsTest.php
deleted file mode 100644
index f4d2f9c..0000000
--- a/libs/cli-utils/test/FlagsTest.php
+++ /dev/null
@@ -1,38 +0,0 @@
-assertNotEmpty($args);
- $this->assertSame('git:tag', $args[0]);
- $this->assertSame('arg0', $args[1]);
-
- $this->assertSame('../view', $sOpts['d']);
- $this->assertTrue($lOpts['only-tag']);
-
- [$args, $opts] = Flags::parseArgv($rawArgv, ['mergeOpts' => true]);
-
- $this->assertNotEmpty($args);
- $this->assertSame('git:tag', $args[0]);
- $this->assertSame('arg0', $args[1]);
-
- $this->assertSame('../view', $opts['d']);
- $this->assertTrue($opts['only-tag']);
- }
-}
diff --git a/libs/cli-utils/test/boot.php b/libs/cli-utils/test/boot.php
deleted file mode 100644
index 8afcdc7..0000000
--- a/libs/cli-utils/test/boot.php
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
- test/
-
-
-
-
-
- src
-
-
-
diff --git a/libs/di/LICENSE b/libs/di/LICENSE
deleted file mode 100644
index d839cdc..0000000
--- a/libs/di/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2016 inhere
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/libs/di/phpunit.xml.dist b/libs/di/phpunit.xml.dist
deleted file mode 100644
index 26bd767..0000000
--- a/libs/di/phpunit.xml.dist
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
- test/
-
-
-
-
-
- src
-
-
-
diff --git a/libs/file-parse/.gitignore b/libs/file-parse/.gitignore
deleted file mode 100644
index 86318a0..0000000
--- a/libs/file-parse/.gitignore
+++ /dev/null
@@ -1,10 +0,0 @@
-.idea/
-.phpintel/
-!README.md
-!.gitkeep
-composer.lock
-*.swp
-*.log
-*.pid
-*.patch
-.DS_Store
diff --git a/libs/file-parse/LICENSE b/libs/file-parse/LICENSE
deleted file mode 100644
index d839cdc..0000000
--- a/libs/file-parse/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2016 inhere
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/libs/file-parse/README.md b/libs/file-parse/README.md
deleted file mode 100644
index 1f24de0..0000000
--- a/libs/file-parse/README.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# file parse
-
-[](LICENSE)
-[](https://packagist.org/packages/toolkit/file-parse)
-[](https://packagist.org/packages/toolkit/file-parse)
-
-Some useful file parse utils for the php.
-
-`ini`, `json`, `yml` 格式的文件解析
-
-- json 文件支持去除注释,即是有注释不会导致解析失败
-- 支持特殊关键字
- - `extend` 继承另一个文件的内容
- - `import` 导入另一个文件的内容
- - `reference` 参考另一个key的值 **todo**
-
-例如在 yml 文件(其他格式的文件类似)可以这样:
-
-```text
-// will parse special keywords
-extend: ../parent.yml
-debug: true
-db: import#../db.yml
-cache:
- debug: reference#debug
-```
-
-## Install
-
-```bash
-composer require toolkit/file-parse
-```
-
-## License
-
-MIT
diff --git a/libs/file-parse/composer.json b/libs/file-parse/composer.json
deleted file mode 100644
index 467baa8..0000000
--- a/libs/file-parse/composer.json
+++ /dev/null
@@ -1,32 +0,0 @@
-{
- "name": "toolkit/file-parse",
- "type": "library",
- "description": "some file parse tool library of the php",
- "keywords": [
- "library",
- "tool",
- "php"
- ],
- "homepage": "https://github.com/php-toolkit/file-parse",
- "license": "MIT",
- "authors": [
- {
- "name": "inhere",
- "email": "in.798@qq.com",
- "homepage": "http://www.yzone.net/"
- }
- ],
- "require": {
- "php": ">7.1.0",
- "toolkit/str-utils": "~1.0"
- },
- "autoload": {
- "psr-4": {
- "Toolkit\\File\\Parse\\": "src/"
- }
- },
- "suggest": {
- "inhere/php-validate": "Very lightweight data validate tool",
- "inhere/console": "a lightweight php console application library."
- }
-}
diff --git a/libs/file-parse/phpunit.xml.dist b/libs/file-parse/phpunit.xml.dist
deleted file mode 100644
index 30356d2..0000000
--- a/libs/file-parse/phpunit.xml.dist
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
- test
-
-
-
-
-
- src
-
-
-
diff --git a/libs/file-parse/src/BaseParser.php b/libs/file-parse/src/BaseParser.php
deleted file mode 100644
index d8d1b90..0000000
--- a/libs/file-parse/src/BaseParser.php
+++ /dev/null
@@ -1,98 +0,0 @@
- $item) {
- if (!is_string($item)) {
- continue;
- }
-
- if (0 === strpos($item, self::IMPORT_KEY . '#')) {
- $importFile = trim(substr($item, 7));
-
- // if needed custom handle $importFile path. e.g: Maybe it uses custom alias path
- if ($pathHandler && is_callable($pathHandler)) {
- $importFile = $pathHandler($importFile);
- }
-
- // if $importFile is not exists AND $importFile is not a absolute path AND have $parentFile
- if ($fileDir && !file_exists($importFile) && $importFile[0] !== '/') {
- $importFile = $fileDir . '/' . trim($importFile, './');
- }
-
- // $importFile is file
- if (is_file($importFile)) {
- $data = file_get_contents($importFile);
- $array[$key] = parse_ini_string(trim($data), true);
- } else {
- throw new UnexpectedValueException("needed imported file [$importFile] don't exists!");
- }
- }
- }
-
- }
-
- return $array;
- }
-
-}
diff --git a/libs/file-parse/src/JsonParser.php b/libs/file-parse/src/JsonParser.php
deleted file mode 100644
index 20762ba..0000000
--- a/libs/file-parse/src/JsonParser.php
+++ /dev/null
@@ -1,121 +0,0 @@
- $item) {
- if (!is_string($item)) {
- continue;
- }
-
- if (0 === strpos($item, self::IMPORT_KEY . '#')) {
- $importFile = trim(substr($item, 6));
-
- // if needed custom handle $importFile path. e.g: Maybe it uses custom alias path
- if ($pathHandler && is_callable($pathHandler)) {
- $importFile = $pathHandler($importFile);
- }
-
- // if $importFile is not exists AND $importFile is not a absolute path AND have $parentFile
- if ($fileDir && !file_exists($importFile) && $importFile[0] !== '/') {
- $importFile = $fileDir . '/' . trim($importFile, './');
- }
-
- // $importFile is file
- if (is_file($importFile)) {
- $data = file_get_contents($importFile);
- $array[$key] = JsonHelper::parse($data);
- } else {
- throw new UnexpectedValueException("needed imported file [$importFile] don't exists!");
- }
- }
- }
-
- }
-
- return $array;
- }
-}
diff --git a/libs/file-parse/src/YmlParser.php b/libs/file-parse/src/YmlParser.php
deleted file mode 100644
index cadd53c..0000000
--- a/libs/file-parse/src/YmlParser.php
+++ /dev/null
@@ -1,128 +0,0 @@
-parse(trim($string));
-
- /*
- * Parse special keywords
- *
- * extend: ../parent.yml
- * db: import#../db.yml
- * cache:
- * debug: reference#debug
- */
- if ($enhancement === true) {
- if (isset($array[self::EXTEND_KEY]) && ($extendFile = $array[self::EXTEND_KEY])) {
- // if needed custom handle $importFile path. e.g: Maybe it uses custom alias path
- if ($pathHandler && is_callable($pathHandler)) {
- $extendFile = $pathHandler($extendFile);
- }
-
- // if $importFile is not exists AND $importFile is not a absolute path AND have $parentFile
- if ($fileDir && !file_exists($extendFile) && $extendFile[0] !== '/') {
- $extendFile = $fileDir . '/' . trim($extendFile, './');
- }
-
- // $importFile is file
- if (is_file($extendFile)) {
- $data = file_get_contents($extendFile);
- $array = array_merge($parser->parse(trim($data)), $array);
- } else {
- throw new UnexpectedValueException("needed extended file $extendFile don't exists!");
- }
- }
-
- foreach ($array as $key => $item) {
- if (!is_string($item)) {
- continue;
- }
-
- if (0 === strpos($item, self::IMPORT_KEY . '#')) {
- $importFile = trim(substr($item, 6));
-
- // if needed custom handle $importFile path. e.g: Maybe it uses custom alias path
- if ($pathHandler && is_callable($pathHandler)) {
- $importFile = $pathHandler($importFile);
- }
-
- // if $importFile is not exists AND $importFile is not a absolute path AND have $parentFile
- if ($fileDir && !file_exists($importFile) && $importFile[0] !== '/') {
- $importFile = $fileDir . '/' . trim($importFile, './');
- }
-
- // $importFile is file
- if (is_file($importFile)) {
- $data = file_get_contents($importFile);
- $array[$key] = $parser->parse(trim($data));
- } else {
- throw new UnexpectedValueException("needed imported file $importFile don't exists!");
- }
- }
- }
-
- }
-
- return $array;
- }
-
-}
diff --git a/libs/file-parse/test/IniParserTest.php b/libs/file-parse/test/IniParserTest.php
deleted file mode 100644
index b869679..0000000
--- a/libs/file-parse/test/IniParserTest.php
+++ /dev/null
@@ -1,37 +0,0 @@
-assertArrayHasKey('name', $ret);
- $this->assertSame('import#include.ini', $ret['include']);
-
-
- $ret = IniParser::parseFile(__DIR__ . '/data/test.ini', true);
-
- $this->assertArrayHasKey('name', $ret);
- $this->assertArrayHasKey('he', $ret['include']);
- }
-}
diff --git a/libs/file-parse/test/boot.php b/libs/file-parse/test/boot.php
deleted file mode 100644
index 117c3f4..0000000
--- a/libs/file-parse/test/boot.php
+++ /dev/null
@@ -1,27 +0,0 @@
-7.1.0"
- },
- "autoload": {
- "psr-4": {
- "Toolkit\\File\\": "src/"
- }
- },
- "suggest": {
- "inhere/php-validate": "Very lightweight data validate tool",
- "inhere/console": "a lightweight php console application library."
- }
-}
diff --git a/libs/file-utils/example/dir-watcher.php b/libs/file-utils/example/dir-watcher.php
deleted file mode 100644
index a680e7f..0000000
--- a/libs/file-utils/example/dir-watcher.php
+++ /dev/null
@@ -1,20 +0,0 @@
-setIdFile(__DIR__ . '/tmp/dir.id')
- ->watch(dirname(__DIR__))->isChanged();
-
-// d41d8cd98f00b204e9800998ecf8427e
-// current file: ae4464472e898ba0bba8dc7302b157c0
-var_dump($ret, $mw->getDirMd5(), $mw->getFileCounter());
diff --git a/libs/file-utils/example/file-finder.php b/libs/file-utils/example/file-finder.php
deleted file mode 100644
index 3eead56..0000000
--- a/libs/file-utils/example/file-finder.php
+++ /dev/null
@@ -1,27 +0,0 @@
-files()->name('*.php')// ->ignoreVCS(false)
- // ->ignoreDotFiles(false)
- // ->exclude('tmp')
- ->notPath('tmp')->inDir(dirname(__DIR__));
-
-foreach ($finder as $file) {
- // var_dump($file);die;
- echo "+ {$file->getPathname()}\n";
-}
-
-// print_r($finder);
-// var_dump($finder->count());
diff --git a/libs/file-utils/src/Directory.php b/libs/file-utils/src/Directory.php
deleted file mode 100644
index 85f81f7..0000000
--- a/libs/file-utils/src/Directory.php
+++ /dev/null
@@ -1,400 +0,0 @@
-getFilename()[0] === '.') {
- * return false;
- * }
- * if ($current->isDir()) {
- * // Only recurse into intended subdirectories.
- * return $current->getFilename() !== '.git';
- * }
- * // Only consume files of interest.
- * return strpos($current->getFilename(), '.php') !== false;
- * };
- *
- * // $info is instance of \SplFileInfo
- * foreach(Directory::getRecursiveIterator($srcDir, $filter) as $info) {
- * // $info->getFilename(); ...
- * }
- * ```
- *
- * @param string $srcDir
- * @param callable $filter
- *
- * @return RecursiveIteratorIterator
- * @throws LogicException
- */
- public static function getRecursiveIterator($srcDir, callable $filter): RecursiveIteratorIterator
- {
- return self::getIterator($srcDir, $filter);
- }
-
- /**
- * 判断文件夹是否为空
- *
- * @param $dir
- *
- * @return bool
- * @throws FileSystemException
- */
- public static function isEmpty($dir): bool
- {
- $handler = opendir($dir);
-
- if (false === $handler) {
- throw new FileSystemException("Open the dir failure! DIR: $dir");
- }
-
- while (($file = readdir($handler)) !== false) {
-
- if ($file !== '.' && $file !== '..') {
- closedir($handler);
-
- return false;
- }
- }
-
- closedir($handler);
-
- return true;
- }
-
- /**
- * 查看一个目录中的所有文件和子目录
- *
- * @param $path
- *
- * @return array
- * @throws FileNotFoundException
- */
- public static function ls($path): array
- {
- $list = [];
-
- try {
- /*** class create new DirectoryIterator Object ***/
- foreach (new DirectoryIterator($path) as $item) {
- $list[] = $item;
- }
- /*** if an exception is thrown, catch it here ***/
- } catch (Exception $e) {
- throw new FileNotFoundException($path . ' 没有任何内容');
- }
-
- return $list;
- }
-
- /**
- * 只获得目录结构
- *
- * @param $path
- * @param int $pid
- * @param int $son
- * @param array $list
- *
- * @return array
- * @throws FileNotFoundException
- */
- public static function getList($path, $pid = 0, $son = 0, array $list = []): array
- {
- $path = self::pathFormat($path);
-
- if (!is_dir($path)) {
- throw new FileNotFoundException("directory not exists! DIR: $path");
- }
-
- static $id = 0;
-
- foreach (glob($path . '*') as $v) {
- if (is_dir($v)) {
- $id++;
-
- $list[$id]['id'] = $id;
- $list[$id]['pid'] = $pid;
- $list[$id]['name'] = basename($v);
- $list[$id]['path'] = realpath($v);
-
- //是否遍历子目录
- if ($son) {
- $list = self::getList($v, $id, $son, $list);
- }
- }
- }
-
- return $list;
- }
-
- /**
- * @param $path
- * @param bool $loop
- * @param null $parent
- * @param array $list
- *
- * @return array
- * @throws FileNotFoundException
- */
- public static function getDirs($path, $loop = 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);
-
- foreach (glob($path . '*') as $v) {
- if (is_dir($v)) {
- $relatePath = substr($v, $len);
- $list[] = $parent . $relatePath;
-
- //是否遍历子目录
- if ($loop) {
- $list = self::getDirs($v, $loop, $relatePath . '/', $list);
- }
- }
- }
-
- return $list;
- }
-
- /**
- * 获得目录下的文件,可选择类型、是否遍历子文件夹
- *
- * @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);
-
- if (!is_dir($dir)) {
- throw new FileNotFoundException("directory not exists! DIR: $dir");
- }
-
- // glob()寻找与模式匹配的文件路径 $file is pull path
- foreach (glob($dir . '*') as $file) {
-
- // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找
- if (is_file($file) && (!$ext || preg_match("/\.($ext)$/i", $file))) {
- //basename — 返回路径中的 文件名部分
- $list[] = basename($file);
-
- // is directory
- } else {
- $list[] = '/' . basename($file);
-
- if ($recursive) {
- $list = array_merge($list, self::simpleInfo($file, $ext, $recursive));
- }
- }
- }
-
- return $list;
- }
-
- /**
- * 获得目录下的文件,可选择类型、是否遍历子文件夹
- *
- * @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 {
- $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);
-
- foreach (glob($path . '*') as $v) {
- $relatePath = substr($v, $len);
-
- // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找
- if (is_file($v) && (!$ext || preg_match("/\.($ext)$/i", $v))) {
- $list[] = $parent . $relatePath;
-
- } elseif ($recursive) {
- $list = self::getFiles($v, $ext, $recursive, $relatePath . '/', $list);
- }
- }
-
- return $list;
- }
-
- /**
- * 获得目录下的文件以及详细信息,可选择类型、是否遍历子文件夹
- *
- * @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 FileNotFoundException
- */
- public static function getFilesInfo($path, $ext = null, $recursive = 0, &$list = []): array
- {
- $path = self::pathFormat($path);
-
- if (!is_dir($path)) {
- throw new FileNotFoundException("directory not exists! DIR: $path");
- }
-
- $ext = is_array($ext) ? implode('|', $ext) : trim($ext);
-
- static $id = 0;
-
- //glob()寻找与模式匹配的文件路径
- foreach (glob($path . '*') as $file) {
- $id++;
-
- // 匹配文件 如果没有传入$ext 则全部遍历,传入了则按传入的类型来查找
- if (is_file($file) && (!$ext || preg_match("/\.($ext)$/i", $file))) {
- $list[$id] = File::info($file);
-
- //是否遍历子目录
- } elseif ($recursive) {
- $list = self::getFilesInfo($file, $ext, $recursive, $list);
- }
- }
-
- return $list;
- }
-
- /**
- * 支持层级目录的创建
- *
- * @param $path
- * @param int|string $mode
- * @param bool $recursive
- *
- * @return bool
- */
- public static function create($path, $mode = 0775, $recursive = true): bool
- {
- return (is_dir($path) || !(!@mkdir($path, $mode, $recursive) && !is_dir($path))) && is_writable($path);
- }
-
- /**
- * 复制目录内容
- *
- * @param $oldDir
- * @param $newDir
- *
- * @return bool
- * @throws FileNotFoundException
- */
- public static function copy($oldDir, $newDir): bool
- {
- $oldDir = self::pathFormat($oldDir);
- $newDir = self::pathFormat($newDir);
-
- if (!is_dir($oldDir)) {
- throw new FileNotFoundException('复制失败:' . $oldDir . ' 不存在!');
- }
-
- $newDir = self::create($newDir);
-
- foreach (glob($oldDir . '*') as $v) {
- $newFile = $newDir . basename($v);//文件
-
- //文件存在,跳过复制它
- if (file_exists($newFile)) {
- continue;
- }
-
- if (is_dir($v)) {
- self::copy($v, $newFile);
- } else {
- copy($v, $newFile);//是文件就复制过来
- @chmod($newFile, 0664);// 权限 0777
- }
- }
-
- return true;
- }
-
- /**
- * 删除目录及里面的文件
- *
- * @param $path
- * @param boolean $delSelf 默认最后删掉自己
- *
- * @return bool
- */
- public static function delete($path, $delSelf = true): bool
- {
- $dirPath = self::pathFormat($path);
-
- if (is_file($dirPath)) {
- return unlink($dirPath);
- }
-
- foreach (glob($dirPath . '*') as $v) {
- is_dir($v) ? self::delete($v) : unlink($v);
- }
-
- $delSelf && rmdir($dirPath);//默认最后删掉自己
-
- return true;
- }
-}
diff --git a/libs/file-utils/src/Exception/FileNotFoundException.php b/libs/file-utils/src/Exception/FileNotFoundException.php
deleted file mode 100644
index 473ba29..0000000
--- a/libs/file-utils/src/Exception/FileNotFoundException.php
+++ /dev/null
@@ -1,21 +0,0 @@
- basename($filename), //文件名
- 'type' => filetype($filename), //类型
- 'size' => (filesize($filename) / 1000) . ' Kb', //大小
- 'is_write' => is_writable($filename) ? 'true' : 'false', //可写
- 'is_read' => is_readable($filename) ? 'true' : 'false',//可读
- 'update_time' => filectime($filename), //修改时间
- 'last_visit_time' => fileatime($filename), //文件的上次访问时间
- ];
- }
-
- /**
- * @param $filename
- *
- * @return array
- */
- public static function getStat($filename): array
- {
- return stat($filename);
- }
-
- /**
- * save description
- *
- * @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;
- }
-
- /**
- * @param $content
- * @param $path
- *
- * @throws IOException
- */
- public static function write($content, $path): void
- {
- $handler = static::openHandler($path);
-
- static::writeToFile($handler, $content);
-
- @fclose($handler);
- }
-
- /**
- * @param string $path
- *
- * @return resource
- * @throws IOException
- */
- public static function openHandler(string $path)
- {
- if (($handler = @fopen($path, 'wb')) === false) {
- throw new IOException('The file "' . $path . '" could not be opened for writing. Check if PHP has enough permissions.');
- }
-
- return $handler;
- }
-
- /**
- * 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).
- *
- * @throws IOException
- */
- public static function writeToFile($handler, string $content, string $path = ''): void
- {
- 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.');
- }
- }
-
- /**
- * ********************** 创建多级目录和多个文件 **********************
- * 结合上两个函数
- *
- * @param $fileData - 数组:要创建的多个文件名组成,含文件的完整路径
- * @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);
-
- //$fileName = basename($file); //文件名
-
- //检查文件是否存在
- if (!is_file($file)) {
- file_put_contents($file, $content, LOCK_EX);
- @chmod($file, $mode);
- } elseif ($append) {
- file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
- @chmod($file, $mode);
- }
- }
- }
-
- /**
- * @param string $file a file path or url path
- * @param bool|false $useIncludePath
- * @param null|resource $streamContext
- * @param int $curlTimeout
- *
- * @return bool|mixed|string
- * @throws FileNotFoundException
- * @throws FileReadException
- */
- public static function getContents(
- string $file,
- $useIncludePath = false,
- $streamContext = null,
- int $curlTimeout = 5
- ) {
- $isUrl = preg_match('/^https?:\/\//', $file);
-
- if (null === $streamContext && $isUrl) {
- $streamContext = @stream_context_create(['http' => ['timeout' => $curlTimeout]]);
- }
-
- 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!");
- }
-
- if (!is_readable($file)) {
- throw new FileReadException("File [{$file}] is not readable!");
- }
-
- return @file_get_contents($file, $useIncludePath, $streamContext);
- }
-
- // fetch remote content by url
- if (function_exists('curl_init')) {
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($curl, CURLOPT_URL, $file);
- curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
- curl_setopt($curl, CURLOPT_TIMEOUT, $curlTimeout);
- // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
-
- if (null !== $streamContext) {
- $opts = stream_context_get_options($streamContext);
-
- if (isset($opts['http']['method']) && strtolower($opts['http']['method']) === 'post') {
- curl_setopt($curl, CURLOPT_POST, true);
-
- if (isset($opts['http']['content'])) {
- parse_str($opts['http']['content'], $post_data);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
- }
- }
- }
-
- $content = curl_exec($curl);
- curl_close($curl);
-
- return $content;
- }
-
- return false;
- }
-
- /**
- * @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));
-
- if (static::copy($file, $target)) {
- unlink($file);
- }
- }
-
- /**
- * @param $filename
- *
- * @return bool
- * @throws InvalidArgumentException
- * @throws FileNotFoundException
- */
- public static function delete($filename): bool
- {
- return self::check($filename) && unlink($filename);
- }
-
- /**
- * @param $source
- * @param $destination
- * @param null $streamContext
- *
- * @return bool|int
- * @throws FileSystemException
- * @throws FileNotFoundException
- */
- public static function copy($source, $destination, $streamContext = null)
- {
- if (null === $streamContext && !preg_match('/^https?:\/\//', $source)) {
- if (!is_file($source)) {
- throw new FileSystemException("Source file don't exists. File: $source");
- }
-
- return copy($source, $destination);
- }
-
- return @file_put_contents($destination, self::getContents($source, false, $streamContext));
- }
-
- /**
- * @param $inFile
- * @param $outFile
- *
- * @return mixed
- * @throws InvalidArgumentException
- * @throws FileNotFoundException
- */
- public static function combine($inFile, $outFile)
- {
- self::check($inFile);
-
- $data = '';
- if (is_array($inFile)) {
- foreach ($inFile as $value) {
- if (is_file($value)) {
- $data .= trim(file_get_contents($value));
- } else {
- throw new FileNotFoundException('File: ' . $value . ' not exists!');
- }
- }
- }
-
- /*if (is_string($inFile) && is_file($value)) {
- $data .= trim( file_get_contents($inFile) );
- } else {
- Trigger::error('文件'.$value.'不存在!!');
- }*/
-
- $preg_arr = [
- '/\/\*.*?\*\/\s*/is', // 去掉所有多行注释/* .... */
- '/\/\/.*?[\r\n]/is', // 去掉所有单行注释//....
- '/(?!\w)\s*?(?!\w)/is' // 去掉空白行
- ];
-
- $data = preg_replace($preg_arr, '', $data);
- // $outFile = $outDir . Data::getRandStr(8) . '.' . $fileType;
-
- $fileData = [
- $outFile => $data
- ];
-
- self::createAndWrite($fileData);
-
- return $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')) {
- return $source;
- }
-
- $output = '';
- foreach (token_get_all($source) as $token) {
- if (is_string($token)) {
- $output .= $token;
- } 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
- $whitespace = preg_replace('{[ \t]+}', ' ', $token[1]);
- // normalize newlines to \n
- $whitespace = preg_replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
- // trim leading spaces
- $whitespace = preg_replace('{\n +}', "\n", $whitespace);
- $output .= $whitespace;
- } else {
- $output .= $token[1];
- }
- }
-
- return $output;
- }
-
- /**
- * 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
- */
- public static function downBigFile($file, $as): void
- {
- header('Expires: Mon, 1 Apr 1974 05:00:00 GMT');
- header('Pragma: no-cache');
- header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
- header('Content-Description: File Download');
- header('Content-Type: application/octet-stream');
- header('Content-Length: ' . trim(shell_exec('stat -c%s "$file"')));
- header('Content-Disposition: attachment; filename="' . $as . '"');
- header('Content-Transfer-Encoding: binary');
- //@readfile( $file );
-
- flush();
- $fp = popen('tail -c ' . trim(shell_exec('stat -c%s "$file"')) . ' ' . $file . ' 2>&1', 'r');
-
- while (!feof($fp)) {
- // send the current file part to the browser
- print fread($fp, 1024);
- // flush the content to the browser
- flush();
- }
-
- fclose($fp);
- }
-}
diff --git a/libs/file-utils/src/FileFinder.php b/libs/file-utils/src/FileFinder.php
deleted file mode 100644
index d6809a9..0000000
--- a/libs/file-utils/src/FileFinder.php
+++ /dev/null
@@ -1,737 +0,0 @@
-files()
- * ->name('*.php')
- * ->notName('some.php')
- * ->in('/path/to/project')
- * ;
- *
- * foreach($finder as $file) {
- * // something ......
- * }
- * ```
- *
- * @package Toolkit\File
- * @ref \Symfony\Component\Finder\Finder
- */
-final class FileFinder implements IteratorAggregate, Countable
-{
- public const ONLY_FILE = 1;
- public const ONLY_DIR = 2;
- public const IGNORE_VCS_FILES = 1;
- public const IGNORE_DOT_FILES = 2;
-
- /** @var array */
- private static $vcsPatterns = ['.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg'];
-
- /** @var int */
- private $mode = 0;
-
- /** @var int */
- private $ignore;
-
- /** @var bool */
- private $ignoreVcsAdded = false;
-
- /** @var array */
- private $dirs = [];
-
- /** @var array */
- private $names = [];
-
- /** @var array */
- private $notNames = [];
-
- /** @var array */
- private $paths = [];
-
- /** @var array */
- private $notPaths = [];
-
- /** @var array */
- private $excludes = [];
-
- /** @var array */
- private $filters = [];
-
- /** @var array */
- private $iterators = [];
-
- /** @var bool */
- private $followLinks = false;
-
- /**
- * @return FileFinder
- */
- public static function create(): self
- {
- return new self();
- }
-
- /**
- * @param array $config
- *
- * @return FileFinder
- */
- public static function fromArray(array $config): self
- {
- $finder = new self();
- $allowed = [
- 'names' => 'addNames',
- 'notNames' => 'addNotNames',
- 'paths' => 'addNotPaths',
- 'notPaths' => 'addNotPaths',
- 'exclude' => 'exclude',
- 'excludes' => 'exclude',
- ];
-
- foreach ($config as $prop => $values) {
- if ($values && isset($allowed[$prop])) {
- $method = $allowed[$prop];
- $finder->$method($values);
- }
- }
-
- return $finder;
- }
-
- /**
- * FileFinder constructor.
- */
- public function __construct()
- {
- $this->ignore = self::IGNORE_VCS_FILES | self::IGNORE_DOT_FILES;
- }
-
- /**
- * @return $this
- */
- public function directories(): self
- {
- $this->mode = self::ONLY_DIR;
-
- return $this;
- }
-
- /**
- * @return $this
- */
- public function dirs(): self
- {
- $this->mode = self::ONLY_DIR;
-
- return $this;
- }
-
- /**
- * @return FileFinder
- */
- public function files(): self
- {
- $this->mode = self::ONLY_FILE;
-
- return $this;
- }
-
- /**
- * $finder->name('*.php')
- * $finder->name('test.php')
- *
- * @param string $pattern
- *
- * @return FileFinder
- */
- public function name(string $pattern): self
- {
- $this->names[] = $pattern;
-
- return $this;
- }
-
- /**
- * @param string|array $patterns
- *
- * @return FileFinder
- */
- public function addNames($patterns): self
- {
- if ($patterns) {
- $this->names = array_merge($this->names, (array)$patterns);
- }
-
- return $this;
- }
-
- /**
- * @param string $pattern
- *
- * @return FileFinder
- */
- public function notName(string $pattern): self
- {
- $this->notNames[] = $pattern;
-
- return $this;
- }
-
- /**
- * @param string|array $patterns
- *
- * @return FileFinder
- */
- public function addNotNames($patterns): self
- {
- if ($patterns) {
- $this->notNames = array_merge($this->notNames, (array)$patterns);
- }
-
- return $this;
- }
-
- /**
- * $finder->path('some/special/dir')
- *
- * @param string $pattern
- *
- * @return FileFinder
- */
- public function path(string $pattern): self
- {
- $this->paths[] = $pattern;
-
- return $this;
- }
-
- /**
- * @param string|array $patterns
- *
- * @return FileFinder
- */
- public function addPaths($patterns): self
- {
- if ($patterns) {
- $this->paths = array_merge($this->paths, (array)$patterns);
- }
-
- return $this;
- }
-
- /**
- * @param string $pattern
- *
- * @return FileFinder
- */
- public function notPath(string $pattern): self
- {
- $this->notPaths[] = $pattern;
-
- return $this;
- }
-
- /**
- * @param string|array $patterns
- *
- * @return FileFinder
- */
- public function addNotPaths($patterns): self
- {
- if ($patterns) {
- $this->notPaths = array_merge($this->notPaths, (array)$patterns);
- }
-
- return $this;
- }
-
- /**
- * @param $dirs
- *
- * @return FileFinder
- */
- public function exclude($dirs): self
- {
- if ($dirs) {
- $this->excludes = array_merge($this->excludes, (array)$dirs);
- }
-
- return $this;
- }
-
- /**
- * @param bool $ignoreVCS
- *
- * @return self
- */
- public function ignoreVCS($ignoreVCS): self
- {
- if ($ignoreVCS) {
- $this->ignore |= static::IGNORE_VCS_FILES;
- } else {
- $this->ignore &= ~static::IGNORE_VCS_FILES;
- }
-
- return $this;
- }
-
- /**
- * @param bool $ignoreDotFiles
- *
- * @return FileFinder
- */
- public function ignoreDotFiles($ignoreDotFiles): self
- {
- if ($ignoreDotFiles) {
- $this->ignore |= static::IGNORE_DOT_FILES;
- } else {
- $this->ignore &= ~static::IGNORE_DOT_FILES;
- }
- return $this;
- }
-
- /**
- * @param bool $followLinks
- *
- * @return FileFinder
- */
- public function followLinks($followLinks = true): self
- {
- $this->followLinks = (bool)$followLinks;
-
- return $this;
- }
-
- /**
- * @param Closure $closure
- *
- * @return FileFinder
- */
- public function filter(Closure $closure): self
- {
- $this->filters[] = $closure;
-
- return $this;
- }
-
- /**
- * @param string|array $dirs
- *
- * @return $this
- */
- public function in($dirs): self
- {
- return $this->inDir($dirs);
- }
-
- /**
- * 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);
- }
-
- return $this;
- }
-
- /**
- * @param mixed $iterator
- *
- * @return $this
- * @throws InvalidArgumentException
- */
- public function append($iterator): self
- {
- if ($iterator instanceof IteratorAggregate) {
- $this->iterators[] = $iterator->getIterator();
- } elseif ($iterator instanceof Iterator) {
- $this->iterators[] = $iterator;
- } elseif ($iterator instanceof Traversable || is_array($iterator)) {
- $it = new ArrayIterator();
- foreach ($iterator as $file) {
- $it->append($file instanceof SplFileInfo ? $file : new SplFileInfo($file));
- }
- $this->iterators[] = $it;
- } else {
- throw new InvalidArgumentException('The argument type is error');
- }
-
- return $this;
- }
-
- /**
- * @return int
- */
- public function count(): int
- {
- return iterator_count($this->getIterator());
- }
-
- /**
- * @return bool
- */
- public function isFollowLinks(): bool
- {
- return $this->followLinks;
- }
-
- /**
- * Retrieve an external iterator
- *
- * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
- * @return Iterator|SplFileInfo[] An iterator
- * @throws LogicException
- */
- 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 (!$this->ignoreVcsAdded && self::IGNORE_VCS_FILES === (self::IGNORE_VCS_FILES & $this->ignore)) {
- $this->excludes = array_merge($this->excludes, self::$vcsPatterns);
- $this->ignoreVcsAdded = true;
- }
-
- if (self::IGNORE_DOT_FILES === (self::IGNORE_DOT_FILES & $this->ignore)) {
- $this->notNames[] = '.*';
- }
-
- if (1 === count($this->dirs) && 0 === count($this->iterators)) {
- return $this->findInDirectory($this->dirs[0]);
- }
-
- $iterator = new AppendIterator();
- foreach ($this->dirs as $dir) {
- $iterator->append($this->findInDirectory($dir));
- }
-
- foreach ($this->iterators as $it) {
- $iterator->append($it);
- }
-
- return $iterator;
- }
-
- /**
- * @param string $dir
- *
- * @return Iterator
- */
- private function findInDirectory(string $dir): Iterator
- {
- $flags = RecursiveDirectoryIterator::SKIP_DOTS;
-
- if ($this->followLinks) {
- $flags |= RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
- }
-
- $iterator = new class ($dir, $flags) extends RecursiveDirectoryIterator
- {
- private $rootPath;
- private $subPath;
- private $rewindable;
- private $directorySeparator = '/';
- private $ignoreUnreadableDirs;
-
- 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.');
- }
-
- $this->rootPath = $path;
- $this->ignoreUnreadableDirs = $ignoreUnreadableDirs;
- parent::__construct($path, $flags);
-
- if ('/' !== DIRECTORY_SEPARATOR && !($flags & self::UNIX_PATHS)) {
- $this->directorySeparator = DIRECTORY_SEPARATOR;
- }
- }
-
- public function current()
- {
- if (null === $subPathname = $this->subPath) {
- $subPathname = $this->subPath = (string)$this->getSubPath();
- }
-
- if ('' !== $subPathname) {
- $subPathname .= $this->directorySeparator;
- }
-
- $subPathname .= $this->getFilename();
-
- // $fileInfo = new \SplFileInfo($this->getPathname());
- $fileInfo = new SplFileInfo($this->rootPath . $this->directorySeparator . $subPathname);
- $fileInfo->relativePath = $this->subPath;
- $fileInfo->relativePathname = $subPathname;
-
- return $fileInfo;
- }
-
- public function getChildren()
- {
- try {
- $children = parent::getChildren();
-
- if ($children instanceof self) {
- $children->rootPath = $this->rootPath;
- $children->rewindable = &$this->rewindable;
- $children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs;
- }
-
- return $children;
- } catch (UnexpectedValueException $e) {
- if ($this->ignoreUnreadableDirs) {
- return new RecursiveArrayIterator([]);
- }
-
- throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
- }
- }
-
- public function rewind(): void
- {
- if (false === $this->isRewindable()) {
- return;
- }
-
- parent::rewind();
- }
-
- public function isRewindable()
- {
- if (null !== $this->rewindable) {
- return $this->rewindable;
- }
-
- if (false !== $stream = @opendir($this->getPath())) {
- $infoS = stream_get_meta_data($stream);
- closedir($stream);
-
- if ($infoS['seekable']) {
- return $this->rewindable = true;
- }
- }
-
- return $this->rewindable = false;
- }
- };
-
- // exclude directories
- if ($this->excludes) {
- $iterator = new class ($iterator, $this->excludes) extends FilterIterator implements RecursiveIterator
- {
- private $excludes;
- private $iterator;
-
- public function __construct(RecursiveIterator $iterator, array $excludes)
- {
- $this->excludes = array_flip($excludes);
- $this->iterator = $iterator;
-
- parent::__construct($iterator);
- }
-
- public function accept(): bool
- {
- $name = $this->current()->getFilename();
- return !($this->current()->isDir() && isset($this->excludes[$name]));
- }
-
- public function hasChildren(): bool
- {
- return $this->iterator->hasChildren();
- }
-
- public function getChildren()
- {
- $children = new self($this->iterator->getChildren(), []);
- $children->excludes = $this->excludes;
-
- return $children;
- }
- };
- }
-
- // create recursive iterator
- $iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
-
- // mode: find files or dirs
- if ($this->mode) {
- $iterator = new class ($iterator, $this->mode) extends FilterIterator
- {
- private $mode;
-
- public function __construct(Iterator $iterator, int $mode)
- {
- $this->mode = $mode;
- parent::__construct($iterator);
- }
-
- public function accept(): bool
- {
- $info = $this->current();
- if (FileFinder::ONLY_DIR === $this->mode && $info->isFile()) {
- return false;
- }
-
- if (FileFinder::ONLY_FILE === $this->mode && $info->isDir()) {
- return false;
- }
-
- return true;
- }
- };
- }
-
- if ($this->names || $this->notNames) {
- $iterator = new class ($iterator, $this->names, $this->notNames) extends FilterIterator
- {
- private $names;
- private $notNames;
-
- public function __construct(Iterator $iterator, array $names, array $notNames)
- {
- parent::__construct($iterator);
- $this->names = $names;
- $this->notNames = $notNames;
- }
-
- public function accept(): bool
- {
- $pathname = $this->current()->getFilename();
-
- foreach ($this->notNames as $not) {
- if (fnmatch($not, $pathname)) {
- return false;
- }
- }
-
- if ($this->names) {
- foreach ($this->names as $need) {
- if (fnmatch($need, $pathname)) {
- return true;
- }
- }
-
- return false;
- }
-
- return true;
- }
- };
- }
-
- if ($this->filters) {
- $iterator = new class ($iterator, $this->filters) extends FilterIterator
- {
- private $filters;
-
- public function __construct(Iterator $iterator, array $filters)
- {
- parent::__construct($iterator);
- $this->filters = $filters;
- }
-
- public function accept(): bool
- {
- $fileInfo = $this->current();
- foreach ($this->filters as $filter) {
- if (false === $filter($fileInfo)) {
- return false;
- }
- }
-
- return true;
- }
- };
- }
-
- if ($this->paths || $this->notPaths) {
- $iterator = new class ($iterator, $this->paths, $this->notPaths) extends FilterIterator
- {
- private $paths;
- private $notPaths;
-
- public function __construct(Iterator $iterator, array $paths, array $notPaths)
- {
- parent::__construct($iterator);
- $this->paths = $paths;
- $this->notPaths = $notPaths;
- }
-
- public function accept(): bool
- {
- $pathname = $this->current()->relativePathname;
-
- if ('\\' === DIRECTORY_SEPARATOR) {
- $pathname = str_replace('\\', '/', $pathname);
- }
-
- foreach ($this->notPaths as $not) {
- if (fnmatch($not, $pathname)) {
- return false;
- }
- }
-
- if ($this->paths) {
- foreach ($this->paths as $need) {
- if (fnmatch($need, $pathname)) {
- return true;
- }
- }
-
- return false;
- }
-
- return true;
- }
- };
- }
-
- return $iterator;
- }
-}
diff --git a/libs/file-utils/src/FileSystem.php b/libs/file-utils/src/FileSystem.php
deleted file mode 100644
index 9d640a0..0000000
--- a/libs/file-utils/src/FileSystem.php
+++ /dev/null
@@ -1,485 +0,0 @@
- 3 && ctype_alpha($file[0]) && $file[1] === ':' && strspn($file, '/\\', 2,
- 1)) || null !== parse_url($file, PHP_URL_SCHEME);
- }
-
- /**
- * 转换为标准的路径结构
- *
- * @param string $dirName
- *
- * @return string
- */
- public static function pathFormat(string $dirName): string
- {
- $dirName = (string)str_ireplace('\\', '/', trim($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
- {
- if (strpos($path, 'phar://') === 0) {
- $path = (string)substr($path, 7);
-
- if (strpos($path, '.phar')) {
- return preg_replace('//[\w-]+\.phar/', '', $path);
- }
- }
-
- return $path;
- }
-
- /**
- * 检查文件/夹/链接是否存在
- *
- * @param string $file 要检查的目标
- * @param null|string $type
- *
- * @return array|string
- */
- public static function exists(string $file, $type = null)
- {
- if (!$type) {
- return file_exists($file);
- }
-
- $ret = false;
-
- if ($type === 'file') {
- $ret = is_file($file);
- } elseif ($type === 'dir') {
- $ret = is_dir($file);
- } elseif ($type === 'link') {
- $ret = is_link($file);
- }
-
- return $ret;
- }
-
- /**
- * @param string $file
- * @param null|string|array $ext eg: 'jpg|gif'
- *
- * @throws FileNotFoundException
- * @throws InvalidArgumentException
- */
- public static function check(string $file, $ext = null): void
- {
- if (!$file || !file_exists($file)) {
- throw new FileNotFoundException("File {$file} not exists!");
- }
-
- if ($ext) {
- if (is_array($ext)) {
- $ext = implode('|', $ext);
- }
-
- if (preg_match("/\.($ext)$/i", $file)) {
- 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 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
- */
- public static function rename(string $origin, string $target, bool $overwrite = false): void
- {
- // we check that target does not exist
- if (!$overwrite && static::isReadable($target)) {
- throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target));
- }
-
- if (true !== rename($origin, $target)) {
- throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target));
- }
- }
-
- /**
- * 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) {
- throw new IOException('Could not check if file is readable because path length exceeds 258 characters.');
- }
-
- return is_readable($filename);
- }
-
- /**
- * Creates a directory recursively.
- *
- * @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
- {
- foreach (Arr::toIterator($dirs) as $dir) {
- if (is_dir($dir)) {
- continue;
- }
-
- if (!@mkdir($dir, $mode, true) && !is_dir($dir)) {
- $error = error_get_last();
-
- if (!is_dir($dir)) {
- // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one
- if ($error) {
- throw new IOException(sprintf('Failed to create "%s": %s.', $dir, $error['message']));
- }
-
- throw new IOException(sprintf('Failed to create "%s"', $dir));
- }
- }
- }
- }
-
- /**
- * 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
- *
- * @throws IOException When the change fail
- */
- public static function chmod($files, $mode, $umask = 0000, $recursive = false): void
- {
- foreach (Arr::toIterator($files) as $file) {
- if (true !== @chmod($file, $mode & ~$umask)) {
- throw new IOException(sprintf('Failed to chmod file "%s".', $file));
- }
-
- if ($recursive && is_dir($file) && !is_link($file)) {
- 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
- *
- * @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);
- }
-
- if (is_link($file) && function_exists('lchown')) {
- if (true !== lchown($file, $user)) {
- throw new IOException(sprintf('Failed to chown file "%s".', $file));
- }
- } elseif (true !== chown($file, $user)) {
- throw new IOException(sprintf('Failed to chown file "%s".', $file));
- }
- }
- }
-
- /**
- * @param string $srcDir
- * @param callable $filter
- *
- * @return RecursiveIteratorIterator
- * @throws InvalidArgumentException
- */
- public static function getIterator(string $srcDir, callable $filter): RecursiveIteratorIterator
- {
- if (!$srcDir || !file_exists($srcDir)) {
- throw new InvalidArgumentException('Please provide a exists source directory.');
- }
-
- $directory = new RecursiveDirectoryIterator($srcDir);
- $filterIterator = new RecursiveCallbackFilterIterator($directory, $filter);
-
- return new RecursiveIteratorIterator($filterIterator);
- }
-
- /**
- * @param $path
- * @param int $mode
- *
- * @return bool
- */
- public static function chmodDir(string $path, $mode = 0664): bool
- {
- if (!is_dir($path)) {
- return @chmod($path, $mode);
- }
-
- $dh = opendir($path);
- while (($file = readdir($dh)) !== false) {
- if ($file !== '.' && $file !== '..') {
- $fullPath = $path . '/' . $file;
- if (is_link($fullPath)) {
- return false;
- }
-
- if (!is_dir($fullPath) && !@chmod($fullPath, $mode)) {
- return false;
- }
-
- if (!self::chmodDir($fullPath, $mode)) {
- return false;
- }
- }
- }
-
- closedir($dh);
-
- return @chmod($path, $mode) ? true : false;
- }
-
- /**
- * @param string $dir
- *
- * @return string
- */
- public static function availableSpace(string $dir = '.'): string
- {
- $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);
-
- //echo $bytes . '
';
-
- // pow($base, $class)
- return sprintf('%1.2f', $bytes / ($base ** $class)) . ' ' . $suffix[$class];
- }
-
- /**
- * @param string $dir
- *
- * @return string
- */
- public static function countSpace(string $dir = '.'): string
- {
- $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);
-
- // pow($base, $class)
- return sprintf('%1.2f', $bytes / ($base ** $class)) . ' ' . $suffix[$class];
- }
-
- /**
- * 文件或目录权限检查函数
- *
- * @from web
- * @access public
- *
- * @param string $file_path 文件路径
- *
- * @return int 返回值的取值范围为{0 <= x <= 15},每个值表示的含义可由四位二进制数组合推出。
- * 返回值在二进制计数法中,四位由高到低分别代表
- * 可执行rename()函数权限 |可对文件追加内容权限 |可写入文件权限|可读取文件权限。
- */
- public static function pathModeInfo(string $file_path): int
- {
- /* 如果不存在,则不可读、不可写、不可改 */
- if (!file_exists($file_path)) {
- return false;
- }
-
- $mark = 0;
-
- if (0 === stripos(PHP_OS, 'WIN')) {
- /* 测试文件 */
- $test_file = $file_path . '/cf_test.txt';
-
- /* 如果是目录 */
- if (is_dir($file_path)) {
- /* 检查目录是否可读 */
- $dir = @opendir($file_path);
-
- //如果目录打开失败,直接返回目录不可修改、不可写、不可读
- if ($dir === false) {
- return $mark;
- }
-
- //目录可读 001,目录不可读 000
- if (@readdir($dir) !== false) {
- $mark ^= 1;
- }
-
- @closedir($dir);
-
- /* 检查目录是否可写 */
- $fp = @fopen($test_file, 'wb');
-
- //如果目录中的文件创建失败,返回不可写。
- if ($fp === false) {
- return $mark;
- }
-
- //目录可写可读 011,目录可写不可读 010
- if (@fwrite($fp, 'directory access testing.') !== false) {
- $mark ^= 2;
- }
-
- @fclose($fp);
- @unlink($test_file);
-
- /* 检查目录是否可修改 */
- $fp = @fopen($test_file, 'ab+');
- if ($fp === false) {
- return $mark;
- }
-
- if (@fwrite($fp, "modify test.\r\n") !== false) {
- $mark ^= 4;
- }
-
- @fclose($fp);
-
- /* 检查目录下是否有执行rename()函数的权限 */
- if (@rename($test_file, $test_file) !== false) {
- $mark ^= 8;
- }
-
- @unlink($test_file);
-
- /* 如果是文件 */
- } elseif (is_file($file_path)) {
- /* 以读方式打开 */
- $fp = @fopen($file_path, 'rb');
- if ($fp) {
- $mark ^= 1; //可读 001
- }
-
- @fclose($fp);
-
- /* 试着修改文件 */
- $fp = @fopen($file_path, 'ab+');
- if ($fp && @fwrite($fp, '') !== false) {
- $mark ^= 6; //可修改可写可读 111,不可修改可写可读011...
- }
-
- @fclose($fp);
-
- /* 检查目录下是否有执行rename()函数的权限 */
- if (@rename($test_file, $test_file) !== false) {
- $mark ^= 8;
- }
- }
- } else {
- if (@is_readable($file_path)) {
- $mark ^= 1;
- }
-
- if (@is_writable($file_path)) {
- $mark ^= 14;
- }
- }
-
- return $mark;
- }
-}
diff --git a/libs/file-utils/src/ModifyWatcher.php b/libs/file-utils/src/ModifyWatcher.php
deleted file mode 100644
index d3c724c..0000000
--- a/libs/file-utils/src/ModifyWatcher.php
+++ /dev/null
@@ -1,320 +0,0 @@
-idFile = $idFile;
- }
- }
-
- /**
- * @param string $idFile
- *
- * @return $this
- */
- public function setIdFile(string $idFile): self
- {
- $this->idFile = $idFile;
-
- return $this;
- }
-
- /**
- * @param string|array $notNames
- *
- * @return ModifyWatcher
- */
- public function name($notNames): self
- {
- $this->notNames = array_merge($this->notNames, (array)$notNames);
-
- return $this;
- }
-
- /**
- * @param string|array $notNames
- *
- * @return ModifyWatcher
- */
- public function notName($notNames): self
- {
- $this->notNames = array_merge($this->notNames, (array)$notNames);
-
- return $this;
- }
-
- /**
- * @param string|array $excludeDirs
- *
- * @return ModifyWatcher
- */
- public function exclude($excludeDirs): self
- {
- $this->excludes = array_merge($this->excludes, (array)$excludeDirs);
-
- return $this;
- }
-
- /**
- * @param bool $ignoreDotDirs
- *
- * @return ModifyWatcher
- */
- public function ignoreDotDirs($ignoreDotDirs): ModifyWatcher
- {
- $this->ignoreDotDirs = (bool)$ignoreDotDirs;
-
- return $this;
- }
-
- /**
- * @param bool $ignoreDotFiles
- *
- * @return ModifyWatcher
- */
- public function ignoreDotFiles($ignoreDotFiles): ModifyWatcher
- {
- $this->ignoreDotFiles = (bool)$ignoreDotFiles;
- return $this;
- }
-
- /**
- * @param string|array $dirs
- *
- * @return $this
- */
- public function watch($dirs): self
- {
- $this->watchDirs = array_merge($this->watchDirs, (array)$dirs);
-
- return $this;
- }
-
- /**
- * alias of the watch()
- *
- * @param string|array $dirs
- *
- * @return $this
- */
- public function watchDir($dirs): self
- {
- $this->watchDirs = array_merge($this->watchDirs, (array)$dirs);
-
- return $this;
- }
-
- /**
- * @return bool
- */
- public function isModified(): bool
- {
- return $this->isChanged();
- }
-
- /**
- * @return bool
- */
- public function isChanged(): bool
- {
- if (!$this->idFile) {
- $this->idFile = Sys::getTempDir() . '/' . md5(json_encode($this->watchDirs)) . '.id';
- }
-
- // get old hash id
- if (!($old = $this->dirMd5) && (!$old = $this->getMd5ByIdFile())) {
- $this->calcMd5Hash();
-
- return false;
- }
-
- $this->calcMd5Hash();
-
- return $this->dirMd5 !== $old;
- }
-
- /**
- * @return bool|string
- */
- public function getMd5ByIdFile()
- {
- if (!$file = $this->idFile) {
- return false;
- }
-
- if (!is_file($file)) {
- return false;
- }
-
- return trim(file_get_contents($file));
- }
-
- /**
- * @return string
- */
- public function calcMd5Hash(): string
- {
- if (!$this->watchDirs) {
- 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->md5String = null;
-
- if ($this->idFile) {
- file_put_contents($this->idFile, $this->dirMd5);
- }
-
- return $this->dirMd5;
- }
-
- /**
- * @param string $watchDir
- */
- private function collectDirMd5(string $watchDir): void
- {
- $files = scandir($watchDir, 0);
-
- foreach ($files as $f) {
- if ($f === '.' || $f === '..') {
- continue;
- }
-
- $path = $watchDir . '/' . $f;
-
- // 递归目录
- if (is_dir($path)) {
- if ($this->ignoreDotDirs && $f[0] === '.') {
- continue;
- }
-
- if (in_array($f, $this->excludes, true)) {
- continue;
- }
-
- $this->collectDirMd5($path);
-
- continue;
- }
-
- // 检测文件
- foreach ($this->notNames as $name) {
- if (preg_match('#' . $name . '#', $name)) {
- continue;
- }
- }
-
- if ($this->names) {
- foreach ($this->names as $name) {
- if (preg_match('#' . $name . '#', $name)) {
- $this->md5String .= md5_file($path);
- $this->fileCounter++;
- }
- }
- } else {
- $this->md5String .= md5_file($path);
- $this->fileCounter++;
- }
- }
- }
-
- /**
- * @return string
- */
- public function getIdFile(): string
- {
- return $this->idFile;
- }
-
- /**
- * @return string[]
- */
- public function getWatchDir(): array
- {
- return $this->watchDirs;
- }
-
- /**
- * @return string
- */
- public function getDirMd5(): string
- {
- return $this->dirMd5;
- }
-
- /**
- * @return int
- */
- public function getFileCounter(): int
- {
- return $this->fileCounter;
- }
-}
diff --git a/libs/file-utils/src/ReadTrait.php b/libs/file-utils/src/ReadTrait.php
deleted file mode 100644
index 60ad167..0000000
--- a/libs/file-utils/src/ReadTrait.php
+++ /dev/null
@@ -1,290 +0,0 @@
-=5.1.0)
- if (class_exists('SplFileObject', false)) {
- $count = $endLine - $startLine;
-
- try {
- $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) {
- throw new FileSystemException("Error on read the file '{$fileName}'. ERR: " . $e->getMessage());
- }
-
- } else { // PHP<5.1
- if (!$fp = fopen($fileName, $mode)) {
- throw new FileSystemException('can not open the file:' . $fileName);
- }
-
- // 移动指针 跳过前$startLine行
- for ($i = 1; $i < $startLine; ++$i) {
- fgets($fp);
- }
-
- // 读取文件行内容
- for (; $i <= $endLine; ++$i) {
- $content[] = fgets($fp);
- }
-
- fclose($fp);
- }
-
- return $content;
- }
-
- /**
- * symmetry 得到当前行对称上下几($lineNum)行的内容
- *
- * @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;
-
- if ((int)$current < ($lineNum + 1)) {
- $startLine = 1;
- $endLine = 9;
- }
-
- return self::readLines($fileName, $startLine, $endLine);
- }
-
- /**
- * @param string $file
- * @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;
-
- return self::readLines($file, $startLine, $endLine);
- }
-
- /**
- * 得到基准行数上5行下3行的内容, lines up and down
- *
- * @param string $file
- * @param int $baseLine 基准行数
- *
- * @return array
- * @throws FileSystemException
- */
- public static function getLines5u3d(string $file, int $baseLine = 1): array
- {
- return self::readRangeLines($file, $baseLine, 5);
- }
-
- /**
- * 读取文件的最后几行(支持大文件读取)
- *
- * @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);
-
- $pos = $n + 1;
- $lines = [];
-
- while (count($lines) <= $n) {
- try {
- fseek($fp, -$pos, SEEK_END);
- } catch (Exception $e) {
- fclose($fp);
- break;
- }
-
- $pos *= $base;
-
- while (!feof($fp)) {
- array_unshift($lines, fgets($fp));
- }
- }
-
- return array_slice($lines, 0, $n);
- }
-}
diff --git a/libs/file-utils/test/boot.php b/libs/file-utils/test/boot.php
deleted file mode 100644
index dccabf2..0000000
--- a/libs/file-utils/test/boot.php
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
-
-
- test
-
-
-
-
-
- src
-
-
-
diff --git a/libs/obj-utils/.gitignore b/libs/obj-utils/.gitignore
deleted file mode 100644
index 86318a0..0000000
--- a/libs/obj-utils/.gitignore
+++ /dev/null
@@ -1,10 +0,0 @@
-.idea/
-.phpintel/
-!README.md
-!.gitkeep
-composer.lock
-*.swp
-*.log
-*.pid
-*.patch
-.DS_Store
diff --git a/libs/obj-utils/LICENSE b/libs/obj-utils/LICENSE
deleted file mode 100644
index d839cdc..0000000
--- a/libs/obj-utils/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2016 inhere
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/libs/obj-utils/README.md b/libs/obj-utils/README.md
deleted file mode 100644
index 1f2a6a2..0000000
--- a/libs/obj-utils/README.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# object utils
-
-[](LICENSE)
-[](https://packagist.org/packages/toolkit/obj-utils)
-[](https://packagist.org/packages/toolkit/obj-utils)
-
-Some useful object utils for the php.
-
-## Install
-
-```bash
-composer require toolkit/obj-utils
-```
-
-## License
-
-MIT
diff --git a/libs/obj-utils/composer.json b/libs/obj-utils/composer.json
deleted file mode 100644
index ec77810..0000000
--- a/libs/obj-utils/composer.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "name": "toolkit/obj-utils",
- "type": "library",
- "description": "some object tool library of the php",
- "keywords": [
- "library",
- "tool",
- "php"
- ],
- "homepage": "https://github.com/php-toolkit/obj-utils",
- "license": "MIT",
- "authors": [
- {
- "name": "inhere",
- "email": "in.798@qq.com",
- "homepage": "http://www.yzone.net/"
- }
- ],
- "require": {
- "php": ">7.1.0"
- },
- "autoload": {
- "psr-4": {
- "Toolkit\\ObjUtil\\": "src/"
- }
- },
- "suggest": {
- "inhere/php-validate": "Very lightweight data validate tool",
- "inhere/console": "a lightweight php console application library."
- },
- "scripts": {
- "test": "phpunit test"
- }
-}
diff --git a/libs/obj-utils/phpunit.xml.dist b/libs/obj-utils/phpunit.xml.dist
deleted file mode 100644
index 6052813..0000000
--- a/libs/obj-utils/phpunit.xml.dist
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
- test/
-
-
-
-
-
- src
-
-
-
diff --git a/libs/obj-utils/src/Configurable.php b/libs/obj-utils/src/Configurable.php
deleted file mode 100644
index f6d8176..0000000
--- a/libs/obj-utils/src/Configurable.php
+++ /dev/null
@@ -1,43 +0,0 @@
-init();
- }
-
- /**
- * init
- */
- protected function init(): void
- {
- // init something ...
- }
-}
diff --git a/libs/obj-utils/src/Exception/GetPropertyException.php b/libs/obj-utils/src/Exception/GetPropertyException.php
deleted file mode 100644
index b829696..0000000
--- a/libs/obj-utils/src/Exception/GetPropertyException.php
+++ /dev/null
@@ -1,20 +0,0 @@
- $value) {
- if (is_numeric($property)) {
- continue;
- }
-
- $setter = 'set' . ucfirst($property);
-
- // has setter
- if (method_exists($object, $setter)) {
- $object->$setter($value);
- } elseif (property_exists($object, $property)) {
- $object->$property = $value;
- }
- }
-
- return $object;
- }
-
- /**
- * 给对象设置属性值
- *
- * @param $object
- * @param array $options
- */
- public static function configure($object, array $options): void
- {
- foreach ($options as $property => $value) {
- if (property_exists($object, $property)) {
- $object->$property = $value;
- }
- }
- }
-
- /**
- * 给对象设置属性值
- *
- * @param $object
- * @param array $options
- */
- public static function setAttrs($object, array $options): void
- {
- self::configure($object, $options);
- }
-
- /**
- * 定义一个用来序列化数据的函数
- *
- * @param mixed $obj
- *
- * @return string
- */
- public static function encode($obj): string
- {
- 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]);
- }
-
- /**
- * php对象转换成为数组
- *
- * @param iterable|array|Traversable $data
- * @param bool $recursive
- *
- * @return array|bool
- */
- 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')) {
- $arr = $data->toArray();
- }
- } else {
- $arr = (array)$data;
- }
-
- if ($recursive) {
- foreach ($arr as $key => $value) {
- if (is_array($value) || is_object($value)) {
- $arr[$key] = static::toArray($value, $recursive);
- }
- }
- }
-
- return $arr;
- }
-
- /**
- * @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 ($unique) {
- $hash = md5($hash);
- }
-
- return $hash;
- }
-
- // a class
- 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
- *
- * @return array
- * @throws RuntimeException
- * @throws ReflectionException
- */
- public static function getMethodArgs(ReflectionMethod $method, array $extraArgs = []): array
- {
- $methodArgs = [];
-
- foreach ($method->getParameters() as $idx => $param) {
- // if user have been provide arg
- if (isset($extraArgs[$idx])) {
- $methodArgs[] = $extraArgs[$idx];
- continue;
- }
-
- $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();
- $depObject = self::create($depClass);
-
- if ($depObject instanceof $depClass) {
- $methodArgs[] = $depObject;
- continue;
- }
- }
-
- // Finally, if there is a default parameter, use it.
- if ($param->isOptional()) {
- $methodArgs[] = $param->getDefaultValue();
- continue;
- }
-
- // $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()));
- }
-
- return $methodArgs;
- }
-
- /**
- * 从类名创建服务实例对象,会尽可能自动补完构造函数依赖
- *
- * @from windWalker https://github.com/ventoviro/windwalker
- *
- * @param string $class a className
- *
- * @return mixed
- * @throws RuntimeException
- */
- public static function create(string $class)
- {
- try {
- $reflection = new ReflectionClass($class);
- } catch (ReflectionException $e) {
- return false;
- }
-
- $constructor = $reflection->getConstructor();
-
- // If there are no parameters, just return a new object.
- if (null === $constructor) {
- return new $class;
- }
-
- $newInstanceArgs = self::getMethodArgs($constructor);
-
- // Create a callable for the dataStorage
- return $reflection->newInstanceArgs($newInstanceArgs);
- }
-
- /**
- * @param string|array $config
- *
- * @return mixed
- */
- public static function smartCreate($config)
- {
- if (is_string($config)) {
- return new $config;
- }
-
- if (is_array($config) && !empty($config['class'])) {
- $class = $config['class'];
- $args = $config[0] ?? [];
-
- $obj = new $class(...$args);
-
- unset($config['class'], $config[0]);
- return self::init($obj, $config);
- }
-
- return null;
- }
-}
diff --git a/libs/obj-utils/src/Traits/ArrayAccessByGetterSetterTrait.php b/libs/obj-utils/src/Traits/ArrayAccessByGetterSetterTrait.php
deleted file mode 100644
index c23bed0..0000000
--- a/libs/obj-utils/src/Traits/ArrayAccessByGetterSetterTrait.php
+++ /dev/null
@@ -1,83 +0,0 @@
-$getter();
- }
-
- return null;
- }
-
- /**
- * Sets an offset in the iterator.
- *
- * @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)) {
- $this->$setter($value);
- }
- }
-
- /**
- * Unset an offset in the iterator.
- *
- * @param mixed $offset The array offset.
- *
- * @return void
- */
- public function offsetUnset($offset): void
- {
- // unset($this->$offset);
- }
-}
diff --git a/libs/obj-utils/src/Traits/ArrayAccessByPropertyTrait.php b/libs/obj-utils/src/Traits/ArrayAccessByPropertyTrait.php
deleted file mode 100644
index dfb8194..0000000
--- a/libs/obj-utils/src/Traits/ArrayAccessByPropertyTrait.php
+++ /dev/null
@@ -1,74 +0,0 @@
-$offset;
- }
-
- /**
- * Sets an offset in the iterator.
- *
- * @param mixed $offset The array offset.
- * @param mixed $value The array value.
- *
- * @return void
- */
- public function offsetSet($offset, $value): void
- {
- $this->$offset = $value;
- }
-
- /**
- * Unset an offset in the iterator.
- *
- * @param mixed $offset The array offset.
- *
- * @return void
- */
- public function offsetUnset($offset): void
- {
- // unset($this->$offset);
- }
-}
diff --git a/libs/obj-utils/src/Traits/ObjectPoolTrait.php b/libs/obj-utils/src/Traits/ObjectPoolTrait.php
deleted file mode 100644
index d91c041..0000000
--- a/libs/obj-utils/src/Traits/ObjectPoolTrait.php
+++ /dev/null
@@ -1,128 +0,0 @@
- \SplStack]
- */
- private static $pool = [];
-
- /**
- * @param string $class
- *
- * @return mixed
- */
- public static function get(string $class)
- {
- $stack = self::getStack($class);
-
- if (!$stack->isEmpty()) {
- return $stack->shift();
- }
-
- return new $class;
- }
-
- /**
- * @param stdClass|string $object
- */
- public static function put($object): void
- {
- if (is_string($object)) {
- $object = new $object;
- }
-
- self::getStack($object)->push($object);
- }
-
- /**
- * @param string $class
- * @param Closure $handler
- *
- * @return mixed
- */
- public static function use($class, Closure $handler)
- {
- $obj = self::get($class);
-
- $ret = $handler($obj);
-
- self::put($obj);
-
- return $ret;
- }
-
- /**
- * @param string|stdClass $class
- *
- * @return SplStack
- */
- public static function getStack($class): SplStack
- {
- $class = is_string($class) ? $class : get_class($class);
-
- if (!isset(self::$pool[$class])) {
- self::$pool[$class] = new SplStack();
- }
-
- return self::$pool[$class];
- }
-
- /**
- * @param null $class
- *
- * @return int
- * @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");
- }
-
- return self::$pool[$class]->count();
- }
-
- return count(self::$pool);
- }
-
- /**
- * @param null $class
- *
- * @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");
- }
-
- unset(self::$pool[$class]);
- } else {
- self::$pool = [];
- }
- }
-}
diff --git a/libs/obj-utils/src/Traits/PropertyAccessByGetterSetterTrait.php b/libs/obj-utils/src/Traits/PropertyAccessByGetterSetterTrait.php
deleted file mode 100644
index f709109..0000000
--- a/libs/obj-utils/src/Traits/PropertyAccessByGetterSetterTrait.php
+++ /dev/null
@@ -1,108 +0,0 @@
-$setter($value);
- } 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}");
- }
- }
-
- /**
- * @reference yii2 yii\base\Object::__set()
- *
- * @param $name
- *
- * @return mixed
- * @throws GetPropertyException
- */
- public function __get($name)
- {
- $getter = 'get' . ucfirst($name);
-
- 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}");
- }
-
- 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)) {
- return $this->$getter() !== null;
- }
-
- return false;
- }
-
- /**
- * @param $name
- *
- * @throws PropertyException
- */
- public function __unset($name)
- {
- $setter = 'set' . ucfirst($name);
-
- if (method_exists($this, $setter)) {
- $this->$setter(null);
-
- return;
- }
-
- 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
deleted file mode 100644
index 68e282a..0000000
--- a/libs/obj-utils/src/Traits/SingletonTrait.php
+++ /dev/null
@@ -1,31 +0,0 @@
-init();
- }
-
- /**
- * init
- */
- protected function init(): void
- {
- // init something ...
- }
-
- /**
- * @param string $method
- * @param $args
- *
- * @return mixed
- * @throws InvalidArgumentException
- */
- public function __call($method, array $args)
- {
- // if (method_exists($this, $method) && $this->isAllowCall($method) ) {
- // return call_user_func_array( array($this, $method), (array) $args);
- // }
-
- throw new InvalidArgumentException('Called a Unknown method! ' . get_class($this) . "->{$method}()");
- }
-
- /**
- * @param string $method
- * @param $args
- *
- * @return mixed
- * @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);
- }
-
- throw new InvalidArgumentException('Called a Unknown static method! [ ' . self::class . "::{$method}()]");
- }
-}
diff --git a/libs/obj-utils/test/boot.php b/libs/obj-utils/test/boot.php
deleted file mode 100644
index 01ff8b9..0000000
--- a/libs/obj-utils/test/boot.php
+++ /dev/null
@@ -1,27 +0,0 @@
-7.1.0"
- },
- "autoload": {
- "psr-4": {
- "Toolkit\\PhpUtil\\": "src/"
- }
- },
- "suggest": {
- "inhere/php-validate": "Very lightweight data validate tool",
- "inhere/console": "a lightweight php console application library."
- }
-}
diff --git a/libs/php-utils/example/property_exists.php b/libs/php-utils/example/property_exists.php
deleted file mode 100644
index 8d86234..0000000
--- a/libs/php-utils/example/property_exists.php
+++ /dev/null
@@ -1,36 +0,0 @@
-prop1;
- }
-}
-
-
-echo "use class:\n";
-
-echo 'public: ' . (property_exists(Some::class, 'prop0') ? 'Y' : 'N') . PHP_EOL;
-echo 'private: ' . (property_exists(Some::class, 'prop1') ? 'Y' : 'N') . PHP_EOL;
-echo 'protected: ' . (property_exists(Some::class, 'prop2') ? 'Y' : 'N') . PHP_EOL;
-echo "use object:\n";
-
-$object = new Some();
-
-echo 'public: ' . (property_exists($object, 'prop0') ? 'Y' : 'N') . PHP_EOL;
-echo 'private: ' . (property_exists($object, 'prop1') ? 'Y' : 'N') . PHP_EOL;
-echo 'protected: ' . (property_exists($object, 'prop2') ? 'Y' : 'N') . PHP_EOL;
diff --git a/libs/php-utils/phpunit.xml.dist b/libs/php-utils/phpunit.xml.dist
deleted file mode 100644
index 6052813..0000000
--- a/libs/php-utils/phpunit.xml.dist
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
- test/
-
-
-
-
-
- src
-
-
-
diff --git a/libs/php-utils/src/AutoLoader.php b/libs/php-utils/src/AutoLoader.php
deleted file mode 100644
index a19099d..0000000
--- a/libs/php-utils/src/AutoLoader.php
+++ /dev/null
@@ -1,365 +0,0 @@
-addPsr4Map([
- * 'namespace' => 'path'
- * ]);
- * $loader->addClassMap([
- * 'name' => 'file'
- * ]);
- * ```
- */
-class AutoLoader
-{
- /**
- * @var self
- */
- private static $loader;
-
- /**
- * @var array
- */
- private static $files = [];
-
- /**
- * @var array
- * array (
- * 'prefix' => 'dir path'
- * )
- */
- private $psr0Map = [];
-
- /**
- * @var array
- * array (
- * 'prefix' => 'dir path'
- * )
- */
- private $psr4Map = [];
-
- /**
- * @var array
- */
- private $classMap = [];
-
- /**
- * @var array
- */
- private $missingClasses = [];
-
- /**
- * @param array $files
- *
- * @return self
- */
- public static function getLoader(array $files = []): self
- {
- if (null !== self::$loader) {
- return self::$loader;
- }
-
- if ($files) {
- self::addFiles($files);
- }
-
- self::$loader = $loader = new self();
-
- $loader->register(true);
-
- foreach (self::$files as $fileIdentifier => $file) {
- _globalIncludeFile($fileIdentifier, $file);
- }
-
- return $loader;
- }
-
- /**************************************************************************
- * independent files
- *************************************************************************/
-
- /**
- * @return array
- */
- public static function getFiles(): array
- {
- return self::$files;
- }
-
- /**
- * @param array $files
- */
- public static function setFiles(array $files): void
- {
- self::$files = $files;
- }
-
- /**
- * @param array $files
- */
- public static function addFiles(array $files): void
- {
- if (self::$files) {
- self::$files = array_merge(self::$files, $files);
- } else {
- self::$files = $files;
- }
- }
-
- /**************************************************************************
- * class loader
- *************************************************************************/
-
- /**
- * @param string $prefix
- * @param string $path
- */
- public function addPsr0(string $prefix, string $path): void
- {
- $this->psr0Map[$prefix] = $path;
- }
-
- /**
- * @param array $psr0Map Class to filename map
- */
- public function addPsr0Map(array $psr0Map): void
- {
- if ($this->psr0Map) {
- $this->psr0Map = array_merge($this->psr0Map, $psr0Map);
- } else {
- $this->psr0Map = $psr0Map;
- }
- }
-
- /**
- * @param string $prefix
- * @param string $path
- *
- * @throws InvalidArgumentException
- */
- public function addPsr4(string $prefix, string $path): void
- {
- // Register directories for a new namespace.
- $length = strlen($prefix);
-
- if ('\\' !== $prefix[$length - 1]) {
- throw new InvalidArgumentException('A non-empty PSR-4 prefix must end with a namespace separator.');
- }
-
- $this->psr4Map[$prefix] = $path;
- }
-
- /**
- * @param array $psr4Map Class to filename map
- */
- public function addPsr4Map(array $psr4Map): void
- {
- if ($this->psr4Map) {
- $this->psr4Map = array_merge($this->psr4Map, $psr4Map);
- } else {
- $this->psr4Map = $psr4Map;
- }
- }
-
- /**
- * @return array
- */
- public function getPsr4Map(): array
- {
- return $this->psr4Map;
- }
-
- /**
- * @param array $psr4Map
- */
- public function setPsr4Map($psr4Map): void
- {
- $this->psr4Map = $psr4Map;
- }
-
- /**
- * @return array
- */
- public function getClassMap(): array
- {
- return $this->classMap;
- }
-
- /**
- * @param array $classMap
- */
- public function setClassMap(array $classMap): void
- {
- $this->classMap = $classMap;
- }
-
- /**
- * @param array $classMap Class to filename map
- */
- public function addClassMap(array $classMap): void
- {
- if ($this->classMap) {
- $this->classMap = array_merge($this->classMap, $classMap);
- } else {
- $this->classMap = $classMap;
- }
- }
-
- /**
- * 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);
- }
-
- /**
- * Un-registers this instance as an autoloader.
- */
- public function unRegister(): void
- {
- spl_autoload_unregister([$this, 'loadClass']);
- }
-
- /**
- * Loads the given class or interface.
- *
- * @param string $class The name of the class
- *
- * @return bool|null True if loaded, null otherwise
- */
- public function loadClass(string $class): ?bool
- {
- if ($file = $this->findFile($class)) {
- _includeClassFile($file);
- return true;
- }
-
- return null;
- }
-
- /**
- * 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 map lookup
- if (isset($this->classMap[$class])) {
- return $this->classMap[$class];
- }
-
- $file = $this->findFileWithExtension($class, '.php');
-
- if (false === $file) {
- // Remember that this class does not exist.
- $this->missingClasses[$class] = true;
- }
-
- return $file;
- }
-
- /**
- * @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;
-
- // PSR-4
- foreach ($this->psr4Map as $prefix => $dir) {
- if (0 === strpos($class, $prefix)) {
- $length = strlen($prefix);
-
- if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
- return $file;
- }
- }
- }
-
- // PEAR-like class name
- $logicalPathPsr0 = str_replace('_', DIRECTORY_SEPARATOR, $class) . $ext;
-
- foreach ($this->psr0Map as $prefix => $dir) {
- if (0 === strpos($class, $prefix)) {
- $file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0;
-
- if (file_exists($file)) {
- return $file;
- }
- }
- }
-
- return false;
- }
-
- /**
- * @return array
- */
- public function getMissingClasses(): array
- {
- return $this->missingClasses;
- }
-}
-
-function _globalIncludeFile($fileIdentifier, $file)
-{
- if (empty($GLOBALS['__global_autoload_files'][$fileIdentifier])) {
- require $file;
-
- $GLOBALS['__global_autoload_files'][$fileIdentifier] = true;
- }
-}
-
-/**
- * Scope isolated include.
- * Prevents access to $this/self from included files.
- *
- * @param $file
- */
-function _includeClassFile($file)
-{
- include $file;
-}
-
diff --git a/libs/php-utils/src/Php.php b/libs/php-utils/src/Php.php
deleted file mode 100644
index 8edec73..0000000
--- a/libs/php-utils/src/Php.php
+++ /dev/null
@@ -1,18 +0,0 @@
- '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")) {
- return [];
- }
-
- $options = array_merge([
- 'allow' => [], // only allowed tags
- 'ignore' => ['param', 'return'], // ignore tags
- 'default' => 'description', // default tag name, first line text will attach to it.
- ], $options);
-
- $allow = (array)$options['allow'];
- $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)));
-
- $tags = [];
- $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
-
- foreach ($parts as $part) {
- if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
- $name = $matches[1];
- if (!$name || in_array($name, $ignored, true)) {
- continue;
- }
-
- if (!$value = trim($matches[2])) {
- continue;
- }
-
- // always allow default tag
- if ($default !== $name && $allow && !in_array($name, $allow, true)) {
- continue;
- }
-
- if (!isset($tags[$name])) {
- $tags[$name] = $value;
- } elseif (is_array($tags[$name])) {
- $tags[$name][] = $value;
- } else {
- $tags[$name] = [$tags[$name], $value];
- }
- }
- }
-
- 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);
-
- if (isset($docLines[1])) {
- return trim($docLines[1], "/\t *");
- }
-
- return '';
- }
-
- /**
- * 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, '/'))));
-
- 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
deleted file mode 100644
index bf3a170..0000000
--- a/libs/php-utils/src/PhpDotEnv.php
+++ /dev/null
@@ -1,132 +0,0 @@
-add($file);
- }
-
- /**
- * @param string $file
- */
- public function add(string $file): void
- {
- 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)));
- unset($loadedVars['']);
-
- foreach ($data as $name => $value) {
- if (is_int($name) || !is_string($value)) {
- continue;
- }
-
- $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])) {
- continue;
- }
-
- // is a constant var
- if ($value && defined($value)) {
- $value = constant($value);
- }
-
- // eg: "FOO=BAR"
- putenv("$name=$value");
- $_ENV[$name] = $value;
-
- if ($notHttpName) {
- $_SERVER[$name] = $value;
- }
-
- $loadedVars[$name] = true;
- }
-
- if ($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
deleted file mode 100644
index a072333..0000000
--- a/libs/php-utils/src/PhpEnv.php
+++ /dev/null
@@ -1,232 +0,0 @@
- $lastError['type'],
- 'message' => $lastError['message'],
- 'file' => $lastError['file'],
- 'line' => $lastError['line'],
- 'catcher' => __METHOD__,
- ];
-
- if ($catcher) {
- $data['catcher'] = $catcher;
- }
-
- return [$digest, $data];
- }
-
- /**
- * @param int $code
- *
- * @return string
- */
- public static function codeToString(int $code): string
- {
- switch ($code) {
- case E_ERROR:
- return 'E_ERROR';
- case E_WARNING:
- return 'E_WARNING';
- case E_PARSE:
- return 'E_PARSE';
- case E_NOTICE:
- return 'E_NOTICE';
- case E_CORE_ERROR:
- return 'E_CORE_ERROR';
- case E_CORE_WARNING:
- return 'E_CORE_WARNING';
- case E_COMPILE_ERROR:
- return 'E_COMPILE_ERROR';
- case E_COMPILE_WARNING:
- return 'E_COMPILE_WARNING';
- case E_USER_ERROR:
- return 'E_USER_ERROR';
- case E_USER_WARNING:
- return 'E_USER_WARNING';
- case E_USER_NOTICE:
- return 'E_USER_NOTICE';
- case E_STRICT:
- return 'E_STRICT';
- case E_RECOVERABLE_ERROR:
- return 'E_RECOVERABLE_ERROR';
- case E_DEPRECATED:
- return 'E_DEPRECATED';
- case E_USER_DEPRECATED:
- return 'E_USER_DEPRECATED';
- }
-
- return 'Unknown PHP error';
- }
-}
diff --git a/libs/php-utils/src/PhpException.php b/libs/php-utils/src/PhpException.php
deleted file mode 100644
index a63c072..0000000
--- a/libs/php-utils/src/PhpException.php
+++ /dev/null
@@ -1,117 +0,0 @@
-getMessage()}";
- } else {
- $message = sprintf("%s(%d): %s
\nFile: %s(Line %d)%s \n\n%s
",
- get_class($e), $e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(),
- $catcher ? "\nCatch By: $catcher" : '', $e->getTraceAsString());
- }
-
- return $clearHtml ? strip_tags($message) : "{$message}
";
- }
-
- /**
- * Converts an exception into a simple array.
- *
- * @param Exception|Throwable $e the exception being converted
- * @param bool $getTrace
- * @param null|string $catcher
- *
- * @return array
- */
- public static function toArray($e, bool $getTrace = true, string $catcher = null): array
- {
- $data = [
- 'class' => get_class($e),
- 'message' => $e->getMessage(),
- 'code' => $e->getCode(),
- 'file' => $e->getFile() . ':' . $e->getLine(),
- ];
-
- if ($catcher) {
- $data['catcher'] = $catcher;
- }
-
- if ($getTrace) {
- $data['trace'] = $e->getTrace();
- }
-
- return $data;
- }
-
- /**
- * Converts an exception into a json string.
- *
- * @param Exception|Throwable $e the exception being converted
- * @param bool $getTrace
- * @param null|string $catcher
- *
- * @return string the string representation of the exception.
- */
- public static function toJson($e, bool $getTrace = true, string $catcher = null): string
- {
- if (!$getTrace) {
- return json_encode(['msg' => "Error: {$e->getMessage()}"]);
- }
-
- $map = [
- 'code' => $e->getCode() ?: 500,
- 'msg' => sprintf('%s(%d): %s, File: %s(Line %d)', get_class($e), $e->getCode(), $e->getMessage(),
- $e->getFile(), $e->getLine()),
- 'data' => $e->getTrace()
- ];
-
- if ($catcher) {
- $map['catcher'] = $catcher;
- }
-
- if ($getTrace) {
- $map['trace'] = $e->getTrace();
- }
-
- return json_encode($map);
- }
-}
diff --git a/libs/php-utils/src/PhpHelper.php b/libs/php-utils/src/PhpHelper.php
deleted file mode 100644
index 0314a69..0000000
--- a/libs/php-utils/src/PhpHelper.php
+++ /dev/null
@@ -1,208 +0,0 @@
- 0) {
- $cb = explode('::', $cb, 2);
- // function
- } elseif (function_exists($cb)) {
- return $cb(...$args);
- }
- } elseif (is_object($cb) && method_exists($cb, '__invoke')) {
- return $cb(...$args);
- }
-
- if (is_array($cb)) {
- [$obj, $mhd] = $cb;
-
- return is_object($obj) ? $obj->$mhd(...$args) : $obj::$mhd(...$args);
- }
-
- return $cb(...$args);
- }
-
- /**
- * @param callable $cb
- * @param array $args
- *
- * @return mixed
- */
- public static function callByArray(callable $cb, array $args)
- {
- return self::call($cb, ...$args);
- }
-
- /**
- * 给对象设置属性值
- * - 会先尝试用 setter 方法设置属性
- * - 再尝试直接设置属性
- *
- * @param mixed $object An object instance
- * @param array $options
- *
- * @return mixed
- */
- public static function initObject($object, array $options)
- {
- foreach ($options as $property => $value) {
- if (is_numeric($property)) {
- continue;
- }
-
- $setter = 'set' . ucfirst($property);
-
- // has setter
- if (method_exists($object, $setter)) {
- $object->$setter($value);
- } elseif (property_exists($object, $property)) {
- $object->$property = $value;
- }
- }
-
- return $object;
- }
-
- /**
- * 获取资源消耗
- *
- * @param int $startTime
- * @param int|float $startMem
- * @param array $info
- * @param bool $realUsage
- *
- * @return array
- */
- public static function runtime($startTime, $startMem, array $info = [], $realUsage = false): array
- {
- $info['startTime'] = $startTime;
- $info['endTime'] = microtime(true);
- $info['endMemory'] = memory_get_usage($realUsage);
-
- // 计算运行时间
- $info['runtime'] = number_format(($info['endTime'] - $startTime) * 1000, 3) . 'ms';
-
- if ($startMem) {
- $startMem = array_sum(explode(' ', $startMem));
- $endMem = array_sum(explode(' ', $info['endMemory']));
-
- $info['memory'] = number_format(($endMem - $startMem) / 1024, 3) . 'kb';
- }
-
- $peakMem = memory_get_peak_usage(true) / 1024 / 1024;
- // record
- $info['peakMemory'] = number_format($peakMem, 3) . 'Mb';
-
- return $info;
- }
-
- /**
- * @return array
- */
- public static function getUserConstants(): array
- {
- $const = get_defined_constants(true);
-
- return $const['user'] ?? [];
- }
-
- /**
- * dump vars
- *
- * @param array ...$args
- *
- * @return string
- */
- public static function dumpVars(...$args): string
- {
- ob_start();
- var_dump(...$args);
- $string = ob_get_clean();
-
- return preg_replace("/=>\n\s+/", '=> ', $string);
- }
-
- /**
- * print vars
- *
- * @param array ...$args
- *
- * @return string
- */
- public static function printVars(...$args): string
- {
- $string = '';
-
- foreach ($args as $arg) {
- $string .= print_r($arg, 1) . PHP_EOL;
- }
-
- return preg_replace("/Array\n\s+\(/", 'Array (', $string);
- }
-
- /**
- * @param mixed $var
- *
- * @return string
- */
- public static function exportVar($var): string
- {
- $string = var_export($var, true);
-
- return preg_replace('/=>\s+\n\s+array \(/', '=> array (', $string);
- }
-
-}
diff --git a/libs/php-utils/src/Type.php b/libs/php-utils/src/Type.php
deleted file mode 100644
index 452ee20..0000000
--- a/libs/php-utils/src/Type.php
+++ /dev/null
@@ -1,66 +0,0 @@
-assertCount(3, $ret);
- $this->assertArrayHasKey('since', $ret);
- $this->assertArrayHasKey('example', $ret);
- $this->assertArrayHasKey('description', $ret);
-
- $ret = PhpDoc::getTags($comment, ['allow' => ['example']]);
- $this->assertCount(2, $ret);
- $this->assertArrayNotHasKey('since', $ret);
- $this->assertArrayHasKey('example', $ret);
- $this->assertArrayHasKey('description', $ret);
-
- $ret = PhpDoc::getTags($comment, [
- 'allow' => ['example'],
- 'default' => 'desc'
- ]);
- $this->assertCount(2, $ret);
- $this->assertArrayNotHasKey('since', $ret);
- $this->assertArrayHasKey('example', $ret);
- $this->assertArrayHasKey('desc', $ret);
- $this->assertArrayNotHasKey('description', $ret);
- }
-}
diff --git a/libs/php-utils/test/boot.php b/libs/php-utils/test/boot.php
deleted file mode 100644
index 6acd4bf..0000000
--- a/libs/php-utils/test/boot.php
+++ /dev/null
@@ -1,27 +0,0 @@
-7.1.0",
- "ext-mbstring": "*"
- },
- "autoload": {
- "psr-4": {
- "Toolkit\\StrUtil\\": "src/"
- }
- },
- "suggest": {
- "inhere/php-validate": "Very lightweight data validate tool"
- }
-}
diff --git a/libs/str-utils/phpunit.xml.dist b/libs/str-utils/phpunit.xml.dist
deleted file mode 100644
index 26bd767..0000000
--- a/libs/str-utils/phpunit.xml.dist
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
-
- test/
-
-
-
-
-
- src
-
-
-
diff --git a/libs/str-utils/src/HtmlHelper.php b/libs/str-utils/src/HtmlHelper.php
deleted file mode 100644
index 55da156..0000000
--- a/libs/str-utils/src/HtmlHelper.php
+++ /dev/null
@@ -1,241 +0,0 @@
- $value) {
- if (is_string($key)) {
- $key = htmlspecialchars($key, ENT_QUOTES, $charset);
- }
-
- if (is_string($value)) {
- $value = htmlspecialchars($value, ENT_QUOTES, $charset);
- } elseif (is_array($value)) {
- $value = static::encodeArray($value);
- }
-
- $d[$key] = $value;
- }
-
- return $d;
- }
-
-
- /**
- * html代码转义
- * htmlspecialchars 只转化这几个html [ & ' " < > ] 代码 --> [ & " ],
- * 而 htmlentities 却会转化所有的html代码,连同里面的它无法识别的中文字符也会转化。
- * 一般使用 htmlspecialchars 就足够了,要使用 htmlentities 时,要注意为第三个参数传递正确的编码。
- * htmlentities() <--> html_entity_decode() — 将特殊的 HTML 实体转换回普通字符
- * htmlspecialchars() <--> htmlspecialchars_decode() — 将特殊的 HTML 实体转换回普通字符
- * ENT_COMPAT ENT_QUOTES ENT_NOQUOTES ENT_HTML401 ENT_XML1 ENT_XHTML ENT_HTML5
- *
- * @param $data
- * @param int $type
- * @param string $encoding
- *
- * @return array|mixed|string
- */
- public static function escape($data, int $type = 0, $encoding = 'UTF-8')
- {
- if (is_array($data)) {
- foreach ($data as $k => $v) {
- $data[$k] = self::escape($data, $type, $encoding);
- }
-
- return $data;
- }
-
- // 默认使用 htmlspecialchars()
- if (!$type) {
- $data = htmlspecialchars($data, ENT_QUOTES, $encoding);
- } else {
- $data = htmlentities($data, ENT_QUOTES, $encoding);
- }
-
- //如‘志’这样的16进制的html字符,为了防止这样的字符被错误转译,使用正则进行匹配,把这样的字符又转换回来。
- if (strpos($data, '')) {
- $data = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $data);
- }
-
- return $data;
- }
-
- /**
- * 去掉html转义
- *
- * @param $data
- * @param int $type
- * @param string $encoding
- *
- * @return array|string
- */
- public static function unescap($data, $type = 0, $encoding = 'UTF-8')
- {
- if (is_array($data)) {
- foreach ($data as $k => $v) {
- $data[$k] = self::unescap($data, $type, $encoding);
- }
-
- } elseif (!$type) {//默认使用 htmlspecialchars_decode()
- $data = htmlspecialchars_decode($data, ENT_QUOTES);
- } else {
- $data = html_entity_decode($data, ENT_QUOTES, $encoding);
- }
-
- return $data;
- }
-
- /**
- * Strip img-tags from string
- *
- * @param string $string Sting to be cleaned.
- *
- * @return string Cleaned string
- */
- public static function stripImages(string $string): string
- {
- return preg_replace('#(<[/]?img.*>)#U', '', $string);
- }
-
- /**
- * Strip iframe-tags from string
- *
- * @param string $string Sting to be cleaned.
- *
- * @return string Cleaned string
- */
- public static function stripIframes(string $string): string
- {
- return preg_replace('#(<[/]?iframe.*>)#U', '', $string);
- }
-
- /**
- * stripScript
- *
- * @param string $string
- *
- * @return string
- */
- public static function stripScript(string $string): string
- {
- return preg_replace('//si', '', $string);
- }
-
- /**
- * stripStyle
- *
- * @param string $string
- *
- * @return string
- */
- public static function stripStyle(string $string): string
- {
- return preg_replace('//si', '', $string);
- }
-
- /**
- * @param string $html
- * @param bool|true $onlySrc
- *
- * @return array
- */
- public static function matchImages(string $html, bool $onlySrc = true): array
- {
- // $preg = '//i';
- $preg = '//i';
-
- if (!preg_match_all($preg, trim($html), $images)) {
- return [];
- }
-
- if ($onlySrc) {
- return array_key_exists(1, $images) ? $images[1] : [];
- }
-
- return $images;
- }
-
- /**
- * @param string $html
- *
- * @return string
- */
- public static function minify(string $html): string
- {
- $search = [
- '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?[^\S ]+/s',
- '/[^\S ]+\', '<', '\\1'];
-
- return preg_replace($search, $replace, $html);
- }
-}
diff --git a/libs/str-utils/src/Json.php b/libs/str-utils/src/Json.php
deleted file mode 100644
index fccc524..0000000
--- a/libs/str-utils/src/Json.php
+++ /dev/null
@@ -1,18 +0,0 @@
- 'min' // 输出数据类型 min 压缩过的 raw 正常的
- * 'file' => 'xx.json' // 输出文件路径;仅是文件名,则会取输入路径
- * ]
- *
- * @return string | bool
- */
- public static function format($input, $output = false, array $options = [])
- {
- if (!is_string($input)) {
- return false;
- }
-
- $data = trim($input);
-
- if (file_exists($input)) {
- $data = file_get_contents($input);
- }
-
- if (!$data) {
- return false;
- }
-
- $data = preg_replace([
- // 去掉所有多行注释/* .... */
- '/\/\*.*?\*\/\s*/is',
- // 去掉所有单行注释//....
- '/\/\/.*?[\r\n]/is',
- // 去掉空白行
- "/(\n[\r])+/is"
- ], ['', '', "\n"], $data);
-
- if (!$output) {
- return $data;
- }
-
- $default = ['type' => 'min'];
- $options = array_merge($default, $options);
-
- if (file_exists($input) && (empty($options['file']) || !is_file($options['file']))) {
- $dir = dirname($input);
- $name = basename($input, '.json');
- $file = $dir . '/' . $name . '.' . $options['type'] . '.json';
- // save to options
- $options['file'] = $file;
- }
-
- static::saveAs($data, $options['file'], $options['type']);
- return $data;
- }
-
- /**
- * @param string $data
- * @param string $output
- * @param array $options
- *
- * @return bool|int
- */
- public static function saveAs(string $data, string $output, array $options = [])
- {
- $default = ['type' => 'min', 'file' => ''];
- $options = array_merge($default, $options);
- $saveDir = dirname($output);
-
- if (!file_exists($saveDir)) {
- throw new RuntimeException('设置的json文件输出' . $saveDir . '目录不存在!');
- }
-
- $name = basename($output, '.json');
- $file = $saveDir . '/' . $name . '.' . $options['type'] . '.json';
-
- // 去掉空白
- if ($options['type '] === 'min') {
- $data = preg_replace('/(?!\w)\s*?(?!\w)/i', '', $data);
- }
-
- return file_put_contents($file, $data);
- }
-}
diff --git a/libs/str-utils/src/Str.php b/libs/str-utils/src/Str.php
deleted file mode 100644
index e24b930..0000000
--- a/libs/str-utils/src/Str.php
+++ /dev/null
@@ -1,18 +0,0 @@
-body = $content;
- }
-
- /**
- * @param string $content
- */
- public function write(string $content): void
- {
- $this->body .= $content;
- }
-
- /**
- * @param string $content
- */
- public function append(string $content): void
- {
- $this->write($content);
- }
-
- /**
- * @param string $content
- */
- public function prepend(string $content): void
- {
- $this->body = $content . $this->body;
- }
-
- /**
- * clear data
- */
- public function clear(): string
- {
- $string = $this->body;
- // clear
- $this->body = '';
-
- return $string;
- }
-
- /**
- * @return string
- */
- public function getBody(): string
- {
- return $this->body;
- }
-
- /**
- * @param string $body
- */
- public function setBody(string $body): void
- {
- $this->body = $body;
- }
-
- /**
- * @return string
- */
- public function toString(): string
- {
- return $this->body;
- }
-
- /**
- * @return string
- */
- public function __toString()
- {
- return $this->toString();
- }
-}
diff --git a/libs/str-utils/src/StringHelper.php b/libs/str-utils/src/StringHelper.php
deleted file mode 100644
index 27d7959..0000000
--- a/libs/str-utils/src/StringHelper.php
+++ /dev/null
@@ -1,1078 +0,0 @@
- '/\S+/',
- 'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
- // 'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
- 'url' => '/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i',
- 'currency' => '/^\d+(\.\d+)?$/',
- # 货币
- 'number' => '/^\d+$/',
- 'zip' => '/^\d{6}$/',
- 'integer' => '/^[-\+]?\d+$/',
- 'double' => '/^[-\+]?\d+(\.\d+)?$/',
- 'english' => '/^[A-Za-z]+$/',
- ];
-
- $value = trim($value);
- $name = strtolower($rule);
-
- // 检查是否有内置的正则表达式
- if (isset($validate[$name])) {
- $rule = $validate[$name];
- }
-
- return preg_match($rule, $value) === 1;
- }
-
- ////////////////////////////////////////////////////////////////////////
- /// Check Length
- ////////////////////////////////////////////////////////////////////////
-
- /**
- * from Symfony
- *
- * @param string $string
- *
- * @return int
- */
- public static function len(string $string): int
- {
- if (false === $encoding = mb_detect_encoding($string, null, true)) {
- return strlen($string);
- }
-
- return mb_strwidth($string, $encoding);
- }
-
- public static function strlen(string $str, string $encoding = 'UTF-8'): int
- {
- $str = html_entity_decode($str, ENT_COMPAT, 'UTF-8');
-
- return function_exists('mb_strlen') ? mb_strlen($str, $encoding) : strlen($str);
- }
-
- /**
- * @param string $string
- *
- * @return int
- */
- public static function utf8Len(string $string): int
- {
- // strlen: one chinese is 3 char.
- // mb_strlen: one chinese is 1 char.
- // mb_strwidth: one chinese is 2 char.
- return mb_strlen($string, 'utf-8');
- }
-
- /**
- * 计算字符长度
- *
- * @param string $str
- *
- * @return int
- */
- public static function length(string $str): int
- {
- if ($str === '') {
- return 0;
- }
-
- if (function_exists('mb_strlen')) {
- return mb_strlen($str, 'utf-8');
- }
-
- preg_match_all('/./u', $str, $arr);
-
- return count($arr[0]);
- }
-
- /**
- * @from web
- * 可以统计中文字符串长度的函数
- *
- * @param string $str 要计算长度的字符串
- *
- * @return int
- * @internal param bool $type 计算长度类型,0(默认)表示一个中文算一个字符,1表示一个中文算两个字符
- */
- public static function absLen(string $str): int
- {
- if (empty($str)) {
- return 0;
- }
-
- if (function_exists('mb_strwidth')) {
- return mb_strwidth($str, 'utf-8');
- }
-
- if (function_exists('mb_strlen')) {
- return mb_strlen($str, 'utf-8');
- }
-
- preg_match_all('/./u', $str, $ar);
-
- return count($ar[0]);
- }
-
- ////////////////////////////////////////////////////////////
- /// Security
- ////////////////////////////////////////////////////////////
-
- /**
- * ********************** 生成一定长度的随机字符串函数 **********************
- *
- * @param int $length - 随机字符串长度
- * @param array|string $param -
- *
- * @return string
- * @throws Exception
- * @internal param string $chars
- */
- public static function random(int $length, array $param = []): string
- {
- $param = array_merge([
- 'prefix' => '',
- 'suffix' => '',
- 'chars' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
- ], $param);
-
- $chars = $param['chars'];
- $max = strlen($chars) - 1; //strlen($chars) 计算字符串的长度
- $str = '';
-
- for ($i = 0; $i < $length; $i++) {
- $str .= $chars[random_int(0, $max)];
- }
-
- return $param['prefix'] . $str . $param['suffix'];
- }
-
- /**
- * @param int $length
- *
- * @return string
- */
- public static function genSalt(int $length = 32): string
- {
- return substr(str_replace('+', '.', base64_encode(hex2bin(random_token($length)))), 0, 44);
- }
-
- /**
- * @param int $length
- *
- * @return bool|string
- */
- public static function genUid(int $length = 7): string
- {
- if (!is_int($length) || $length > 32 || $length < 1) {
- $length = 7;
- }
-
- return substr(hash('md5', uniqid('', true)), 0, $length);
- }
-
- /**
- * @param string $string
- * @param int $padLen
- * @param string $padStr
- * @param int $padType
- *
- * @return string
- */
- public static function pad(string $string, int $padLen, string $padStr = ' ', int $padType = STR_PAD_RIGHT): string
- {
- return $padLen > 0 ? str_pad($string, $padLen, $padStr, $padType) : $string;
- }
-
- public static function padLeft(string $string, int $padLen, string $padStr = ' '): string
- {
- return $padLen > 0 ? str_pad($string, $padLen, $padStr, STR_PAD_LEFT) : $string;
- }
-
- public static function padRight(string $string, int $padLen, string $padStr = ' '): string
- {
- return $padLen > 0 ? str_pad($string, $padLen, $padStr) : $string;
- }
-
- /**
- * gen UUID
- *
- * @param int $version
- * @param null $node
- * @param null $ns
- *
- * @return UUID
- * @throws InvalidArgumentException
- */
- // public static function genUUID($version = 1, $node = null, $ns = null)
- // {
- // return UUID::generate($version, $node, $ns);
- // }
-
- ////////////////////////////////////////////////////////////////////////
- /// Case Convert
- ////////////////////////////////////////////////////////////////////////
-
- /**
- * Convert \n and \r\n and \r to
- *
- * @param string $str String to transform
- *
- * @return string New string
- */
- public static function nl2br(string $str): string
- {
- return str_replace(["\r\n", "\r", "\n"], '
', $str);
- }
-
- public static function lower(string $str): string
- {
- return static::strtolower($str);
- }
-
- /**
- * @param string $str
- *
- * @return bool|string
- */
- public static function strtolower(string $str): string
- {
- return function_exists('mb_strtolower') ? mb_strtolower($str, 'utf-8') : strtolower($str);
- }
-
- public static function upper(string $str): string
- {
- return static::strtoupper($str);
- }
-
- /**
- * @param $str
- *
- * @return bool|string
- */
- public static function strtoupper(string $str)
- {
- if (!is_string($str)) {
- return $str;
- }
-
- return function_exists('mb_strtoupper') ? mb_strtoupper($str, 'utf-8') : strtoupper($str);
- }
-
- /**
- * @param $str
- *
- * @return string
- */
- public static function ucfirst(string $str): string
- {
- return self::strtoupper(self::substr($str, 0, 1)) . self::substr($str, 1);
- }
-
- /**
- * @param $str
- *
- * @return string
- */
- public static function ucwords(string $str): string
- {
- return function_exists('mb_convert_case') ? mb_convert_case($str, MB_CASE_TITLE) :
- ucwords(self::strtolower($str));
- }
-
- /**
- * @param string $str
- * @param bool $upperFirstChar
- *
- * @return mixed
- */
- public static function camel(string $str, bool $upperFirstChar = false): string
- {
- return self::toCamelCase($str, $upperFirstChar);
- }
-
- /**
- * @param string $str
- * @param bool $upperFirstChar
- *
- * @return mixed
- */
- public static function toCamel(string $str, bool $upperFirstChar = false): string
- {
- return self::toCamelCase($str, $upperFirstChar);
- }
-
- /**
- * to camel
- *
- * @param string $name
- * @param bool $upperFirst
- *
- * @return string
- */
- public static function camelCase(string $name, bool $upperFirst = false): string
- {
- $name = trim($name, '-_');
-
- // convert 'first-second' to 'firstSecond'
- if (strpos($name, '-')) {
- $name = ucwords(str_replace('-', ' ', $name));
- $name = str_replace(' ', '', lcfirst($name));
- }
-
- return $upperFirst ? ucfirst($name) : $name;
- }
-
- /**
- * Translates a string with underscores into camel case (e.g. first_name -> firstName)
- *
- * @param string $str
- * @param bool $upperFirst
- *
- * @return mixed
- */
- public static function toCamelCase(string $str, bool $upperFirst = false): string
- {
- $str = (string)self::strtolower($str);
-
- if ($upperFirst) {
- $str = self::ucfirst($str);
- }
-
- return preg_replace_callback('/_+([a-z])/', function ($c) {
- return strtoupper($c[1]);
- }, $str);
- }
-
- public static function snake(string $str, string $sep = '_'): string
- {
- return self::toSnakeCase($str, $sep);
- }
-
- public static function toSnake(string $str, string $sep = '_'): string
- {
- return self::toSnakeCase($str, $sep);
- }
-
- /**
- * Transform a CamelCase string to underscore_case string
- *
- * @param string $str
- * @param string $sep
- *
- * @return string
- */
- public static function toSnakeCase(string $str, string $sep = '_'): string
- {
- // 'CMSCategories' => 'cms_categories'
- // 'RangePrice' => 'range_price'
- return self::lower(trim(preg_replace('/([A-Z][a-z])/', $sep . '$1', $str), $sep));
- }
-
- /**
- * 驼峰式 <=> 下划线式
- *
- * @param string $str [description]
- * @param bool $toCamelCase
- * true : 驼峰式 => 下划线式
- * false : 驼峰式 <= 下划线式
- *
- * @return string
- */
- public static function nameChange(string $str, bool $toCamelCase = true): string
- {
- $str = trim($str);
-
- // 默认 :下划线式 =>驼峰式
- if ($toCamelCase) {
- if (strpos($str, '_') === false) {
- return $str;
- }
-
- $arr_char = explode('_', strtolower($str));
- $newString = array_shift($arr_char);
-
- foreach ($arr_char as $val) {
- $newString .= ucfirst($val);
- }
-
- return $newString;
- }
-
- // 驼峰式 => 下划线式
- return strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $str));
- }
-
- ////////////////////////////////////////////////////////////////////////
- /// Convert to array
- ////////////////////////////////////////////////////////////////////////
-
- /**
- * var_dump(str2array('34,56,678, 678, 89, '));
- *
- * @param string $str
- * @param string $sep
- *
- * @return array
- */
- public static function str2array(string $str, string $sep = ','): array
- {
- $str = trim($str, "$sep ");
-
- if (!$str) {
- return [];
- }
-
- return preg_split("/\s*$sep\s*/", $str, -1, PREG_SPLIT_NO_EMPTY);
- }
-
- public static function toArray(string $string, string $delimiter = ',', int $limit = 0): array
- {
- $string = trim($string, "$delimiter ");
- if ($string === '') {
- return [];
- }
-
- $values = [];
- $rawList = $limit < 1 ? explode($delimiter, $string) : explode($delimiter, $string, $limit);
-
- foreach ($rawList as $val) {
- if (($val = trim($val)) !== '') {
- $values[] = $val;
- }
- }
-
- return $values;
- }
-
- public static function explode(string $str, string $separator = '.', int $limit = 0): array
- {
- return static::split2Array($str, $separator, $limit);
- }
-
- /**
- * @param string $string
- * @param string $delimiter
- * @param int $limit
- *
- * @return array
- */
- public static function split2Array(string $string, string $delimiter = ',', int $limit = 0): array
- {
- $string = trim($string, "$delimiter ");
-
- if (!strpos($string, $delimiter)) {
- return [$string];
- }
-
- if ($limit < 1) {
- $list = explode($delimiter, $string);
- } else {
- $list = explode($delimiter, $string, $limit);
- }
-
- return array_values(array_filter(array_map('trim', $list), 'strlen'));
- }
-
- /**
- * @param string $string
- * @param int $width
- *
- * @return array
- */
- public static function splitByWidth(string $string, int $width): array
- {
- // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
- // additionally, array_slice() is not enough as some character has doubled width.
- // we need a function to split string not by character count but by string width
- if (false === $encoding = mb_detect_encoding($string, null, true)) {
- return str_split($string, $width);
- }
-
- $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
- $lines = [];
- $line = '';
-
- foreach (preg_split('//u', $utf8String) as $char) {
- // test if $char could be appended to current line
- if (mb_strwidth($line . $char, 'utf8') <= $width) {
- $line .= $char;
- continue;
- }
-
- // if not, push current line to array and make new line
- $lines[] = str_pad($line, $width);
- $line = $char;
- }
-
- if ('' !== $line) {
- $lines[] = count($lines) ? str_pad($line, $width) : $line;
- }
-
- mb_convert_variables($encoding, 'utf8', $lines);
-
- return $lines;
- }
-
- ////////////////////////////////////////////////////////////////////////
- /// Truncate
- ////////////////////////////////////////////////////////////////////////
-
- /**
- * @param string $str
- * @param int $start
- * @param int|null $length
- * @param string $encoding
- *
- * @return bool|string
- */
- public static function substr(string $str, int $start, int $length = null, string $encoding = 'utf-8')
- {
- if (function_exists('mb_substr')) {
- return mb_substr($str, $start, ($length === null ? self::strlen($str) : (int)$length), $encoding);
- }
-
- return substr($str, $start, ($length === null ? self::strlen($str) : (int)$length));
- }
-
- /**
- * @from web
- * utf-8编码下截取中文字符串,参数可以参照substr函数
- *
- * @param string $str 要进行截取的字符串
- * @param int $start 要进行截取的开始位置,负数为反向截取
- * @param int $end 要进行截取的长度
- *
- * @return string
- */
- public static function utf8SubStr(string $str, int $start = 0, int $end = null): string
- {
- if (empty($str)) {
- return false;
- }
-
- if (function_exists('mb_substr')) {
- if (func_num_args() >= 3) {
- $end = func_get_arg(2);
-
- return mb_substr($str, $start, $end, 'utf-8');
- }
-
- mb_internal_encoding('UTF-8');
-
- return mb_substr($str, $start);
-
- }
-
- $null = '';
- preg_match_all('/./u', $str, $ar);
-
- if (func_num_args() >= 3) {
- $end = func_get_arg(2);
- return implode($null, array_slice($ar[0], $start, $end));
- }
-
- return implode($null, array_slice($ar[0], $start));
- }
-
-
- /**
- * @from web
- * 中文截取,支持gb2312,gbk,utf-8,big5 *
- *
- * @param string $str 要截取的字串
- * @param int $start 截取起始位置
- * @param int $length 截取长度
- * @param string $charset utf-8|gb2312|gbk|big5 编码
- * @param bool $suffix 是否加尾缀
- *
- * @return string
- */
- public static function zhSubStr($str, $start = 0, $length = 0, $charset = 'utf-8', $suffix = true): string
- {
- if (function_exists('mb_substr')) {
- if (mb_strlen($str, $charset) <= $length) {
- return $str;
- }
-
- $slice = mb_substr($str, $start, $length, $charset);
- } else {
- $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
- $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
- $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
- $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
-
- preg_match_all($re[$charset], $str, $match);
- if (count($match[0]) <= $length) {
- return $str;
- }
-
- $slice = implode('', array_slice($match[0], $start, $length));
- }
-
- return (bool)$suffix ? $slice . '…' : $slice;
- }
-
- /**
- * Truncate strings
- *
- * @param string $str
- * @param int $maxLength Max length
- * @param string $suffix Suffix optional
- *
- * @return string $str truncated
- */
- /* CAUTION : Use it only on module hookEvents.
- ** For other purposes use the smarty function instead */
- public static function truncate(string $str, $maxLength, $suffix = '...'): string
- {
- if (self::strlen($str) <= $maxLength) {
- return $str;
- }
-
- $str = utf8_decode($str);
-
- return utf8_encode(substr($str, 0, $maxLength - self::strlen($suffix)) . $suffix);
- }
-
- /**
- * 字符截断输出
- *
- * @param string $str
- * @param int $start
- * @param null|int $length
- *
- * @return string
- */
- public static function truncate2(string $str, int $start, int $length = null): string
- {
- if (!$length) {
- $length = $start;
- $start = 0;
- }
-
- if (strlen($str) <= $length) {
- return $str;
- }
-
- if (function_exists('mb_substr')) {
- $str = mb_substr(strip_tags($str), $start, $length, 'utf-8');
- } else {
- $str = substr($str, $start, $length) . '...';
- }
-
- return $str;
- }
-
- /**
- * Copied from CakePHP String utility file
- *
- * @param string $text
- * @param int $length
- * @param array $options
- *
- * @return bool|string
- */
- public static function truncate3(string $text, int $length = 120, array $options = [])
- {
- $default = [
- 'ellipsis' => '...',
- 'exact' => true,
- 'html' => true
- ];
-
- $options = array_merge($default, $options);
- $ellipsis = $options['ellipsis'];
- $exact = $options['exact'];
- $html = $options['html'];
-
- /**
- * @var string $ellipsis
- * @var bool $exact
- * @var bool $html
- */
- if ($html) {
- if (self::strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
- return $text;
- }
-
- $total_length = self::strlen(strip_tags($ellipsis));
- $open_tags = $tags = [];
- $truncate = '';
- preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
-
- foreach ($tags as $tag) {
- if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/', $tag[2])) {
- if (preg_match('/<[\w]+[^>]*>/', $tag[0])) {
- array_unshift($open_tags, $tag[2]);
- } elseif (preg_match('/<\/([\w]+)[^>]*>/', $tag[0], $close_tag)) {
- $pos = array_search($close_tag[1], $open_tags, true);
- if ($pos !== false) {
- array_splice($open_tags, $pos, 1);
- }
- }
- }
- $truncate .= $tag[1];
- $content_length = self::strlen(preg_replace('/&[0-9a-z]{2,8};|[\d]{1,7};|[0-9a-f]{1,6};/i', ' ',
- $tag[3]));
-
- if ($content_length + $total_length > $length) {
- $left = $length - $total_length;
- $entities_length = 0;
-
- if (preg_match_all('/&[0-9a-z]{2,8};|[\d]{1,7};|[0-9a-f]{1,6};/i', $tag[3], $entities,
- PREG_OFFSET_CAPTURE)
- ) {
- foreach ((array)$entities[0] as $entity) {
- if ($entity[1] + 1 - $entities_length <= $left) {
- $left--;
- $entities_length += self::strlen($entity[0]);
- } else {
- break;
- }
- }
- }
-
- $truncate .= self::substr($tag[3], 0, $left + $entities_length);
- break;
- }
-
- $truncate .= $tag[3];
- $total_length += $content_length;
-
- if ($total_length >= $length) {
- break;
- }
- }
- } else {
- if (self::strlen($text) <= $length) {
- return $text;
- }
-
- $truncate = self::substr($text, 0, $length - self::strlen($ellipsis));
- }
-
- $open_tags = null;
-
- if (!$exact) {
- $spacepos = self::strrpos($truncate, ' ');
- if ($html) {
- $truncate_check = self::substr($truncate, 0, $spacepos);
- $last_open_tag = self::strrpos($truncate_check, '<');
- $last_close_tag = self::strrpos($truncate_check, '>');
-
- if ($last_open_tag > $last_close_tag) {
- preg_match_all('/<[\w]+[^>]*>/', $truncate, $last_tag_matches);
- $last_tag = array_pop($last_tag_matches[0]);
- $spacepos = self::strrpos($truncate, $last_tag) + self::strlen($last_tag);
- }
-
- $bits = self::substr($truncate, $spacepos);
- preg_match_all('/<\/([a-z]+)>/', $bits, $dropped_tags, PREG_SET_ORDER);
-
- /** @var array $dropped_tags */
- if (!empty($dropped_tags)) {
- if (!empty($open_tags)) {
- foreach ($dropped_tags as $closing_tag) {
- if (!in_array($closing_tag[1], $open_tags, true)) {
- array_unshift($open_tags, $closing_tag[1]);
- }
- }
- } else {
- foreach ($dropped_tags as $closing_tag) {
- $open_tags[] = $closing_tag[1];
- }
- }
- }
- }
-
- $truncate = self::substr($truncate, 0, $spacepos);
- }
-
- $truncate .= $ellipsis;
-
- if ($html && $open_tags) {
- foreach ((array)$open_tags as $tag) {
- $truncate .= '' . $tag . '>';
- }
- }
-
- return $truncate;
- }
-
- ////////////////////////////////////////////////////////////////////////
- /// Format
- ////////////////////////////////////////////////////////////////////////
-
- /**
- * [format description]
- *
- * @param $str
- * @param array $replaceParams 用于 str_replace('search','replace',$str )
- * @param array $pregParams 用于 preg_replace('pattern','replace',$str)
- *
- * @return string [type] [description]
- * @example
- * $pregParams = [
- * 'xx', //'pattern'
- * 'yy', //'replace'
- * ]
- * * $pregParams = [
- * ['xx','xx2'], //'pattern'
- * ['yy','yy2'], //'replace'
- * ]
- * @example
- * $replaceParams = [
- * 'xx', //'search'
- * 'yy', //'replace'
- * ]
- * $replaceParams = [
- * ['xx','xx2'], //'search'
- * ['yy','yy2'], //'replace'
- * ]
- */
- public static function format($str, array $replaceParams = [], array $pregParams = []): string
- {
- if (!is_string($str) || !$str || (!$replaceParams && !$pregParams)) {
- return $str;
- }
-
- if ($replaceParams && count($replaceParams) === 2) {
- [$search, $replace] = $replaceParams;
- $str = str_replace($search, $replace, $str);
- }
-
- if ($pregParams && count($pregParams) === 2) {
- [$pattern, $replace] = $pregParams;
- $str = preg_replace($pattern, $replace, $str);
- }
-
- return trim($str);
- }
-
- /**
- * 格式化,用空格分隔各个词组
- *
- * @param string $keyword 字符串
- *
- * @return string 格式化后的字符串
- */
- public static function wordFormat($keyword): string
- {
- // 将全角角逗号换为空格
- $keyword = str_replace([',', ','], ' ', $keyword);
-
- return preg_replace([
- // 去掉两个空格以上的
- '/\s(?=\s)/',
- // 将非空格替换为一个空格
- '/[\n\r\t]/'
- ], ['', ' '], trim($keyword));
- }
-
- /**
- * 缩进格式化内容,去空白/注释
- *
- * @param $fileName
- * @param int $type
- *
- * @return mixed
- */
- public static function deleteStripSpace($fileName, $type = 0)
- {
- $data = trim(file_get_contents($fileName));
- $data = 0 === strpos($data, '' ? substr($data, 0, -2) : $data;
-
- //去掉所有注释 换行空白保留
- if ((int)$type === 1) {
- $preg_arr = [
- '/\/\*.*?\*\/\s*/is' // 去掉所有多行注释/* .... */
- ,
- '/\/\/.*?[\r\n]/is' // 去掉所有单行注释//....
- ,
- '/\#.*?[\r\n]/is' // 去掉所有单行注释 #....
- ];
-
- return preg_replace($preg_arr, '', $data);
- }
-
- $preg_arr = [
- '/\/\*.*?\*\/\s*/is' // 去掉所有多行注释 /* .... */
- ,
- '/\/\/.*?[\r\n]/is' // 去掉所有单行注释 //....
- ,
- '/\#.*?[\r\n]/is' // 去掉所有单行注释 #....
- ,
- '/(?!\w)\s*?(?!\w)/is' //去掉空白行
- ];
-
- return preg_replace($preg_arr, '', $data);
- }
-}
diff --git a/libs/str-utils/src/Token.php b/libs/str-utils/src/Token.php
deleted file mode 100644
index b4de0a7..0000000
--- a/libs/str-utils/src/Token.php
+++ /dev/null
@@ -1,210 +0,0 @@
-query(['name' => $_POST['name'] ]);
- * 1.
- * gen:
- * $password = Token::gen('123456');
- * verify:
- * Token::verify($user['password'], '123456');
- * 2.
- * gen:
- * $password = Token::hash('123456');
- * verify:
- * Token::verifyHash($user['password'], '123456');
- */
-class Token
-{
- /**
- * 指明应该使用的算法
- * $2a BLOWFISH算法。
- * $5 SHA-256
- * $6 SHA-512
- *
- * @var string
- */
- private static $algo = '$2y';
-
- /**
- * cost parameter 就是成本参数
- * $10 这是以2为底的对数,指示计算循环迭代的次数(10 => 2^10 = 1024),取值可以从04到31。
- *
- * @var string
- */
- private static $cost = '$10';
-
- /**
- * *******生成唯一序列号*******
- *
- * @param $var array || obj
- *
- * @return string
- */
- public static function md5($var): string
- {
- //serialize()序列化,串行化
- return md5(md5(serialize($var)));
- }
-
- /**
- * @return string
- */
- public static function uniqueSalt(): string
- {
- return (string)substr(sha1(mt_rand()), 0, 22);
- }
-
- /**
- * @param string $pwd
- * @param string $algo
- * @param array $opts
- *
- * @return bool|string
- */
- public static function pwdHash(string $pwd, string $algo, array $opts = [])
- {
- $opts = array_merge([
- 'cost' => 9
- ], $opts);
-
- return password_hash($pwd, $algo, $opts);
- }
-
- /**
- * @param string $pwd
- * @param string $hash
- *
- * @return bool|string
- */
- public static function pwdVerify(string $pwd, string $hash)
- {
- return password_verify($pwd, $hash);
- }
-
- /**
- * this will be used to generate a hash
- *
- * @param $password
- *
- * @return string
- */
- public static function gen(string $password): string
- {
- return crypt($password, self::$algo . self::$cost . '$' . self::uniqueSalt());
- }
-
- /**
- * this will be used to compare a password against a hash
- *
- * @param string $hash
- * @param string $password the user input
- *
- * @return bool
- */
- public static function verify(string $hash, string $password): bool
- {
- return hash_equals($hash, crypt($password, $hash));
- }
-
- /**
- * 2 生成
- *
- * @param $password
- * @param int $cost
- *
- * @return string
- * @throws RuntimeException
- * @todo from php.net
- */
- public static function hash(string $password, int $cost = 11): string
- {
- // $bytes = \random_bytes(17);
- $bytes = openssl_random_pseudo_bytes(17, $cStrong);
-
- if (false === $bytes || false === $cStrong) {
- throw new RuntimeException('exec gen hash error!');
- }
-
- /* To generate the salt, first generate enough random bytes. Because
- * base64 returns one character for each 6 bits, the we should generate
- * at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first
- * 22 base64 characters
- */
- $salt = substr(base64_encode($bytes), 0, 22);
- /* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to
- * replace any '+' in the base64 string with '.'. We don't have to do
- * anything about the '=', as this only occurs when the b64 string is
- * padded, which is always after the first 22 characters.
- */
- $salt = str_replace('+', '.', $salt);
- /* Next, create a string that will be passed to crypt, containing all
- * of the settings, separated by dollar signs
- */
- $param = '$' . implode('$', [
- '2x', //select the most secure version of blowfish (>=PHP 5.3.7)
- str_pad($cost, 2, '0', STR_PAD_LEFT), //add the cost in two digits
- $salt //add the salt
- ]);
-
- //now do the actual hashing
- return crypt($password, $param);
- }
-
- /**
- * 2 验证
- * Check the password against a hash generated by the generate_hash
- * function.
- *
- * @param $hash
- * @param $password
- *
- * @return bool
- */
- public static function verifyHash(string $hash, string $password): bool
- {
- /* Regenerating the with an available hash as the options parameter should
- * produce the same hash if the same password is passed.
- */
- return crypt($password, $hash) === $hash;
- }
-
- /**
- * 生成guid
- *
- * @return string
- */
- public static function GUID(): string
- {
- mt_srand((double)microtime() * 10000);
-
- $charId = strtolower(md5(uniqid(mt_rand(), true)));
- // $hyphen = chr(45);
- $uuid = substr($charId, 0, 8) . substr($charId, 8, 4) . substr($charId, 12, 4) . substr($charId, 16,
- 4) . substr($charId, 20, 12);
-
- return $uuid;
- }
-
-}
diff --git a/libs/str-utils/src/UUID.php b/libs/str-utils/src/UUID.php
deleted file mode 100644
index d0198bd..0000000
--- a/libs/str-utils/src/UUID.php
+++ /dev/null
@@ -1,472 +0,0 @@
-bytes = $uuid;
-
- // Optimize the most common use
- $this->string = bin2hex(substr($uuid, 0, 4)) . '-' . bin2hex(substr($uuid, 4, 2)) . '-' . bin2hex(substr($uuid,
- 6, 2)) . '-' . bin2hex(substr($uuid, 8, 2)) . '-' . bin2hex(substr($uuid, 10, 6));
- }
-
- /**
- * Generates a Version 1 UUID.
- * These are derived from the time at which they were generated.
- *
- * @param string $node
- *
- * @return string
- * @throws Exception
- */
- protected static function mintTime(string $node = null): string
- {
- /** Get time since Gregorian calendar reform in 100ns intervals
- * This is exceedingly difficult because of PHP's (and pack()'s)
- * integer size limits.
- * Note that this will never be more accurate than to the microsecond.
- */
- $time = microtime(1) * 10000000 + static::INTERVAL;
-
- // Convert to a string representation
- $time = sprintf('%F', $time);
-
- //strip decimal point
- preg_match("/^\d+/", $time, $time);
-
- // And now to a 64-bit binary representation
- $time = base_convert($time[0], 10, 16);
- $time = pack('H*', str_pad($time, 16, '0', STR_PAD_LEFT));
-
- // Reorder bytes to their proper locations in the UUID
- $uuid = $time[4] . $time[5] . $time[6] . $time[7] . $time[2] . $time[3] . $time[0] . $time[1];
-
- // Generate a random clock sequence
- $uuid .= static::randomBytes(2);
-
- // set variant
- $uuid[8] = chr(ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC);
-
- // set version
- $uuid[6] = chr(ord($uuid[6]) & static::CLEAR_VER | static::VERSION_1);
-
- // Set the final 'node' parameter, a MAC address
- if (null !== $node) {
- $node = static::makeBin($node, 6);
- }
-
- // If no node was provided or if the node was invalid,
- // generate a random MAC address and set the multicast bit
- if (null === $node) {
- $node = static::randomBytes(6);
- $node[0] = pack('C', ord($node[0]) | 1);
- }
-
- $uuid .= $node;
- return $uuid;
- }
-
- /**
- * Randomness is returned as a string of bytes
- *
- * @param int $bytes
- *
- * @return string
- * @throws Exception
- */
- public static function randomBytes($bytes): string
- {
- return random_bytes($bytes);
- }
-
- /**
- * Insure that an input string is either binary or hexadecimal.
- * Returns binary representation, or false on failure.
- *
- * @param string|self $str
- * @param integer $len
- *
- * @return string|null
- */
- protected static function makeBin($str, $len): ?string
- {
- if ($str instanceof self) {
- return $str->bytes;
- }
-
- if (strlen($str) === $len) {
- return $str;
- }
-
- $str = (string)preg_replace([
- // strip URN scheme and namespace
- '/^urn:uuid:/is',
- // strip non-hex characters
- '/[^a-f0-9]/is',
- ], '', $str);
-
- if (strlen($str) !== ($len * 2)) {
- return null;
- }
-
- return pack('H*', $str);
- }
-
- /**
- * Generates a Version 3 or Version 5 UUID.
- * These are derived from a hash of a name and its namespace, in binary form.
- *
- * @param int $ver
- * @param string $node
- * @param string|null $ns
- *
- * @return string
- * @throws InvalidArgumentException
- */
- protected static function mintName($ver, $node, $ns): string
- {
- if (empty($node)) {
- throw new InvalidArgumentException('A name-string is required for Version 3 or 5 UUIDs.');
- }
-
- // if the namespace UUID isn't binary, make it so
- $ns = static::makeBin($ns, 16);
- if (null === $ns) {
- throw new InvalidArgumentException('A binary namespace is required for Version 3 or 5 UUIDs.');
- }
-
- $version = $uuid = null;
-
- switch ($ver) {
- case static::MD5:
- $version = static::VERSION_3;
- $uuid = md5($ns . $node, 1);
- break;
- case static::SHA1:
- $version = static::VERSION_5;
- $uuid = substr(sha1($ns . $node, 1), 0, 16);
- break;
- default:
- // no default really required here
- }
-
- // set variant
- $uuid[8] = chr(ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC);
-
- // set version
- $uuid[6] = chr(ord($uuid[6]) & static::CLEAR_VER | $version);
-
- return $uuid;
- }
-
- /**
- * Generate a Version 4 UUID.
- * These are derived solely from random numbers.
- * generate random fields
- *
- * @return string
- * @throws Exception
- */
- protected static function mintRand(): string
- {
- $uuid = static::randomBytes(16);
- // set variant
- $uuid[8] = chr(ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC);
- // set version
- $uuid[6] = chr(ord($uuid[6]) & static::CLEAR_VER | static::VERSION_4);
-
- return $uuid;
- }
-
- /**
- * Import an existing UUID
- *
- * @param string $uuid
- *
- * @return Uuid
- * @throws InvalidArgumentException
- */
- public static function import(string $uuid): UUID
- {
- return new static(static::makeBin($uuid, 16));
- }
-
- /**
- * Compares the binary representations of two UUIDs.
- * The comparison will return true if they are bit-exact,
- * or if neither is valid.
- *
- * @param string $a
- * @param string $b
- *
- * @return string|string
- */
- public static function compare(string $a, string $b): string
- {
- return static::makeBin($a, 16) === static::makeBin($b, 16);
- }
-
- /**
- * Import and validate an UUID
- *
- * @param Uuid|string $uuid
- *
- * @return boolean
- * @throws InvalidArgumentException
- */
- public static function validate(string $uuid): bool
- {
- return (boolean)preg_match('~' . static::VALID_UUID_REGEX . '~', static::import($uuid)->string);
- }
-
- public function __isset($var)
- {
- //
- }
-
- public function __set($var, $val)
- {
- //
- }
-
- /**
- * @param string $var
- *
- * @return string|int|NULL
- */
- public function __get(string $var)
- {
- switch ($var) {
- case 'bytes':
- return $this->bytes;
- break;
- case 'hex':
- return bin2hex($this->bytes);
- break;
- case 'node':
- if (ord($this->bytes[6]) >> 4 === 1) {
- return bin2hex(substr($this->bytes, 10));
- }
-
- return null;
- break;
- case 'string':
- return $this->__toString();
- break;
- case 'time':
- if (ord($this->bytes[6]) >> 4 === 1) {
- // Restore contiguous big-endian byte order
- $time = bin2hex($this->bytes[6] . $this->bytes[7] . $this->bytes[4] . $this->bytes[5] . $this->bytes[0] . $this->bytes[1] . $this->bytes[2] . $this->bytes[3]);
- // Clear version flag
- $time[0] = '0';
-
- // Do some reverse arithmetic to get a Unix timestamp
- return (hexdec($time) - static::INTERVAL) / 10000000;
- }
-
- break;
- case 'urn':
- return 'urn:uuid:' . $this->__toString();
- break;
- case 'variant':
- $byte = ord($this->bytes[8]);
- if ($byte >= static::VAR_RES) {
- return 3;
- }
-
- if ($byte >= static::VAR_MS) {
- return 2;
- }
-
- if ($byte >= static::VAR_RFC) {
- return 1;
- }
-
- return 0;
- break;
- case 'version':
- return ord($this->bytes[6]) >> 4;
- break;
- default:
- return null;
- break;
- }
-
- return null;
- }
-
- /**
- * Return the UUID
- *
- * @return string
- */
- public function __toString()
- {
- return $this->string;
- }
-}
diff --git a/libs/str-utils/src/UrlHelper.php b/libs/str-utils/src/UrlHelper.php
deleted file mode 100644
index 7450510..0000000
--- a/libs/str-utils/src/UrlHelper.php
+++ /dev/null
@@ -1,242 +0,0 @@
- 0;
- } else {
- $opts = [
- 'http' => ['timeout' => 5,]
- ];
- $context = stream_context_create($opts);
- $resource = file_get_contents($url, false, $context);
-
- return (bool)$resource;
- }
-
- return false;
- }
-
- // Build arrays of values we need to decode before parsing
- protected static $entities = [
- '%21',
- '%2A',
- '%27',
- '%28',
- '%29',
- '%3B',
- '%3A',
- '%40',
- '%26',
- '%3D',
- '%24',
- '%2C',
- '%2F',
- '%3F',
- '%23',
- '%5B',
- '%5D'
- ];
-
- protected static $replacements = [
- '!',
- '*',
- "'",
- '(',
- ')',
- ';',
- ':',
- '@',
- '&',
- '=',
- '$',
- ',',
- '/',
- '?',
- '#',
- '[',
- ']'
- ];
-
- public static function parseUrl(string $url): array
- {
- $result = [];
-
- // Create encoded URL with special URL characters decoded so it can be parsed
- // All other characters will be encoded
- $encodedURL = str_replace(self::$entities, self::$replacements, urlencode($url));
-
- // Parse the encoded URL
- $encodedParts = parse_url($encodedURL);
-
- // Now, decode each value of the resulting array
- if ($encodedParts) {
- foreach ((array)$encodedParts as $key => $value) {
- $result[$key] = urldecode(str_replace(self::$replacements, self::$entities, $value));
- }
- }
-
- return $result;
- }
-
- /**
- * url_encode form urlencode(),但是 : / ? & = ...... 几个符号不会被转码为 %3A %2F %3F %26 %3D ......
- * $url="ftp://ud03:password@www.xxx.net/中文/中文.rar";
- * $url1 = url_encode1($url);
- * //ftp://ud03:password@www.xxx.net/%E4%B8%AD%E6%96%87/%E4%B8%AD%E6%96%87.rar
- * $url2 = urldecode($url);
- * echo $url1.PHP_EOL.$url2.PHP_EOL;
- *
- * @param $url
- *
- * @return mixed|string [type] [description]
- */
- public static function encode(string $url)
- {
- $url = trim($url);
-
- if ($url === '') {
- return $url;
- }
-
- // 若已被编码的url,将被解码,再继续重新编码
- $url = urldecode($url);
- $encodeUrl = urlencode($url);
- $encodeUrl = str_replace(self::$entities, self::$replacements, $encodeUrl);
-
- return $encodeUrl;
- }
-
- /**
- * [urlEncode 会先转换编码]
- * $url="ftp://ud03:password@www.xxx.net/中文/中文.rar";
- * $url1 = url_encode($url);
- * //ftp://ud03:password@www.xxx.net/%C3%A4%C2%B8%C2%AD%C3%A6%C2%96%C2%87/%C3%A4%C2%B8%C2%AD%C3%A6%C2%96%C2%87.rar
- * $url2 = urldecode($url);
- * echo $url1.PHP_EOL.$url2;
- *
- * @param string $url [description]
- *
- * @return mixed|string [type] [description]
- */
- public static function encode2(string $url)
- {
- if (!$url = trim($url)) {
- return $url;
- }
-
- // 若已被编码的url,将被解码,再继续重新编码
- $url = urldecode($url);
- $encodeUrl = rawurlencode(mb_convert_encoding($url, 'utf-8'));
- // $url = rawurlencode($url);
- $encodeUrl = str_replace(self::$entities, self::$replacements, $encodeUrl);
-
- return $encodeUrl;
- }
-}
diff --git a/libs/str-utils/test/boot.php b/libs/str-utils/test/boot.php
deleted file mode 100644
index b00f6f4..0000000
--- a/libs/str-utils/test/boot.php
+++ /dev/null
@@ -1,27 +0,0 @@
-7.1.0"
- },
- "autoload": {
- "psr-4": {
- "Toolkit\\Sys\\": "src/"
- }
- },
- "suggest": {
- "inhere/php-validate": "Very lightweight data validate tool",
- "inhere/console": "a lightweight php console application library."
- }
-}
diff --git a/libs/sys-utils/phpunit.xml.dist b/libs/sys-utils/phpunit.xml.dist
deleted file mode 100644
index 6052813..0000000
--- a/libs/sys-utils/phpunit.xml.dist
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
-
-
- test/
-
-
-
-
-
- src
-
-
-
diff --git a/libs/sys-utils/src/ProcessUtil.php b/libs/sys-utils/src/ProcessUtil.php
deleted file mode 100644
index 7e110db..0000000
--- a/libs/sys-utils/src/ProcessUtil.php
+++ /dev/null
@@ -1,715 +0,0 @@
- 'SIGINT(Ctrl+C)',
- SIGTERM => 'SIGTERM',
- SIGKILL => 'SIGKILL',
- SIGSTOP => 'SIGSTOP',
- ];
-
- /**
- * fork/create a child process.
- *
- * @param callable|null $onStart Will running on the child process start.
- * @param callable|null $onError
- * @param int $id The process index number. will use `forks()`
- *
- * @return array|false
- * @throws RuntimeException
- */
- public static function fork(callable $onStart = null, callable $onError = null, $id = 0)
- {
- if (!self::hasPcntl()) {
- return false;
- }
-
- $info = [];
- $pid = pcntl_fork();
-
- // at parent, get forked child info
- if ($pid > 0) {
- $info = [
- 'id' => $id,
- 'pid' => $pid,
- 'startTime' => time(),
- ];
- } elseif ($pid === 0) { // at child
- $pid = self::getPid();
-
- if ($onStart) {
- $onStart($pid, $id);
- }
- } else {
- if ($onError) {
- $onError($pid);
- }
-
- throw new RuntimeException('Fork child process failed! exiting.');
- }
-
- return $info;
- }
-
- /**
- * @param callable|null $onStart
- * @param callable|null $onError
- * @param int $id
- *
- * @return array|false
- * @throws RuntimeException
- * @see ProcessUtil::fork()
- */
- public static function create(callable $onStart = null, callable $onError = null, $id = 0)
- {
- return self::fork($onStart, $onError, $id);
- }
-
- /**
- * Daemon, detach and run in the background
- *
- * @param Closure|null $beforeQuit
- *
- * @return int Return new process PID
- * @throws RuntimeException
- */
- public static function daemonRun(Closure $beforeQuit = null): int
- {
- if (!self::hasPcntl()) {
- return 0;
- }
-
- // umask(0);
- $pid = pcntl_fork();
-
- switch ($pid) {
- case 0: // at new process
- $pid = self::getPid();
-
- if (posix_setsid() < 0) {
- throw new RuntimeException('posix_setsid() execute failed! exiting');
- }
-
- // chdir('/');
- // umask(0);
- break;
-
- case -1: // fork failed.
- throw new RuntimeException('Fork new process is failed! exiting');
- break;
-
- default: // at parent
- if ($beforeQuit) {
- $beforeQuit($pid);
- }
-
- exit;
- }
-
- return $pid;
- }
-
- /**
- * @param int $number
- * @param callable|null $onStart
- * @param callable|null $onError
- *
- * @return array|false
- * @throws RuntimeException
- * @see ProcessUtil::forks()
- */
- public static function multi(int $number, callable $onStart = null, callable $onError = null)
- {
- return self::forks($number, $onStart, $onError);
- }
-
- /**
- * fork/create multi child processes.
- *
- * @param int $number
- * @param callable|null $onStart Will running on the child processes.
- * @param callable|null $onError
- *
- * @return array|false
- * @throws RuntimeException
- */
- public static function forks(int $number, callable $onStart = null, callable $onError = null)
- {
- if ($number <= 0) {
- return false;
- }
-
- if (!self::hasPcntl()) {
- return false;
- }
-
- $pidAry = [];
-
- for ($id = 0; $id < $number; $id++) {
- $info = self::fork($onStart, $onError, $id);
- $pidAry[$info['pid']] = $info;
- }
-
- return $pidAry;
- }
-
- /**
- * wait child exit.
- *
- * @param callable $onExit Exit callback. will received args: (pid, exitCode, status)
- *
- * @return bool
- */
- public static function wait(callable $onExit): bool
- {
- if (!self::hasPcntl()) {
- return false;
- }
-
- $status = null;
-
- // pid < 0:子进程都没了
- // pid > 0:捕获到一个子进程退出的情况
- // pid = 0:没有捕获到退出的子进程
- while (($pid = pcntl_waitpid(-1, $status, WNOHANG)) >= 0) {
- if ($pid) {
- // handler(pid, exitCode, status)
- $onExit($pid, pcntl_wexitstatus($status), $status);
- } else {
- usleep(50000);
- }
- }
-
- return true;
- }
-
- /**
- * Stops all running children
- *
- * @param array $children
- * [
- * 'pid' => [
- * 'id' => worker id
- * ],
- * ... ...
- * ]
- * @param int $signal
- * @param array $events
- * [
- * 'beforeStops' => function ($sigText) {
- * echo "Stopping processes({$sigText}) ...\n";
- * },
- * 'beforeStop' => function ($pid, $info) {
- * echo "Stopping process(PID:$pid)\n";
- * }
- * ]
- *
- * @return bool
- */
- public static function stopWorkers(array $children, int $signal = SIGTERM, array $events = []): bool
- {
- if (!$children) {
- return false;
- }
-
- if (!self::hasPcntl()) {
- return false;
- }
-
- $events = array_merge([
- 'beforeStops' => null,
- 'beforeStop' => null,
- ], $events);
-
- if ($cb = $events['beforeStops']) {
- $cb($signal, self::$signalMap[$signal]);
- }
-
- foreach ($children as $pid => $child) {
- if ($cb = $events['beforeStop']) {
- $cb($pid, $child);
- }
-
- // send exit signal.
- self::sendSignal($pid, $signal);
- }
-
- return true;
- }
-
- /**************************************************************************************
- * basic signal methods
- *************************************************************************************/
-
- /**
- * send kill signal to the process
- *
- * @param int $pid
- * @param bool $force
- * @param int $timeout
- *
- * @return bool
- */
- public static function kill(int $pid, bool $force = false, int $timeout = 3): bool
- {
- return self::sendSignal($pid, $force ? SIGKILL : SIGTERM, $timeout);
- }
-
- /**
- * Do shutdown process and wait it exit.
- *
- * @param int $pid Master Pid
- * @param bool $force
- * @param int $waitTime
- * @param null $error
- * @param string $name
- *
- * @return bool
- */
- public static function killAndWait(
- int $pid,
- &$error = null,
- $name = 'process',
- bool $force = false,
- int $waitTime = 10
- ): bool {
- // do stop
- if (!self::kill($pid, $force)) {
- $error = "Send stop signal to the $name(PID:$pid) failed!";
-
- return false;
- }
-
- // not wait, only send signal
- if ($waitTime <= 0) {
- $error = "The $name process stopped";
-
- return true;
- }
-
- $startTime = time();
- echo 'Stopping .';
-
- // wait exit
- while (true) {
- if (!self::isRunning($pid)) {
- break;
- }
-
- if (time() - $startTime > $waitTime) {
- $error = "Stop the $name(PID:$pid) failed(timeout)!";
- break;
- }
-
- echo '.';
- sleep(1);
- }
-
- if ($error) {
- return false;
- }
-
- return true;
- }
-
- /**
- * @param int $pid
- *
- * @return bool
- */
- public static function isRunning(int $pid): bool
- {
- return ($pid > 0) && @posix_kill($pid, 0);
- }
-
- /**
- * exit
- *
- * @param int $code
- */
- public static function quit($code = 0): void
- {
- exit((int)$code);
- }
-
- /**
- * 杀死所有进程
- *
- * @param $name
- * @param int $sigNo
- *
- * @return string
- */
- public static function killByName(string $name, int $sigNo = 9): string
- {
- $cmd = 'ps -eaf |grep "' . $name . '" | grep -v "grep"| awk "{print $2}"|xargs kill -' . $sigNo;
-
- return exec($cmd);
- }
-
- /**************************************************************************************
- * process signal handle
- *************************************************************************************/
-
- /**
- * send signal to the process
- *
- * @param int $pid
- * @param int $signal
- * @param int $timeout
- *
- * @return bool
- */
- public static function sendSignal(int $pid, int $signal, int $timeout = 0): bool
- {
- if ($pid <= 0 || !self::hasPosix()) {
- return false;
- }
-
- // do send
- if ($ret = posix_kill($pid, $signal)) {
- return true;
- }
-
- // don't want retry
- if ($timeout <= 0) {
- return $ret;
- }
-
- // failed, try again ...
- $timeout = $timeout > 0 && $timeout < 10 ? $timeout : 3;
- $startTime = time();
-
- // retry stop if not stopped.
- while (true) {
- // success
- if (!$isRunning = @posix_kill($pid, 0)) {
- break;
- }
-
- // have been timeout
- if ((time() - $startTime) >= $timeout) {
- return false;
- }
-
- // try again kill
- $ret = posix_kill($pid, $signal);
- usleep(10000);
- }
-
- return $ret;
- }
-
- /**
- * install signal
- *
- * @param int $signal e.g: SIGTERM SIGINT(Ctrl+C) SIGUSR1 SIGUSR2 SIGHUP
- * @param callable $handler
- *
- * @return bool
- */
- public static function installSignal($signal, callable $handler): bool
- {
- if (!self::hasPcntl()) {
- return false;
- }
-
- return pcntl_signal($signal, $handler, false);
- }
-
- /**
- * dispatch signal
- *
- * @return bool
- */
- public static function dispatchSignal(): bool
- {
- if (!self::hasPcntl()) {
- return false;
- }
-
- // receive and dispatch signal
- return pcntl_signal_dispatch();
- }
-
- /**
- * get signal handler
- *
- * @param int $signal
- *
- * @return bool|string|mixed
- * @since 7.1
- */
- public static function getSignalHandler(int $signal)
- {
- return pcntl_signal_get_handler($signal);
- }
-
- /**
- * Enable/disable asynchronous signal handling or return the old setting
- *
- * @param bool|null $on
- * - bool Enable or disable.
- * - null Return old setting.
- *
- * @return bool
- * @since 7.1
- */
- public static function asyncSignal(bool $on = null): bool
- {
- return pcntl_async_signals($on);
- }
-
- /**************************************************************************************
- * some help method
- *************************************************************************************/
-
- /**
- * get current process id
- *
- * @return int
- */
- public static function getPid(): int
- {
- if (function_exists('posix_getpid')) {
- return posix_getpid();
- }
-
- return getmypid();
- }
-
- /**
- * get PID by pid File
- *
- * @param string $file
- * @param bool $checkLive
- *
- * @return int
- */
- public static function getPidByFile(string $file, bool $checkLive = false): int
- {
- if ($file && file_exists($file)) {
- $pid = (int)file_get_contents($file);
-
- // check live
- if ($checkLive && self::isRunning($pid)) {
- return $pid;
- }
-
- unlink($file);
- }
-
- return 0;
- }
-
- /**
- * Get unix user of current process.
- *
- * @return array
- */
- public static function getCurrentUser(): array
- {
- return posix_getpwuid(posix_getuid());
- }
-
- /**
- *
- * ProcessUtil::afterDo(300, function () {
- * static $i = 0;
- * echo "#{$i}\talarm\n";
- * $i++;
- * if ($i > 20) {
- * ProcessUtil::clearAlarm(); // close
- * }
- * });
- *
- * @param int $seconds
- * @param callable $handler
- *
- * @return bool|int
- */
- public static function afterDo(int $seconds, callable $handler)
- {
- if (!self::hasPcntl()) {
- return false;
- }
-
- self::installSignal(SIGALRM, $handler);
-
- return pcntl_alarm($seconds);
- }
-
- /**
- * @return int
- */
- public static function clearAlarm(): int
- {
- return pcntl_alarm(-1);
- }
-
- /**
- * run a command. it is support windows
- *
- * @param string $command
- * @param string|null $cwd
- *
- * @return array
- * @throws RuntimeException
- * @deprecated Please use Sys::run()
- */
- public static function run(string $command, string $cwd = null): array
- {
- return Sys::run($command, $cwd);
- }
-
- /**
- * Set process title.
- *
- * @param string $title
- *
- * @return bool
- */
- public static function setName(string $title): bool
- {
- return self::setTitle($title);
- }
-
- /**
- * Set process title.
- *
- * @param string $title
- *
- * @return bool
- */
- public static function setTitle(string $title): bool
- {
- if (!$title || 'Darwin' === PHP_OS) {
- return false;
- }
-
- if (function_exists('cli_set_process_title')) {
- cli_set_process_title($title);
- } elseif (function_exists('setproctitle')) {
- setproctitle($title);
- }
-
- if ($error = error_get_last()) {
- throw new RuntimeException($error['message']);
- }
-
- return false;
- }
-
- /**
- * Set unix user and group for current process script.
- *
- * @param string $user
- * @param string $group
- *
- * @throws RuntimeException
- */
- public static function changeScriptOwner(string $user, string $group = ''): void
- {
- $uInfo = posix_getpwnam($user);
-
- if (!$uInfo || !isset($uInfo['uid'])) {
- throw new RuntimeException("User ({$user}) not found.");
- }
-
- $uid = (int)$uInfo['uid'];
-
- // Get gid.
- if ($group) {
- if (!$gInfo = posix_getgrnam($group)) {
- throw new RuntimeException("Group {$group} not exists", -300);
- }
-
- $gid = (int)$gInfo['gid'];
- } else {
- $gid = (int)$uInfo['gid'];
- }
-
- if (!posix_initgroups($uInfo['name'], $gid)) {
- throw new RuntimeException("The user [{$user}] is not in the user group ID [GID:{$gid}]", -300);
- }
-
- posix_setgid($gid);
-
- if (posix_geteuid() !== $gid) {
- throw new RuntimeException("Unable to change group to {$user} (UID: {$gid}).", -300);
- }
-
- posix_setuid($uid);
-
- if (posix_geteuid() !== $uid) {
- throw new RuntimeException("Unable to change user to {$user} (UID: {$uid}).", -300);
- }
- }
-
- /**
- * @return bool
- */
- public static function hasPcntl(): bool
- {
- return !Sys::isWindows() && function_exists('pcntl_fork');
- }
-
- /**
- * @return bool
- */
- public static function hasPosix(): bool
- {
- return !Sys::isWindows() && function_exists('posix_kill');
- }
-}
diff --git a/libs/sys-utils/src/Signal.php b/libs/sys-utils/src/Signal.php
deleted file mode 100644
index 64be458..0000000
--- a/libs/sys-utils/src/Signal.php
+++ /dev/null
@@ -1,58 +0,0 @@
-> \"$logfile\" 2>&1", $dummy, $retVal);
-
- if ($retVal !== 0) {
- throw new RuntimeException("command exited with status '$retVal'.");
- }
-
- return $dummy;
- }
-
- /**
- * run a command. it is support windows
- *
- * @param string $command
- * @param string|null $cwd
- *
- * @return array
- * @throws RuntimeException
- */
- public static function run(string $command, string $cwd = null): array
- {
- $descriptors = [
- 0 => ['pipe', 'r'], // stdin - read channel
- 1 => ['pipe', 'w'], // stdout - write channel
- 2 => ['pipe', 'w'], // stdout - error channel
- 3 => ['pipe', 'r'], // stdin - This is the pipe we can feed the password into
- ];
-
- $process = proc_open($command, $descriptors, $pipes, $cwd);
-
- if (!is_resource($process)) {
- throw new RuntimeException("Can't open resource with proc_open.");
- }
-
- // Nothing to push to input.
- fclose($pipes[0]);
-
- $output = stream_get_contents($pipes[1]);
- fclose($pipes[1]);
-
- $error = stream_get_contents($pipes[2]);
- fclose($pipes[2]);
-
- // TODO: Write passphrase in pipes[3].
- fclose($pipes[3]);
-
- // Close all pipes before proc_close! $code === 0 is success.
- $code = proc_close($process);
-
- return [$code, $output, $error];
- }
-
- /**
- * Method to execute a command in the sys
- * Uses :
- * 1. system
- * 2. passthru
- * 3. exec
- * 4. shell_exec
- *
- * @param string $command
- * @param bool $returnStatus
- * @param string|null $cwd
- *
- * @return array|string
- */
- public static function execute(string $command, bool $returnStatus = true, string $cwd = null)
- {
- $exitStatus = 1;
-
- if ($cwd) {
- chdir($cwd);
- }
-
- // system
- if (function_exists('system')) {
- ob_start();
- system($command, $exitStatus);
- $output = ob_get_contents();
- ob_end_clean();
-
- // passthru
- } elseif (function_exists('passthru')) {
- ob_start();
- passthru($command, $exitStatus);
- $output = ob_get_contents();
- ob_end_clean();
- //exec
- } elseif (function_exists('exec')) {
- exec($command, $output, $exitStatus);
- $output = implode("\n", $output);
-
- //shell_exec
- } elseif (function_exists('shell_exec')) {
- $output = shell_exec($command);
- } else {
- $output = 'Command execution not possible on this system';
- $exitStatus = 0;
- }
-
- if ($returnStatus) {
- return [
- 'output' => trim($output),
- 'status' => $exitStatus
- ];
- }
-
- return trim($output);
- }
-
- /**
- * run a command in background
- *
- * @param string $cmd
- */
- public static function bgExec(string $cmd): void
- {
- self::execInBackground($cmd);
- }
-
- /**
- * run a command in background
- *
- * @param string $cmd
- */
- public static function execInBackground(string $cmd): void
- {
- if (self::isWindows()) {
- pclose(popen('start /B ' . $cmd, 'r'));
- } else {
- exec($cmd . ' > /dev/null &');
- }
- }
-
- /**
- * Get unix user of current process.
- *
- * @return array
- */
- public static function getCurrentUser(): array
- {
- return posix_getpwuid(posix_getuid());
- }
-
- /**
- * @return string
- */
- public static function tempDir(): string
- {
- return self::getTempDir();
- }
-
- /**
- * @return string
- */
- public static function getTempDir(): string
- {
- // @codeCoverageIgnoreStart
- if (function_exists('sys_get_temp_dir')) {
- $tmp = sys_get_temp_dir();
- } elseif (!empty($_SERVER['TMP'])) {
- $tmp = $_SERVER['TMP'];
- } elseif (!empty($_SERVER['TEMP'])) {
- $tmp = $_SERVER['TEMP'];
- } elseif (!empty($_SERVER['TMPDIR'])) {
- $tmp = $_SERVER['TMPDIR'];
- } else {
- $tmp = getcwd();
- }
- // @codeCoverageIgnoreEnd
-
- return $tmp;
- }
-
- /**
- * get bash is available
- *
- * @return bool
- */
- public static function shIsAvailable(): bool
- {
- // $checkCmd = "/usr/bin/env bash -c 'echo OK'";
- // $shell = 'echo $0';
- $checkCmd = "sh -c 'echo OK'";
-
- return self::execute($checkCmd, false) === 'OK';
- }
-
- /**
- * get bash is available
- *
- * @return bool
- */
- public static function bashIsAvailable(): bool
- {
- // $checkCmd = "/usr/bin/env bash -c 'echo OK'";
- // $shell = 'echo $0';
- $checkCmd = "bash -c 'echo OK'";
-
- return self::execute($checkCmd, false) === 'OK';
- }
-
- /**
- * @return string
- */
- public static function getOutsideIP(): string
- {
- [$code, $output] = self::run('ip addr | grep eth0');
-
- if ($code === 0 && $output && preg_match('#inet (.*)\/#', $output, $ms)) {
- return $ms[1];
- }
-
- return 'unknown';
- }
-
- /**
- * get screen size
- *
- * ```php
- * list($width, $height) = Sys::getScreenSize();
- * ```
- *
- * @from Yii2
- *
- * @param boolean $refresh whether to force checking and not re-use cached size value.
- * This is useful to detect changing window size while the application is running but may
- * not get up to date values on every terminal.
- *
- * @return array|boolean An array of ($width, $height) or false when it was not able to determine size.
- */
- public static function getScreenSize(bool $refresh = false)
- {
- static $size;
- if ($size !== null && !$refresh) {
- return $size;
- }
-
- if (self::shIsAvailable()) {
- // try stty if available
- $stty = [];
-
- if (exec('stty -a 2>&1', $stty) && preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty),
- $matches)
- ) {
- return ($size = [$matches[2], $matches[1]]);
- }
-
- // fallback to tput, which may not be updated on terminal resize
- if (($width = (int)exec('tput cols 2>&1')) > 0 && ($height = (int)exec('tput lines 2>&1')) > 0) {
- return ($size = [$width, $height]);
- }
-
- // fallback to ENV variables, which may not be updated on terminal resize
- if (($width = (int)getenv('COLUMNS')) > 0 && ($height = (int)getenv('LINES')) > 0) {
- return ($size = [$width, $height]);
- }
- }
-
- if (self::isWindows()) {
- $output = [];
- exec('mode con', $output);
-
- if (isset($output[1]) && strpos($output[1], 'CON') !== false) {
- return ($size = [
- (int)preg_replace('~\D~', '', $output[3]),
- (int)preg_replace('~\D~', '', $output[4])
- ]);
- }
- }
-
- return ($size = false);
- }
-
- /**
- * @param string $program
- *
- * @return int|string
- */
- public static function getCpuUsage(string $program)
- {
- if (!$program) {
- return -1;
- }
-
- $info = exec('ps aux | grep ' . $program . ' | grep -v grep | grep -v su | awk {"print $3"}');
-
- return $info;
- }
-
- /**
- * @param string $program
- *
- * @return int|string
- */
- public static function getMemUsage(string $program)
- {
- if (!$program) {
- return -1;
- }
-
- $info = exec('ps aux | grep ' . $program . ' | grep -v grep | grep -v su | awk {"print $4"}');
-
- return $info;
- }
-}
diff --git a/libs/sys-utils/src/SysEnv.php b/libs/sys-utils/src/SysEnv.php
deleted file mode 100644
index 8db3479..0000000
--- a/libs/sys-utils/src/SysEnv.php
+++ /dev/null
@@ -1,145 +0,0 @@
-exists($path);
}
- public function reset()
+ public function reset(): Collection
{
$this->data = [];
@@ -167,12 +167,10 @@ public function reset()
/**
* Clear all data.
- *
- * @return static
*/
- public function clear()
+ public function clear(): void
{
- return $this->reset();
+ $this->reset();
}
/**
diff --git a/libs/collection/src/CollectionInterface.php b/src/collection/src/CollectionInterface.php
similarity index 95%
rename from libs/collection/src/CollectionInterface.php
rename to src/collection/src/CollectionInterface.php
index ffb86a9..7a5396b 100644
--- a/libs/collection/src/CollectionInterface.php
+++ b/src/collection/src/CollectionInterface.php
@@ -44,5 +44,5 @@ public function remove($key);
/**
* clear all data
*/
- public function clear();
+ public function clear(): void;
}
diff --git a/libs/collection/src/Configuration.php b/src/collection/src/Configuration.php
similarity index 100%
rename from libs/collection/src/Configuration.php
rename to src/collection/src/Configuration.php
diff --git a/libs/collection/src/JsonMessage.php b/src/collection/src/JsonMessage.php
similarity index 100%
rename from libs/collection/src/JsonMessage.php
rename to src/collection/src/JsonMessage.php
diff --git a/libs/collection/src/Language.php b/src/collection/src/Language.php
similarity index 100%
rename from libs/collection/src/Language.php
rename to src/collection/src/Language.php
diff --git a/libs/collection/src/LiteCollection.php b/src/collection/src/LiteCollection.php
similarity index 99%
rename from libs/collection/src/LiteCollection.php
rename to src/collection/src/LiteCollection.php
index c6147fb..90a0c42 100644
--- a/libs/collection/src/LiteCollection.php
+++ b/src/collection/src/LiteCollection.php
@@ -177,7 +177,7 @@ public function remove($key)
/**
* clear all data
*/
- public function clear()
+ public function clear(): void
{
foreach ($this as $key) {
unset($this[$key]);
diff --git a/libs/collection/src/SimpleCollection.php b/src/collection/src/SimpleCollection.php
similarity index 99%
rename from libs/collection/src/SimpleCollection.php
rename to src/collection/src/SimpleCollection.php
index 3562b39..8014a02 100644
--- a/libs/collection/src/SimpleCollection.php
+++ b/src/collection/src/SimpleCollection.php
@@ -244,7 +244,7 @@ public function remove($key)
/**
* Remove all items from collection
*/
- public function clear()
+ public function clear(): void
{
$this->data = [];
}
diff --git a/libs/collection/test/LanguageTest.php b/src/collection/test/LanguageTest.php
similarity index 100%
rename from libs/collection/test/LanguageTest.php
rename to src/collection/test/LanguageTest.php
diff --git a/libs/collection/test/boot.php b/src/collection/test/boot.php
similarity index 100%
rename from libs/collection/test/boot.php
rename to src/collection/test/boot.php
diff --git a/libs/collection/test/testdata/en/response.php b/src/collection/test/testdata/en/response.php
similarity index 100%
rename from libs/collection/test/testdata/en/response.php
rename to src/collection/test/testdata/en/response.php
diff --git a/libs/collection/test/testdata/zh-CN/response.php b/src/collection/test/testdata/zh-CN/response.php
similarity index 100%
rename from libs/collection/test/testdata/zh-CN/response.php
rename to src/collection/test/testdata/zh-CN/response.php
diff --git a/libs/collection/.gitignore b/src/data-parser/.gitignore
similarity index 100%
rename from libs/collection/.gitignore
rename to src/data-parser/.gitignore
diff --git a/libs/cli-utils/LICENSE b/src/data-parser/LICENSE
similarity index 100%
rename from libs/cli-utils/LICENSE
rename to src/data-parser/LICENSE
diff --git a/libs/data-parser/README.md b/src/data-parser/README.md
similarity index 100%
rename from libs/data-parser/README.md
rename to src/data-parser/README.md
diff --git a/libs/data-parser/composer.json b/src/data-parser/composer.json
similarity index 100%
rename from libs/data-parser/composer.json
rename to src/data-parser/composer.json
diff --git a/libs/data-parser/phpunit.xml.dist b/src/data-parser/phpunit.xml.dist
similarity index 100%
rename from libs/data-parser/phpunit.xml.dist
rename to src/data-parser/phpunit.xml.dist
diff --git a/libs/data-parser/src/AbstractDataParser.php b/src/data-parser/src/AbstractDataParser.php
similarity index 100%
rename from libs/data-parser/src/AbstractDataParser.php
rename to src/data-parser/src/AbstractDataParser.php
diff --git a/libs/data-parser/src/DataParserAwareTrait.php b/src/data-parser/src/DataParserAwareTrait.php
similarity index 100%
rename from libs/data-parser/src/DataParserAwareTrait.php
rename to src/data-parser/src/DataParserAwareTrait.php
diff --git a/libs/data-parser/src/DataParserInterface.php b/src/data-parser/src/DataParserInterface.php
similarity index 100%
rename from libs/data-parser/src/DataParserInterface.php
rename to src/data-parser/src/DataParserInterface.php
diff --git a/libs/data-parser/src/JsonParser.php b/src/data-parser/src/JsonParser.php
similarity index 100%
rename from libs/data-parser/src/JsonParser.php
rename to src/data-parser/src/JsonParser.php
diff --git a/libs/data-parser/src/MsgPackParser.php b/src/data-parser/src/MsgPackParser.php
similarity index 100%
rename from libs/data-parser/src/MsgPackParser.php
rename to src/data-parser/src/MsgPackParser.php
diff --git a/libs/data-parser/src/PhpParser.php b/src/data-parser/src/PhpParser.php
similarity index 100%
rename from libs/data-parser/src/PhpParser.php
rename to src/data-parser/src/PhpParser.php
diff --git a/libs/data-parser/src/SwooleParser.php b/src/data-parser/src/SwooleParser.php
similarity index 100%
rename from libs/data-parser/src/SwooleParser.php
rename to src/data-parser/src/SwooleParser.php
diff --git a/libs/data-parser/test/JsonParserTest.php b/src/data-parser/test/JsonParserTest.php
similarity index 100%
rename from libs/data-parser/test/JsonParserTest.php
rename to src/data-parser/test/JsonParserTest.php
diff --git a/libs/data-parser/test/PhpParserTest.php b/src/data-parser/test/PhpParserTest.php
similarity index 100%
rename from libs/data-parser/test/PhpParserTest.php
rename to src/data-parser/test/PhpParserTest.php
diff --git a/libs/data-parser/test/boot.php b/src/data-parser/test/boot.php
similarity index 100%
rename from libs/data-parser/test/boot.php
rename to src/data-parser/test/boot.php
diff --git a/libs/dev-helper/Console/DevController.php b/src/dev-helper/Console/DevController.php
similarity index 100%
rename from libs/dev-helper/Console/DevController.php
rename to src/dev-helper/Console/DevController.php
diff --git a/libs/data-parser/.gitignore b/src/di/.gitignore
similarity index 100%
rename from libs/data-parser/.gitignore
rename to src/di/.gitignore
diff --git a/libs/collection/LICENSE b/src/di/LICENSE
similarity index 100%
rename from libs/collection/LICENSE
rename to src/di/LICENSE
diff --git a/libs/di/README.md b/src/di/README.md
similarity index 100%
rename from libs/di/README.md
rename to src/di/README.md
diff --git a/libs/di/composer.json b/src/di/composer.json
similarity index 100%
rename from libs/di/composer.json
rename to src/di/composer.json
diff --git a/libs/di/example/di.php b/src/di/example/di.php
similarity index 100%
rename from libs/di/example/di.php
rename to src/di/example/di.php
diff --git a/libs/cli-utils/phpunit.xml.dist b/src/di/phpunit.xml.dist
similarity index 100%
rename from libs/cli-utils/phpunit.xml.dist
rename to src/di/phpunit.xml.dist
diff --git a/libs/di/src/CallableResolver.php b/src/di/src/CallableResolver.php
similarity index 100%
rename from libs/di/src/CallableResolver.php
rename to src/di/src/CallableResolver.php
diff --git a/libs/di/src/CallableResolverAwareTrait.php b/src/di/src/CallableResolverAwareTrait.php
similarity index 100%
rename from libs/di/src/CallableResolverAwareTrait.php
rename to src/di/src/CallableResolverAwareTrait.php
diff --git a/libs/di/src/Container.php b/src/di/src/Container.php
similarity index 100%
rename from libs/di/src/Container.php
rename to src/di/src/Container.php
diff --git a/libs/di/src/DIManager.php b/src/di/src/DIManager.php
similarity index 100%
rename from libs/di/src/DIManager.php
rename to src/di/src/DIManager.php
diff --git a/libs/di/src/Exception/DependencyResolutionException.php b/src/di/src/Exception/DependencyResolutionException.php
similarity index 100%
rename from libs/di/src/Exception/DependencyResolutionException.php
rename to src/di/src/Exception/DependencyResolutionException.php
diff --git a/libs/di/src/Exception/NotFoundException.php b/src/di/src/Exception/NotFoundException.php
similarity index 100%
rename from libs/di/src/Exception/NotFoundException.php
rename to src/di/src/Exception/NotFoundException.php
diff --git a/libs/di/src/NameAliasTrait.php b/src/di/src/NameAliasTrait.php
similarity index 100%
rename from libs/di/src/NameAliasTrait.php
rename to src/di/src/NameAliasTrait.php
diff --git a/libs/di/src/ObjectItem.php b/src/di/src/ObjectItem.php
similarity index 100%
rename from libs/di/src/ObjectItem.php
rename to src/di/src/ObjectItem.php
diff --git a/libs/di/src/ServiceProviderInterface.php b/src/di/src/ServiceProviderInterface.php
similarity index 100%
rename from libs/di/src/ServiceProviderInterface.php
rename to src/di/src/ServiceProviderInterface.php
diff --git a/libs/di/test/ContainerTest.php b/src/di/test/ContainerTest.php
similarity index 100%
rename from libs/di/test/ContainerTest.php
rename to src/di/test/ContainerTest.php
diff --git a/libs/di/test/MakeByMethod.php b/src/di/test/MakeByMethod.php
similarity index 100%
rename from libs/di/test/MakeByMethod.php
rename to src/di/test/MakeByMethod.php
diff --git a/libs/di/test/MakeByStatic.php b/src/di/test/MakeByStatic.php
similarity index 100%
rename from libs/di/test/MakeByStatic.php
rename to src/di/test/MakeByStatic.php
diff --git a/libs/di/test/SomeClass.php b/src/di/test/SomeClass.php
similarity index 100%
rename from libs/di/test/SomeClass.php
rename to src/di/test/SomeClass.php
diff --git a/libs/di/test/boot.php b/src/di/test/boot.php
similarity index 100%
rename from libs/di/test/boot.php
rename to src/di/test/boot.php
diff --git a/libs/di/.gitignore b/src/helper-utils/.gitignore
similarity index 100%
rename from libs/di/.gitignore
rename to src/helper-utils/.gitignore
diff --git a/libs/data-parser/LICENSE b/src/helper-utils/LICENSE
similarity index 100%
rename from libs/data-parser/LICENSE
rename to src/helper-utils/LICENSE
diff --git a/libs/helper-utils/README.md b/src/helper-utils/README.md
similarity index 100%
rename from libs/helper-utils/README.md
rename to src/helper-utils/README.md
diff --git a/libs/helper-utils/composer.json b/src/helper-utils/composer.json
similarity index 100%
rename from libs/helper-utils/composer.json
rename to src/helper-utils/composer.json
diff --git a/libs/file-utils/phpunit.xml.dist b/src/helper-utils/phpunit.xml.dist
similarity index 100%
rename from libs/file-utils/phpunit.xml.dist
rename to src/helper-utils/phpunit.xml.dist
diff --git a/libs/helper-utils/src/Helper/AssertHelper.php b/src/helper-utils/src/Helper/AssertHelper.php
similarity index 100%
rename from libs/helper-utils/src/Helper/AssertHelper.php
rename to src/helper-utils/src/Helper/AssertHelper.php
diff --git a/libs/helper-utils/src/Helper/DataHelper.php b/src/helper-utils/src/Helper/DataHelper.php
similarity index 100%
rename from libs/helper-utils/src/Helper/DataHelper.php
rename to src/helper-utils/src/Helper/DataHelper.php
diff --git a/libs/helper-utils/src/Helper/DateHelper.php b/src/helper-utils/src/Helper/DateHelper.php
similarity index 100%
rename from libs/helper-utils/src/Helper/DateHelper.php
rename to src/helper-utils/src/Helper/DateHelper.php
diff --git a/libs/helper-utils/src/Helper/DsnHelper.php b/src/helper-utils/src/Helper/DsnHelper.php
similarity index 100%
rename from libs/helper-utils/src/Helper/DsnHelper.php
rename to src/helper-utils/src/Helper/DsnHelper.php
diff --git a/libs/helper-utils/src/Helper/FormatHelper.php b/src/helper-utils/src/Helper/FormatHelper.php
similarity index 100%
rename from libs/helper-utils/src/Helper/FormatHelper.php
rename to src/helper-utils/src/Helper/FormatHelper.php
diff --git a/libs/helper-utils/src/Helper/Http.php b/src/helper-utils/src/Helper/Http.php
similarity index 100%
rename from libs/helper-utils/src/Helper/Http.php
rename to src/helper-utils/src/Helper/Http.php
diff --git a/libs/helper-utils/src/Helper/IntHelper.php b/src/helper-utils/src/Helper/IntHelper.php
similarity index 100%
rename from libs/helper-utils/src/Helper/IntHelper.php
rename to src/helper-utils/src/Helper/IntHelper.php
diff --git a/libs/helper-utils/src/Helper/SslHelper.php b/src/helper-utils/src/Helper/SslHelper.php
similarity index 100%
rename from libs/helper-utils/src/Helper/SslHelper.php
rename to src/helper-utils/src/Helper/SslHelper.php
diff --git a/libs/helper-utils/src/Helper/UtilHelper.php b/src/helper-utils/src/Helper/UtilHelper.php
similarity index 100%
rename from libs/helper-utils/src/Helper/UtilHelper.php
rename to src/helper-utils/src/Helper/UtilHelper.php
diff --git a/libs/helper-utils/src/Traits/AopProxyAwareTrait.php b/src/helper-utils/src/Traits/AopProxyAwareTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/AopProxyAwareTrait.php
rename to src/helper-utils/src/Traits/AopProxyAwareTrait.php
diff --git a/libs/helper-utils/src/Traits/Config/ConfigTrait.php b/src/helper-utils/src/Traits/Config/ConfigTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/Config/ConfigTrait.php
rename to src/helper-utils/src/Traits/Config/ConfigTrait.php
diff --git a/libs/helper-utils/src/Traits/Config/LiteConfigTrait.php b/src/helper-utils/src/Traits/Config/LiteConfigTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/Config/LiteConfigTrait.php
rename to src/helper-utils/src/Traits/Config/LiteConfigTrait.php
diff --git a/libs/helper-utils/src/Traits/Config/LiteOptionsTrait.php b/src/helper-utils/src/Traits/Config/LiteOptionsTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/Config/LiteOptionsTrait.php
rename to src/helper-utils/src/Traits/Config/LiteOptionsTrait.php
diff --git a/libs/helper-utils/src/Traits/Config/OptionsTrait.php b/src/helper-utils/src/Traits/Config/OptionsTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/Config/OptionsTrait.php
rename to src/helper-utils/src/Traits/Config/OptionsTrait.php
diff --git a/libs/helper-utils/src/Traits/Event/EventTrait.php b/src/helper-utils/src/Traits/Event/EventTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/Event/EventTrait.php
rename to src/helper-utils/src/Traits/Event/EventTrait.php
diff --git a/libs/helper-utils/src/Traits/Event/FixedEventStaticTrait.php b/src/helper-utils/src/Traits/Event/FixedEventStaticTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/Event/FixedEventStaticTrait.php
rename to src/helper-utils/src/Traits/Event/FixedEventStaticTrait.php
diff --git a/libs/helper-utils/src/Traits/Event/FixedEventTrait.php b/src/helper-utils/src/Traits/Event/FixedEventTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/Event/FixedEventTrait.php
rename to src/helper-utils/src/Traits/Event/FixedEventTrait.php
diff --git a/libs/helper-utils/src/Traits/Event/LiteEventStaticTrait.php b/src/helper-utils/src/Traits/Event/LiteEventStaticTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/Event/LiteEventStaticTrait.php
rename to src/helper-utils/src/Traits/Event/LiteEventStaticTrait.php
diff --git a/libs/helper-utils/src/Traits/Event/LiteEventTrait.php b/src/helper-utils/src/Traits/Event/LiteEventTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/Event/LiteEventTrait.php
rename to src/helper-utils/src/Traits/Event/LiteEventTrait.php
diff --git a/libs/helper-utils/src/Traits/LiteContainerStaticTrait.php b/src/helper-utils/src/Traits/LiteContainerStaticTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/LiteContainerStaticTrait.php
rename to src/helper-utils/src/Traits/LiteContainerStaticTrait.php
diff --git a/libs/helper-utils/src/Traits/LiteContainerTrait.php b/src/helper-utils/src/Traits/LiteContainerTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/LiteContainerTrait.php
rename to src/helper-utils/src/Traits/LiteContainerTrait.php
diff --git a/libs/helper-utils/src/Traits/LogProfileTrait.php b/src/helper-utils/src/Traits/LogProfileTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/LogProfileTrait.php
rename to src/helper-utils/src/Traits/LogProfileTrait.php
diff --git a/libs/helper-utils/src/Traits/LogShortTrait.php b/src/helper-utils/src/Traits/LogShortTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/LogShortTrait.php
rename to src/helper-utils/src/Traits/LogShortTrait.php
diff --git a/libs/helper-utils/src/Traits/NameAliasStaticTrait.php b/src/helper-utils/src/Traits/NameAliasStaticTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/NameAliasStaticTrait.php
rename to src/helper-utils/src/Traits/NameAliasStaticTrait.php
diff --git a/libs/helper-utils/src/Traits/NameAliasTrait.php b/src/helper-utils/src/Traits/NameAliasTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/NameAliasTrait.php
rename to src/helper-utils/src/Traits/NameAliasTrait.php
diff --git a/libs/helper-utils/src/Traits/PathAliasTrait.php b/src/helper-utils/src/Traits/PathAliasTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/PathAliasTrait.php
rename to src/helper-utils/src/Traits/PathAliasTrait.php
diff --git a/libs/helper-utils/src/Traits/PathResolverTrait.php b/src/helper-utils/src/Traits/PathResolverTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/PathResolverTrait.php
rename to src/helper-utils/src/Traits/PathResolverTrait.php
diff --git a/libs/helper-utils/src/Traits/RuntimeProfileTrait.php b/src/helper-utils/src/Traits/RuntimeProfileTrait.php
similarity index 100%
rename from libs/helper-utils/src/Traits/RuntimeProfileTrait.php
rename to src/helper-utils/src/Traits/RuntimeProfileTrait.php
diff --git a/libs/helper-utils/src/Util/AopProxy.php b/src/helper-utils/src/Util/AopProxy.php
similarity index 100%
rename from libs/helper-utils/src/Util/AopProxy.php
rename to src/helper-utils/src/Util/AopProxy.php
diff --git a/libs/helper-utils/src/Util/DataProxy.php b/src/helper-utils/src/Util/DataProxy.php
similarity index 100%
rename from libs/helper-utils/src/Util/DataProxy.php
rename to src/helper-utils/src/Util/DataProxy.php
diff --git a/libs/helper-utils/src/Util/DataResult.php b/src/helper-utils/src/Util/DataResult.php
similarity index 100%
rename from libs/helper-utils/src/Util/DataResult.php
rename to src/helper-utils/src/Util/DataResult.php
diff --git a/libs/helper-utils/src/Util/DeferredCallable.php b/src/helper-utils/src/Util/DeferredCallable.php
similarity index 100%
rename from libs/helper-utils/src/Util/DeferredCallable.php
rename to src/helper-utils/src/Util/DeferredCallable.php
diff --git a/libs/helper-utils/src/Util/Pipeline.php b/src/helper-utils/src/Util/Pipeline.php
similarity index 100%
rename from libs/helper-utils/src/Util/Pipeline.php
rename to src/helper-utils/src/Util/Pipeline.php
diff --git a/libs/helper-utils/src/Util/PipelineInterface.php b/src/helper-utils/src/Util/PipelineInterface.php
similarity index 100%
rename from libs/helper-utils/src/Util/PipelineInterface.php
rename to src/helper-utils/src/Util/PipelineInterface.php
diff --git a/libs/helper-utils/test/boot.php b/src/helper-utils/test/boot.php
similarity index 100%
rename from libs/helper-utils/test/boot.php
rename to src/helper-utils/test/boot.php