* Powered by PhpStorm * Created on 2023/1/12 */ use Hyperf\Codec\Json; use Singularity\HDK\Core\Service\UtilsService; use function Hyperf\Support\make; $utils = new UtilsService(); dataset('categories', [ [ 'source' => << << random_int(1, 9) ]; } catch (Exception $e) { continue; } } test('断言验证码可以正常生成指定长度', function (int $length) use ($utils) { try { $code = $utils->generateSecureCode($length); expect($code)->toHaveLength($length); } catch (Exception $e) { expect($e)->toBeNull(); } })->with($length_data)->group('pure', 'utils'); test('断言可以根据参数构建 URL', function (string $url, array $params, bool $anchorQuery, string $expect) use ($utils) { $url = $utils->buildUrl(url: $url, moreQueries: $params, anchorQuery: $anchorQuery); expect($url)->toBe($expect); })->with([ ['baidu.com/list', ['a' => 'b'], false, 'baidu.com/list?a=b'], ['/api/v1/doc/categories/1?order=id', ['sort' => 'desc'], false, '/api/v1/doc/categories/1?order=id&sort=desc'], ['//google.com/search?c=d', ['a' => 'b'], false, '//google.com/search?c=d&a=b'], [ 'https://support.luxcreo.com/#/support?id=123', ['category' => 'abc'], true, 'https://support.luxcreo.com/#/support?id=123&category=abc', ], [ 'https://support.luxcreo.com/#/support', ['category' => 'abc'], true, 'https://support.luxcreo.com/#/support?category=abc', ], [ 'ssh://username:password@127.0.0.1/git/resp?id=1#/page?a=b', ['c' => 'd'], false, 'ssh://username:password@127.0.0.1/git/resp?id=1&c=d#/page?a=b', ], [ 'http://username:password@127.0.0.1/git/resp?id=1#/page?a=b', ['c' => 'd'], true, 'http://username:password@127.0.0.1/git/resp?id=1#/page?a=b&c=d', ], ])->group('pure', 'utils'); test('断言可以判断是否是数组中的元素', function ( $needle, array $haystack, bool $expect, bool $exceptions = false ) use ($utils) { try { expect($utils->inArray($needle, $haystack))->toBe($expect); } catch (Throwable $e) { if ($exceptions) { expect(true)->toBeTrue(); } } })->with([ [1, ['1', 2, 3], true, false], ['1', ['1', 2, 3], true, false], [[1, 2, 3], ['1', 2, 3], false, true], ])->group('pure', 'utils'); test('无极分类', function (string $source, string $expected) { $tree = []; foreach (Json::decode($source) as $item) { $path_array = explode(',', $item['namePath']); $parent_id = 0; $name_path = []; $id_path = ','; foreach ($path_array as $i => $name) { $name_path[] = $name; $level = $i + 1; $id = substr(md5($level . $name), 0, 10); $id_path .= $id . ','; $new_item = [ 'id' => $id, 'id_path' => $id_path, 'level' => $level, 'name' => $name, 'name_path' => join(',', $name_path + [$name]), 'parent_id' => $parent_id, ]; $tree[$id] = $new_item; $parent_id = $id; } } /** @var UtilsService $utils */ $utils = make(UtilsService::class); usort($tree, fn ($prevent, $current) => $current['level'] <=> $prevent['level']); $tree = array_column($tree, null, 'id'); $utils->unlimitedSubCategoriesQuicklyWithLevel(list: $tree); expect($tree)->toBe(Json::decode($expected)); })->with('categories');