popphp / pop-utils
Pop PHP 框架的 Pop Utilities 组件
Requires
- php: >=8.1.0
- ext-json: *
- popphp/popphp: ^4.2.12
Requires (Dev)
- phpunit/phpunit: ^10.0.0
README
概述
pop-utils
是 Pop PHP 框架的基本实用工具组件。它包含一些实用和辅助类,这些类在构建 Pop 应用程序时非常有用。
安装
使用 Composer 安装 pop-utils
。
composer require popphp/pop-utils
或者,在 composer.json 文件中要求它
"require": {
"popphp/pop-utils" : "^2.0.0"
}
数组对象
Pop\Utils\ArrayObject
类实现了多个接口,使其可以像数组一样使用,但内置了更多功能。使用它,您可以通过标准数组表示法($ary['item']
)或对象表示法($ary->item
)访问对象内的数组数据。
您可以迭代数组对象,并且它是可计数的。您还可以使用 toArray()
方法将其转换为原生数组。
use Pop\Utils\ArrayObject; $arrayObject = new ArrayObject(['foo' => 'bar']); echo $arrayObject->foo; echo $arrayObject['foo']; echo count($arrayObject); foreach ($arrayObject as $key => $value) { echo $key . ': ' . $value; } $array = $arrayObject->toArray();
此外,还有额外的序列化/反序列化方法,允许您将数组对象作为 JSON 字符串或 PHP 序列化字符串进行处理。
use Pop\Utils\ArrayObject; $arrayObject = ArrayObject::createFromJson('{"foo":"bar"}'); echo $arrayObject->jsonSerialize(JSON_PRETTY_PRINT);
use Pop\Utils\ArrayObject; $arrayObject = ArrayObject::createFromSerialized('a:1:{s:3:"foo";s:3:"bar";}'); echo $arrayObject->serialize();
集合
集合对象是一个类似于数组的对象,其中内置了大量的数组功能。这允许您在对象上调用任何数量的方法来对数组及其数据进行操作。它的 API 包括:
count(): int
first(): mixed
next(): mixed
current(): mixed
last(): mixed
key(): mixed
contains(mixed $key, bool $strict = false): bool
each(callable $callback): Collection
every(int $step, int $offset = 0): Collection
filter(?callable $callback = null, int $flag = 0): Collection
map(callable $callback): Collection
flip(): Collection
has(mixed $key): bool
isEmpty(): bool
keys(): Collection
column(string $column): Collection
values(): Collection
merge(mixed $data, $recursive = false): Collection
forPage(int $page, int $perPage): Collection
pop(): mixed
push(mixed $value): Collection
shift(): mixed
slice(int $offset, int $length = null): Collection
splice(int $offset, ?int $length = null, mixed $replacement = []): Collection
sort(?callable $callback = null, int $flags = SORT_REGULAR): Collection
sortByAsc(int $flags = SORT_REGULAR): Collection
sortByDesc(int $flags = SORT_REGULAR): Collection
toArray(): array
可调用对象
Pop\Utils\CallableObject
类帮助管理可调用对象及其参数。这包括函数、闭包、类及其方法(静态和实例。)这对于将需要在稍后时间由应用程序调用或触发的内容连接起来非常有用。
可以在可调用对象的整个生命周期中设置参数,从实例化时通过构造函数,通过设置/添加方法,到调用对象时。传递给可调用对象的参数本身也可以是可调用的,并在父可调用对象被调用时被调用。
函数可调用
use Pop\Utils\CallableObject; $callable = new CallableObject('trim', ' Hello World!'); echo $callable->call(); // Outputs 'Hello World!'
闭包可调用
use Pop\Utils\CallableObject; $callable = new CallableObject(function ($var) { echo strtoupper($var) . '!';}); $callable->addParameter('hello world'); echo $callable->call(); // Outputs 'HELLO WORLD!'
以下是通过在调用时传递参数的另一种调用方式
use Pop\Utils\CallableObject; $callable = new CallableObject(function ($var) { echo strtoupper($var) . '!';}); echo $callable->call('hello world'); // Outputs 'HELLO WORLD!'
静态方法可调用
use Pop\Utils\CallableObject; $callable = new CallableObject('MyClass::someMethod'); echo $callable->call(); // Executes the static 'someMethod()' from class 'MyClass'
实例方法可调用
use Pop\Utils\CallableObject; $callable = new CallableObject('MyClass->someMethod'); echo $callable->call(); // Executes the 'someMethod()' in an instance of 'MyClass'
构造函数 Callable
use Pop\Utils\CallableObject; class MyClass { protected $str = null; public function __construct($str) { $this->str = $str; } public function printString() { echo $this->str; } } // Creates an instance of 'MyClass' with the string 'Hello World' passed into the constructor $callable = new CallableObject('MyClass', 'Hello World'); $myInstance = $callable->call(); $myInstance->printString();
DateTime 对象
Pop\Utils\DateTime
类扩展了原生 DateTime
类并添加了一些辅助函数
- 将格式为 HH:MM:SS 的时间相加,得到总时间,格式仍为 HH:MM:SS。
- 将格式为 HH:MM:SS 的时间相加,得到平均时间,格式仍为 HH:MM:SS。
- 获取任何年份任何一周的日期。
use Pop\Utils\DateTime; $times = ['08:45:18', '15:13:58', '09:05:09']; $totalTime = Pop\Utils\DateTime::getTotal($times, '%H:%I:%S'); echo $totalTime . PHP_EOL; // 33:04:25 $averageTime = Pop\Utils\DateTime::getAverage($times, '%H:%I:%S'); echo $averageTime . PHP_EOL; // 11:01:28 $weekDates = DateTime::getWeekDates(40, 2023, 'Y-m-d'); // 40th week of the year 2023 print_r($weekDates); /** Array ( [0] => 2023-10-01 [1] => 2023-10-02 [2] => 2023-10-03 [3] => 2023-10-04 [4] => 2023-10-05 [5] => 2023-10-06 [6] => 2023-10-07 ) */
文件助手
Pop\Utils\File
类可以快速解析并返回有关文件的信息,包括常见文件类型的 mime 类型
use Pop\Utils\File $file = new File(__DIR__ . '/tmp/test.txt'); echo $file->getBasename()); // 'test.txt' echo $file->getFilename()); // 'test' echo $file->getExtension()); // 'txt' echo $file->getMimeType()); // 'text/plain' echo $file->getPath()); // __DIR__ . '/tmp echo $file->getSize()); // 13
您可以通过以下方式快速获取文件的 mime 类型
use Pop\Utils\File echo File::getFileMimeType(__DIR__ . '/tmp/image.jpg'); // 'image/jpeg'
字符串助手
Pop\Utils\Str
类提供了一些静态方法来协助操作和生成字符串。
缩略名
use Pop\Utils\Str; echo Str::createSlug('Hello World | Home Page'); // hello-world-home-page
链接
use Pop\Utils\Str; echo Str::createLinks('Test Email test@test.com and Test Website http://www.test.com/');
Test Email <a href="mailto:test@test.com">test@test.com</a> and
Test Website <href="http://www.test.com/">http://www.test.com/</a>
随机字符串
use Pop\Utils\Str; echo Str::createRandom(10); // 5.u9MHw{PC echo Str::createRandomAlpha(10, Str::LOWERCASE); // wvjvvsmnjw echo Str::createRandomAlphaNum(10, Str::UPPERCASE); // 6S73HQ629R echo Str::createRandomAlphaNum(10, Str::MIXEDCASE); // Yfd35M3T92
转换大小写
转换大小写功能支持以下大小写和字符串格式类型
- 标题大小写
- 驼峰式大小写
- 分隔符为短横线的 kebab-case
- 分隔符为下划线的 snake_case
- 命名空间
- 文件夹/路径
- URL/路径(URI)
可以通过多种动态静态方法调用使用
use Pop\Utils\Str; echo Str::titleCaseToKebabCase('TitleCase'); // title-case echo Str::titleCaseToSnakeCase('TitleCase'); // title_case echo Str::camelCaseToDash('camelCase'); // camel-case echo Str::camelCaseToUnderscore('camelCase'); // camel_case echo Str::kebabCaseToTitleCase('kebab-string'); // KebabString echo Str::snakeCaseToCamelCase('snake_case_string'); // SnakeCaseString echo Str::snakeCaseToNamespace('snake_case_string'); // Snake\Case\String echo Str::kebabCaseToPath('kebab-string'); // kebab/string (kebab\string on Windows) echo Str::camelCaseToUrl('camelCase'); // camel/case
数组助手
Pop\Utils\Arr
类提供了一些静态方法来协助操作数组
Arr::isArray(mixed $value): bool
Arr::isNumeric(array $array): bool
Arr::isAssoc(array $array): bool
Arr::exists(array|ArrayAccess $array, string|int $key): bool
Arr::key(array|AbstractArray $array, string|int $value, bool $strict = false): mixed
Arr::collapse(array|AbstractArray $array): array
Arr::flatten(array|AbstractArray $array, int|float $depth = INF): array
Arr::divide(array|AbstractArray $array): array
Arr::slice(array|AbstractArray $array, int $limit, int $offset = 0): array
Arr::split(string $string, string $separator, int $limit = PHP_INT_MAX): array
Arr::join(array|AbstractArray $array, string $glue, string $finalGlue = ''): string
Arr::prepend(array|AbstractArray $array, mixed $value, mixed $key = null): array
Arr::pull(array &$array, mixed $key): mixed
Arr::sort(array|AbstractArray $array, int $flags = SORT_REGULAR, bool $assoc = true, bool $descending = false): array
Arr::sortDesc(array|AbstractArray $array, int $flags = SORT_REGULAR, bool $assoc = true): array
Arr::ksort(array|AbstractArray $array, int $flags = SORT_REGULAR, bool $descending = false): array
Arr::ksortDesc(array|AbstractArray $array, int $flags = SORT_REGULAR): array
Arr::usort(array|AbstractArray $array, mixed $callback, bool $assoc = true): array
Arr::uksort(array|AbstractArray $array, mixed $callback): array
Arr::map(array|AbstractArray $array, mixed $callback): array
Arr::trim(array|AbstractArray $array): array
Arr::filter(array|AbstractArray $array, mixed $callback = null, int $mode = ARRAY_FILTER_USE_BOTH): array
Arr::make(mixed $value): array
辅助函数
有一组“辅助”函数可以帮助快速操作数据,如字符串、数组和日期。这些函数可以通过在仓库中包含 functions.php
文件或使用 Pop\Utils\Helper
类的函数手动加载。
use Pop\Utils\Helper; if (!Helper::isLoaded()) { Helper::loadFunctions(); }
上述代码在 Pop\Application
对象的引导方法中自动执行,除非通过配置设置 'helper_functions' => false
禁用。
包含的函数有
app_date(string $format, ?int $timestamp = null, string $env = 'APP_TIMEZONE', mixed $envDefault = null): string|null
str_slug(string $string, string $separator = '-'): string
str_random(int $length, int $case = Str::MIXEDCASE): string
str_random_alpha(int $length, int $case = Str::MIXEDCASE): string
str_random_num(int $length): string
str_random_alphanum(int $length, int $case = Str::MIXEDCASE): string
str_from_camel(string $string, ?string $separator = '-', bool $preserveCase = false): string
str_to_camel(string $string): string
str_title_case(string $string): string
str_snake_case(string $string, bool $preserveCase = false): string
str_kebab_case(string $string, bool $preserveCase = false): string
array_collapse(array|AbstractArray $array): array
array_flatten(array|AbstractArray $array, int|float $depth = INF): array
array_divide(array|抽象数组 $array): 数组
array_join(array|抽象数组 $array, string $glue, string $finalGlue = ''): 字符串
array_prepend(array|抽象数组 $array, mixed $value, mixed $key = null): 数组
array_pull(array &$array, mixed $key): 混合类型
array_sort(array|抽象数组 $array, int $flags = SORT_REGULAR, bool $assoc = true, bool $descending = false): 数组
array_sort_desc(array|抽象数组 $array, int $flags = SORT_REGULAR, bool $assoc = true): 数组
array_ksort(array|抽象数组 $array, int $flags = SORT_REGULAR, bool $descending = false): 数组
array_ksort_desc(array|抽象数组 $array, int $flags = SORT_REGULAR): 数组
array_usort(array|抽象数组 $array, mixed $callback, bool $assoc = true): 数组
array_uksort(array|抽象数组 $array, mixed $callback): 数组
array_make(mixed $value): 数组