每天使用的有用的PHP函数、迷你类和代码片段集合

作者:Sec-Labs | 发布时间:

项目地址

https://github.com/m0n0ph1/Utils

项目简介

JBZoo/Utils是一个PHP功能、迷你类和代码片段的集合,用于日常开发者的例行生活。

技术点

  • PHP函数和迷你类
  • 数组操作函数,比如从数组中删除重复项,通过键对数组进行排序,将数组转换为注释样式等。
  • 工具函数,如检查值是否存在于数组中,将非标量值转换为字符串等。
  • 该项目使用Composer管理包依赖关系。

项目用途

JBZoo/Utils可以帮助PHP开发人员更轻松地处理日常编程任务。它提供了许多实用的工具函数,例如将非标量值转换为字符串,检查值是否存在于数组中,以及将数组转换为注释样式。此外,它还提供了许多方便的数组操作函数,例如从数组中删除重复项,通过键对数组进行排序,将数组转换为注释样式等。这些函数和类可以大大简化PHP开发人员的日常编程工作。

JBZoo / Utils

收集了 PHP 函数、迷你类和日常开发人员常用的代码片段。

安装

composer require jbzoo/utils

使用

智能函数

use function JBZoo\Utils\alias;
use function JBZoo\Utils\alpha;
use function JBZoo\Utils\alphanum;
use function JBZoo\Utils\bool;
use function JBZoo\Utils\digits;
use function JBZoo\Utils\float;
use function JBZoo\Utils\int;

int(' 10.0 ') === 10;
float(' 10.0 ') === 10.0;

bool(' yes ') === true;
bool(' no ') === false;
bool('1') === true;
bool('0') === false;

alias('Qwer ty') === 'qwer-ty';
digits('Qwer 1 ty2') === '12';
alpha('Qwer 1 ty2') === 'Qwerty';
alphanum(' #$% Qwer 1 ty2') === 'Qwer1ty2';

JBZoo\Utils\Arr

Arr::addEachKey(array $array, string $prefix): array; // 为每个键添加前缀。

Arr::clean(array $haystack): array; // 根据自定义规则清除数组。

Arr::cleanBeforeJson(array $array): array; // 在序列化为 JSON 之前清除数组。

Arr::first(array $array): ?mixed; // 返回数组中的第一个元素。

Arr::firstKey(array $array): ?string|int|null; // 返回数组中的第一个键。

// 将多维数组展平为一维数组。
//                            从浅嵌套数组中重写键
Arr::flat(array $array, bool $preserveKeys = true): array;

Arr::getField(array $arrayList, string $fieldName = 'id'): array; // 从数组的数组(对象数组)中获取一个字段。

Arr::groupByKey(array $arrayList, string $key = 'id'): array; // 按键分组数组并返回分组的值列表。

Arr::implode(string $glue, array $array): string; // 对嵌套数组进行数组分解。

Arr::in(?mixed $value, array $array, bool $returnKey = false): ?string|int|bool|null; // 检查值是否存在于数组中。

Arr::isAssoc(array $array): bool; // 检查数组是否为关联类型。

Arr::key(?mixed $key, array $array, bool $returnValue = false): ?mixed; // 检查键是否存在。

Arr::last(array $array): ?mixed; // 返回数组中的最后一个元素。

Arr::lastKey(array $array): ?string|int|null; // 返回数组中的最后一个键。

Arr::map(Closure $function, array $array): array; // 递归数组映射。

// 返回一个包含对 arr1 中的每个元素应用回调函数后的所有元素的数组。
//                             (对象、资源等)
Arr::mapDeep(array $array, callable $callback, bool $onNoScalar = false): array;

Arr::removeByValue(array $array, ?string|int|float|bool|null $value): array; // 按值从数组中删除所有项目。

// 在数组的数组、对象和标量值中搜索给定值。您可以选择指定嵌套数组和对象中要搜索的字段。
Arr::search(array $array, ?string|int|float|bool|null $search, ??string $field = null): string|bool;

Arr::sortByArray(array $array, array $orderArray): array; // 基于另一个数组的键对数组进行排序。

Arr::toComment(array $data): string; // 将关联数组转换为注释样式。

Arr::unique(array $array, bool $keepKeys = false): array; // 从数组中删除重复项。

Arr::unshiftAssoc(array $array, string|int $key, ?mixed $value): array; // 在关联数组的开头添加单元格。

// 将其参数包装在数组中,除非它已经是数组。
//   Arr.wrap(null)      # => []
//   Arr.wrap([1, 2, 3]) # => [1, 2, 3]
//   Arr.wrap(0)         # => [0]
Arr::wrap(?mixed $object): array;

```### JBZoo\Utils\Cli

```php
Cli::build(string $command, array $args = []): string; // 为命令行选项构建参数。

Cli::check(): bool; // 是否处于命令行模式。

Cli::err(string $message, bool $addEol = true): bool; // 输出错误信息到标准错误流。

Cli::exec(string $command, array $args = [], ??string $cwd = null, bool $verbose = false): string; // 执行命令行命令。

Cli::getNumberOfColumns(): int; // 返回终端的列数。

// 如果标准输出支持颜色,则返回true。
// 此代码已从 \Symfony\Component\Console\Output\OutputStream 中复制并适应。
Cli::hasColorSupport(): bool;

Cli::isInteractive($fileDescriptor = 1): bool; // 返回文件描述符是否为交互式终端。

Cli::out(string $message, bool $addEol = true): bool; // 输出信息到标准输出流。

JBZoo\Utils\Csv

Csv::parse(string $csvFile, string $delimiter = ';', string $enclosure = '"', bool $hasHeader = true): array; // CSV文件的简单解析器。

JBZoo\Utils\Dates

Dates::factory(?mixed $time = null, ?DateTimeZone|string|null $timeZone = null): DateTime; // 根据混合输入生成 PHP \DateTime 对象。

Dates::formatTime(float $seconds, int $minValuableSeconds = 2): string; // 将秒转换为可读的时间格式 "H:i:s"。

Dates::human(string|int $date, string $format = 'd M Y H:i'): string; // 将日期字符串或Unix时间戳转换为可读的日期格式。

Dates::is(??string $date): bool; // 检查字符串是否为日期。

Dates::isThisMonth(string|int $time): bool; // 如果传递的日期在本月内,则返回true。

Dates::isThisWeek(string|int $time): bool; // 如果传递的日期在本周内,则返回true。

Dates::isThisYear(string|int $time): bool; // 如果传递的日期在本年内,则返回true。

Dates::isToday(string|int $time): bool; // 如果传递的日期是今天,则返回true。

Dates::isTomorrow(string|int $time): bool; // 如果传递的日期是明天,则返回true。

Dates::isYesterday(string|int $time): bool; // 如果传递的日期是昨天,则返回true。

Dates::sql(?string|int|null $time = null): string; // 将时间转换为 SQL 格式。

Dates::timezone(?DateTimeZone|string|null $timezone = null): DateTimeZone; // 根据当前时区返回 DateTimeZone 对象。

Dates::toStamp(?DateTime|string|int|null $time = null, bool $currentIsDefault = true): int; // 转换为 Unix 时间戳。

JBZoo\Utils\Email

Email::check(?mixed $emails): array; // 检查电子邮件地址是否有效。可以发送一个或多个电子邮件地址。

// 检查电子邮件域名的 DNS MX 记录。
// 注意,(临时的) DNS 错误将产生与未找到记录相同的结果。
// 忽略代码覆盖率,因为此方法需要不能可靠的 DNS 请求。
Email::checkDns(string $email): bool;

Email::getDomain(?mixed $emails): array; // 从电子邮件地址获取域名。不合法的电子邮件地址将被跳过。

Email::getDomainSorted(array $emails): array; // 按字母顺序获取电子邮件地址的域名。

Email::getGravatarBuiltInImages(): array; // 返回 Gravatar 支持的占位符。

// 生成 Gravatar URL。
// 图像的大小:
// * 默认大小为 32px,可以在 1px 到 2048px 之间任何值。
// * 如果请求的值超出允许范围,则应用最大值。
// * 如果请求的值小于最小值,则应用默认值。
// 默认图片:
// * 它可以是图像的 URL。
// * 或者是 Gravatar 支持的内置选项之一。请参阅 Email::getGravatarBuiltInImages()。
// * 如果没有定义,则使用内置默认值。请参阅 Email::getGravatarBuiltInDefaultImage()。
Email::getGravatarUrl(string $email, int $size = 32, string $defaultImage = 'identicon'): ??string;

Email::isValid(??string $email): bool; // 如果字符串具有有效的电子邮件格式,则返回true。

Email::random(int $userNameLength = 10): string; // 创建随机电子邮件地址。

JBZoo\Utils\Env

Env::bool(string $envVarName, bool $default = false): bool; // 将环境变量的值转换为严格的布尔值。

Env::convert(??string $value, int $options = 16): ?string|int|float|bool|null; // 转换类型为 "true"、"false"、"null" 或 "123" 的值。

Env::float(string $envVarName, float $default = 0): float; // 将环境变量的值转换为严格的浮点数值。

Env::get(string $envVarName, ?string|int|float|bool|null $default = null, int $options = 16): ?string|int|float|bool|null; // 返回环境变量。

Env::int(string $envVarName, int $default = 0): int; // 将环境变量的值转换为严格的整数值。

Env::isExists(string $envVarName): bool; // 如果环境变量存在,则返回true。

Env::string(string $envVarName, string $default = ''): string; // 将环境变量的值转换为干净的字符串。

```### JBZoo\Utils\FS

```php
FS::base(??string $path): string; // 从 FS 路径名返回带有扩展名的文件名。

FS::clean(??string $path, string $dirSep = '/'): string; // 用于从路径名中去除尾部的/或\的函数。

FS::dirName(??string $path): string; // 从 FS 路径名返回目录名称。

FS::dirSize(string $dir): int; // 返回给定目录的大小(以字节为单位)。

FS::executable(string $filename, bool $executable = true): bool; // 设置文件的可执行位为允许运行 PHP 的用户读取它的最小值。

FS::ext(??string $path): string; // 从 FS 路径名返回文件扩展名。

FS::filename(??string $path): string; // 从 FS 路径名返回不带扩展名的文件名。

FS::firstLine(string $filepath): ??string; // 获取文件的第一行的最快方法。

FS::format(int $bytes, int $decimals = 2): string; // 为计算机大小(字节)进行美观格式化。

FS::getRelative(string $path, ??string $rootPath = null, string $forceDS = '/'): string; // 查找文件的相对路径(删除根部分)。

FS::isDir(??string $path): bool; // 检查当前路径是否为目录。

FS::isFile(string $path): bool; // 检查当前路径是否为常规文件。

FS::isReal(??string $path): bool; // 如果文件或目录存在,则返回干净的 realpath。

FS::ls(string $dir): array; // 返回目录内的所有路径。

FS::openFile(string $filepath): ??string; // 以二进制安全的方式打开文件。

FS::perms(string $file, ??int $perms = null): string; // 以漂亮的字符串形式返回文件权限,例如 -rw-r--r-- 或 false(如果找不到该文件)。

FS::readable(string $filename, bool $readable = true): bool; // 将文件的可读位设置为允许运行 PHP 的用户读取它的最小值。

FS::real(??string $path): ??string; // 返回 realpath(PHP \realpath() 的智能模拟)。

// 递归删除目录(及其内容)。
// 贡献者:Askar(ARACOOL)<https://github.com/ARACOOOL>。
FS::rmDir(string $dir, bool $traverseSymlinks = true): bool;

FS::stripExt(string $path): string; // 如果存在,则去除扩展名。

FS::writable(string $filename, bool $writable = true): bool; // 将文件的可写位设置为允许运行 PHP 的用户写入它的最小值。

JBZoo\Utils\Filter

Filter::_(?mixed $value, Closure|string $filters = 'raw'): ?mixed; // 对变量应用自定义过滤器。

Filter::alias(string $string): string; // 获取外部依赖项的安全字符串。

Filter::alpha(??string $value): string; // 仅返回字母字符。

Filter::alphanum(??string $value): string; // 仅返回字母和数字字符。

Filter::arr(?mixed $value, ?Closure|string|null $filter = null): array; // 清理数组。没有空值。

Filter::base64(string $value): string; // 仅返回用于base64的字符。

Filter::bool(?mixed $variable): bool; // 将许多英文单词转换为布尔值。

Filter::className(string $input): string; // 将单词转换为 PHP 类名。

Filter::clean(string $string): string; // "Str::clean($string, true, true)"的别名。

Filter::cmd(string $value): string; // 清理系统命令。

Filter::data(JBZoo\Data\Data|array $data): JBZoo\Data\Data; // 从数组返回 JSON 对象。

Filter::digits(??string $value): string; // 仅返回数字字符。

Filter::esc(string $string): string; // "Str::esc($string)"的别名。

Filter::float(?mixed $value, int $round = 10): float; // 智能将字符串转换为浮点数。

Filter::html(string $string): string; // "Str::htmlEnt($string)"的别名。

Filter::int(?string|int|float|bool|null $value): int; // 智能将任何字符串转换为整数。

Filter::low(string $string): string; // 字符串转小写并修剪。

Filter::parseLines(array|string $input): array; // 将行解析为关联列表。

Filter::path(string $value): string; // 仅返回base64url的字符。

Filter::raw(?mixed $variable): ?mixed; // 内部库的RAW占位符API。

Filter::strip(string $string): string; // 获取没有HTML标记和修剪的安全字符串。

Filter::stripQuotes(string $value): string; // 智能删除引号,双引号和单引号。

Filter::stripSpace(string $string): string; // "Str::stripSpace($string)"的别名。

Filter::trim(string $value): string; // build-in函数\trim()的别名。

Filter::trimExtend(string $value): string; // 扩展的trim函数用于删除所有空格,制表符,换行符和非常特殊的字符。

Filter::ucFirst(string $input): string; // 首字母转为大写,其他字母转为小写。

Filter::up(string $string): string; // 字符串转大写并修剪。

Filter::xml(string $string): string; // "Xml::escape($string)"的别名。

```### JBZoo\Utils\Http

```php
// 发送强制浏览器下载文件对话框的头信息
// 兼容跨浏览器。仅在头信息尚未发送时触发。
Http::download(string $filename): bool;

Http::getHeaders(): array; // 获取所有 HTTP 头信息。

// 设置头信息以防止不同浏览器的缓存。
// 不同浏览器支持不同的 nocache 头信息,因此必须发送多个头信息,
// 以便它们都能了解不应进行缓存。
Http::nocache(): bool;

Http::utf8(string $contentType = 'text/html'): bool; // 当头信息尚未发送时,传输 UTF-8 内容头信息。

JBZoo\Utils\IP

IP::getNetMask(string $ipAddress): ??string; // 返回网络掩码。例如,'192.0.0.0' => '255.255.255.0'。

// 返回客户端的 IP 地址。
// 仅在服务器位于设置这些值的代理后面时使用
IP::getRemote(bool $trustProxy = false): string;

IP::v4InRange(string $ipAddress, string $range): bool; // 检查给定的 IP 是否在网络中。

JBZoo\Utils\Image

Image::addAlpha(GdImage $image, bool $isBlend = true): void; // 为图像资源添加 Alpha 通道。

Image::alpha(float $color): int; // 返回有效的 Alpha 通道值。

Image::blur(float $blur): int; // 返回模糊图像的有效值(1-10)。

Image::brightness(float $brightness): int; // 返回使图像明亮的有效值(-255..255)。

Image::checkGD(bool $throwException = true): bool; // 检查 GD 库是否在服务器上启用。

Image::color(float $color): int; // 返回改变图像颜色段的有效值(0..255)。

Image::colorize(float $colorize): int; // 返回改变图像颜色段的有效值(-255..255)。

Image::contrast(float $contrast): int; // 返回改变图像对比度的有效值(-100..100)。

Image::direction(string $direction): string; // 返回图像方向的有效值:'x'、'y'、'xy'、'yx'。

Image::getInnerCoords(string $position, array $canvas, array $box, array $offset = []): ??array; // 确定位置。返回 X 和 Y 坐标的数组。

Image::imageCopyMergeAlpha(GdImage $dstImg, GdImage $srcImg, array $dist, array $src, array $srcSizes, int $opacity): void; // 与 PHP 的 imagecopymerge() 函数相同,但在 24 位 PNG 中保留 Alpha 透明度。

Image::isGif(??string $format = null): bool; // 检查图像是否具有 GIF 格式。

Image::isJpeg(??string $format = null): bool; // 检查图像是否具有 JPEG/JPG 格式。

Image::isPng(??string $format = null): bool; // 检查图像是否具有 PNG 格式。

Image::isSupportedFormat(string $format): bool; // 检查 lib 是否支持该格式。

Image::isWebp(??string $format = null): bool; // 检查图像是否具有 WEBP 格式。

// 将十六进制颜色值转换为其 RGB 等效值。
// 其中,红、绿、蓝是 0-255 的整数,alpha 是 0-127 的整数
Image::normalizeColor(array|string $origColor): array;

Image::opacity(float $opacity): int; // 检查不透明度值。

Image::opacity2Alpha(float $opacity): int; // 将不透明度值转换为 Alpha。

Image::percent(float $percent): int; // 返回百分比的有效值(0-100)。

Image::position(string $position): string; // 检查位置名称。

Image::quality(float $percent): int; // 返回图像质量的有效值(0..100)。

Image::rotate(float $color): int; // 返回图像旋转的有效值(-360..360)。

Image::smooth(float $smooth): int; // 返回改变图像平滑度的有效值(1..10)。

Image::strToBin(string $imageString): ??string; // 将字符串转换为二进制数据。

JBZoo\Utils\PhpDocs

// 简单解析 PHPDocs。
// 示例或返回值
//  [
//      'description' => 'Simple parse of PHPDocs. Example or return value',
//      'params'      => [
//          'param'  => ['string $phpDoc'],
//          'return' => ['array']
//      ]
//  ]。
PhpDocs::parse(string $phpDoc): array;

JBZoo\Utils\Ser

// 反序列化部分损坏的数组。有时会发生这种情况。
// 特别是解决了“unserialize(): Error at offset xxx of yyy bytes”错误。
// 注意:此错误可能经常发生在字符集不匹配和高于 ASCII 字符的情况下。
// 由 PHP Experts, Inc. 的 Theodore R. Smith 贡献 <http://www.phpexperts.pro/>。
Ser::fix(string $brokenSerializedData): string;

// 检查值以查找它是否被序列化。
// 如果 $data 不是字符串,则返回值将始终为 false。序列化数据始终是字符串。
Ser::is(?mixed $data): bool;

Ser::maybe(?mixed $data): ?mixed; // 序列化数据(如果需要)。

Ser::maybeUn(string $data): ?mixed; // 仅在值被序列化时,反序列化该值。

```### JBZoo\Utils\Slug

```php
// 将字符转换为它们的ASCII等效字符。
// URLify.php项目的一部分<https://github.com/jbroadway/urlify/>。
Slug::downCode(string $text, string $language = ''): string;

// 将任何重音字符转换为它们对应的普通字符,并将任何其他非字母数字字符转换为破折号,然后将任何两个或多个破折号的序列转换为单个破折号。此函数生成安全用于URL的标记,如果将true作为第二个参数传递,则会创建用于CSS类或ID的字符串。
Slug::filter(??string $string, string $separator = '-', bool $cssMode = false): string;

// 将所有重音字符转换为ASCII字符。
// 如果没有重音字符,则返回给定的字符串。
Slug::removeAccents(string $string, string $language = ''): string;

// 检查字符串是否已编码为UTF8。
// 注意:此函数检查5字节序列,UTF8具有最大长度为4的字节序列。
// 由Tony Ferrara编写<http://blog.ircmaxwell.com>。
Slug::seemsUTF8(string $string): bool;

JBZoo\Utils\Stats

Stats::histogram(array $values, int $steps = 10, ??float $lowerBound = null, ??float $upperBound = null): array; // 生成直方图。请注意,这不是一个很好的函数,不应依赖它进行严肃的使用。

Stats::linSpace(float $min, float $max, int $num = 50, bool $endpoint = true): array; // 返回一个由$num个数字从$min到$max填充的数组。

Stats::mean(??array $values): float; // 返回给定值的平均值。

Stats::renderAverage(array $values, int $rounding = 3): string; // 渲染人类可读的平均值和系统误差字符串。

Stats::stdDev(array $values, bool $sample = false): float; // 返回给定人口的标准偏差。

Stats::variance(array $values, bool $sample = false): float; // 返回给定人口的方差。

JBZoo\Utils\Str

// Make string safe
// - Remove UTF-8 chars
// - Remove all tags
// - Trim
// - Add Slashes (opt)
// - To lower (opt).
Str::clean(string $string, bool $toLower = false, bool $addSlashes = false, bool $removeAccents = true): string;

Str::esc(string $string): string; // Escape UTF-8 strings.

// Escape string before save it as xml content.
// The function is moved. Please, use \JBZoo\Utils\Xml::escape($string). It'll be deprecated soon.
Str::escXml(string $string): string;

Str::getClassName(?object|string|null $object, bool $toLower = false): ??string; // Get class name without namespace.

Str::htmlEnt(string $string, bool $encodedEntities = false): string; // Convert >, <, ', " and & to html entities, but preserves entities that are already encoded.

Str::iPos(string $haystack, string $needle, int $offset = 0): ??int; // Finds position of first occurrence of a string within another, case-insensitive.

Str::iStr(string $haystack, string $needle, bool $beforeNeedle = false): string; // Finds first occurrence of a string within another, case-insensitive.

// Increments a trailing number in a string.
// Used to easily create distinct labels when copying objects. The method has the following styles:
//  - default: "Label" becomes "Label (2)"
//  - dash:    "Label" becomes "Label-2".
Str::inc(string $string, string $style = 'default', int $next = 0): string;

Str::isEmpty(?string|bool|null $value, bool $strict = false): bool; // Extend version of checking if potetielly empty string is empty.

Str::isEnd(string $haystack, string $needle, bool $caseSensitive = false): bool; // Checks if the $haystack ends with the text in the $needle. Case-sensitive.

Str::isMBString(): bool; // Check is mbstring loaded.

Str::isStart(string $haystack, string $needle, bool $caseSensitive = false): bool; // Checks if the $haystack starts with the text in the $needle.

Str::len(string $string): int; // Get real string length if it's possible.

Str::like(string $pattern, string $haystack, bool $caseSensitive = true): bool; // Check if a given string matches a given pattern.

Str::limitChars(string $string, int $limit = 100, string $append = '...'): string; // Truncate the string to given length of characters.

Str::limitWords(string $string, int $limit = 100, string $append = '...'): string; // Truncate the string to given length of words.

Str::listToDescription(array $data, bool $alignByKeys = false): ??string; // Convert array of strings to list as pretty print description.

Str::low(string $string): string; // Make a string lowercase.

Str::parseLines(string $text, bool $toAssoc = true): array; // Parse text by lines.

Str::pos(string $haystack, string $needle, int $offset = 0): ??int; // Find position of first occurrence of string in a string.

Str::rChr(string $haystack, string $needle, bool $part = false): string; // Finds the last occurrence of a character in a string within another.

Str::rPos(string $haystack, string $needle, int $offset = 0): ??int; // Find position of last occurrence of a string in a string.

Str::random(int $length = 10, bool $isReadable = true): string; // Generate readable random string.

Str::slug(string $text = '', bool $isCache = false): string; // Converts any accent characters to their equivalent normal characters.

Str::splitCamelCase(string $input, string $separator = '_', bool $toLower = true): string; // Convert camel case to human-readable format.

// Splits a string of multiple queries into an array of individual queries.
// Single line or line end comments and multi line comments are stripped off.
Str::splitSql(string $sql): array;

Str::strStr(string $haystack, string $needle, bool $beforeNeedle = false): string; // Finds first occurrence of a string within another.

Str::stripSpace(string $string): string; // Strip all whitespaces from the given string.

Str::sub(string $string, int $start, int $length = 0): string; // Get part of string. Safe alias for substr().

Str::subCount(string $haystack, string $needle): int; // Count the number of substring occurrences.

Str::testName2Human(string $input): string; // Convert test name to human-readable string.

Str::trim(string $value, bool $extendMode = false): string; // Trim whitespaces and other special chars.

Str::truncateSafe(string $string, int $length, string $append = '...'): string; // Truncate a string to a specified length without cutting a word off.

Str::unique(string $prefix = 'unique'): string; // Get unique string with prefix.

Str::up(string $string): string; // Make a string uppercase.

// Generates a universally unique identifier (UUID v4) according to RFC 4122
// Version 4 UUIDs are pseudo-random!
// Returns Version 4 UUID format: xxxxxxxx-xxxx-4xxx-Yxxx-xxxxxxxxxxxx where x is
// any random hex digit and Y is a random choice from 8, 9, a, or b.
Str::uuid(): string;

Str::zeroPad(string $number, int $length): string; // Pads a given string with zeroes on the left.

JBZoo\Utils\Sys

// 当支持Xdebug或
//使用的运行时是PHPDBG(PHP> = 7.0)时返回true。
Sys::canCollectCodeCoverage(): bool;

// 返回当前运行时的二进制文件路径。
// 当运行时为HHVM时,将“--php”附加到路径。
Sys::getBinary(): string;

Sys::getDocRoot(): ??string; // 返回当前文档根。

Sys::getHome(): ??string; // 返回当前用户的主目录。

Sys::getMemory(bool $isPeak = true): string; // 获取使用内存,以人类可读形式。

Sys::getName(): string; // 返回PHP类型。

Sys::getNameWithVersion(): string; // 返回当前PHP的类型和版本。

Sys::getUserName(): ??string; // 返回运行脚本的当前Linux用户。

Sys::getVendorUrl(): string; // 返回PHP官方网站的URL。它取决于PHP供应商。

Sys::getVersion(): ??string; // 返回当前PHP版本。

// 当使用的运行时是具有PHPDBG SAPI的PHP并且phpdbg_*_oplog()函数可用时(PHP> = 7.0)返回true。
Sys::hasPHPDBGCodeCoverage(): bool;

Sys::hasXdebug(): bool; // 当使用的运行时是PHP且已加载Xdebug时返回true。

Sys::iniGet(string $varName): string; // ini_get函数的别名。

Sys::iniSet(string $phpIniKey, string $newValue): bool; // ini_set函数的别名。

Sys::isFunc(Closure|string $funcName): bool; // 检查函数是否存在并可调用。

Sys::isHHVM(): bool; // 当使用的运行时是HHVM时返回true。

Sys::isPHP(string $version, string $current = '8.1.16'): bool; // 比较PHP版本。

Sys::isPHPDBG(): bool; // 当使用的运行时是具有PHPDBG SAPI的PHP时返回true。

Sys::isRealPHP(): bool; // 当使用的运行时是没有PHPDBG SAPI的PHP时返回true。

Sys::isRoot(): bool; // 检查当前用户是否为ROOT。

Sys::isWin(): bool; // 检查当前OS是否为Windows。

Sys::setMemory(string $newLimit = '256M'): void; // 设置新的内存限制。

Sys::setTime(int $newLimit = 0): void; // 设置PHP执行时间限制(在安全模式下无效)。

JBZoo\Utils\Timer

Timer::format(float $milliSeconds): string; // 将经过的时间格式化为字符串。

Timer::formatMS(float $seconds): string; // 将经过的时间格式化为字符串。

Timer::getRequestTime(): float; // 以微秒为单位获取请求时间。

Timer::timeSinceStart(): float; // 格式化自请求开始以来经过的时间为字符串。

```### JBZoo\Utils\Url

```php
Url::addArg(array $newParams, ??string $uri = null): string; // 将查询参数添加或删除到URL中。

Url::build(array $queryParams): string; // 根据数组构建HTTP查询。

// 根据标志参数将第二个URL的部分合并到第一个URL中
Url::buildAll(array|string $sourceUrl, array|string $destParts = [], int $flags = 1, array $newUrl = []): string;

Url::create(array $parts = []): string; // 根据数组参数创建URL。

Url::current(bool $addAuth = false): ??string; // 返回当前URL。

Url::delArg(array|string $keys, ??string $uri = null): string; // 从查询字符串中删除一个或多个项目。

Url::getAuth(): ??string; // 获取当前的身份验证信息。

Url::isAbsolute(string $path): bool; // 检查URL是否不是相对的。

Url::isHttps(bool $trustProxyHeaders = false): bool; // 检查页面是否通过SSL进行服务器。

// 将字符串中的所有链接转换为HTML链接。
Url::parseLink(string $text): string;

Url::path(): ??string; // 返回当前路径。

Url::pathToRel(string $path): string; // 将文件路径转换为相对URL。

Url::pathToUrl(string $path): string; // 将文件路径转换为绝对URL。

Url::root(bool $addAuth = false): ??string; // 返回当前根URL。

JBZoo\Utils\Vars

Vars::isEven(int $number): bool; // 当前值是偶数吗?

Vars::isIn(float $number, float $min, float $max): bool; // 如果数字在最小值和最大值之间,则返回true。

Vars::isNegative(float $number): bool; // 当前值是否为负数;小于零。

Vars::isOdd(int $number): bool; // 当前值是否为奇数?

Vars::isPositive(float $number, bool $zero = true): bool; // 当前值是否为正数;大于或等于零。

Vars::limit(float $number, float $min, float $max): int; // 限制数字在两个范围之间。

Vars::max(float $number, float $max): int; // 如果超过阈值,则将数字减少到最大值。

Vars::min(float $number, float $min): int; // 如果低于阈值,则将数字增加到最小值。

Vars::out(float $number, float $min, float $max): bool; // 如果数字在最小值和最大值之外,则返回true。

Vars::range(float $value, float $min, float $max): int; // 确保$值始终在$min和$max范围内。

Vars::relativePercent(float $normal, float $current): string; // 获取相对百分比。

JBZoo\Utils\Xml

// 将数组转换为PHP DOMDocument对象。
// 输入数组格式
// $source = [
//     '_node'     => '#document',
//     '_text'     => null,
//     '_cdata'    => null,
//     '_attrs'    => [],
//     '_children' => [
//         [
//             '_node'     => 'parent',
//             '_text'     => "Content of parent tag",
//             '_cdata'    => null,
//             '_attrs'    => ['parent-attribute' => 'value'],
//             '_children' => [
//                 [
//                     '_node'     => 'child',
//                     '_text'     => "Content of child tag",
//                     '_cdata'    => null,
//                     '_attrs'    => [],
//                     '_children' => [],
//                 ],
//             ]
//         ]
//     ]
// ]。
// 输出格式
//     <?xml version="1.0" encoding="UTF-8"?>
//     <parent parent-attribute="value">Content of parent tag<child>Content of child tag</child></parent>
Xml::array2Dom(array $xmlAsArray, ??DOMElement $domElement = null, ??DOMDocument $document = null): DOMDocument;

Xml::createFromString(??string $source = null, bool $preserveWhiteSpace = false): DOMDocument; // 从XML字符串创建DOMDocument对象。

// 将PHP \ DOMDocument或\ DOMNode对象转换为简单数组
// 输入XML格式(作为字符串)
//     <?xml version="1.0" encoding="UTF-8"?>
//     <parent parent-attribute="value">Content of parent tag<child>Content of child tag</child></parent>。
// 输出数组格式
// $result = [
//     '_node'     => '#document',
//     '_text'     => null,
//     '_cdata'    => null,
//     '_attrs'    => [],
//     '_children' => [
//         [
//             '_node'     => 'parent',
//             '_text'     => "Content of parent tag",
//             '_cdata'    => null,
//             '_attrs'    => ['parent-attribute' => 'value'],
//             '_children' => [
//                 [
//                     '_node'     => 'child',
//                     '_text'     => "Content of child tag",
//                     '_cdata'    => null,
//                     '_attrs'    => [],
//                     '_children' => [],
//                 ],
//             ]
//         ]
//     ]
// ];
Xml::dom2Array(DOMNode $element): array;

Xml::escape(?string|int|float|null $rawXmlContent): string; // 将字符串转义后保存为xml内容。

```## 链接(思路和一些功能)
 * utilphp - https://github.com/brandonwamboldt/utilphp
 * PHPBinString - https://github.com/Grandt/PHPBinString
 * PHP的URLify - https://github.com/jbroadway/urlify
 * LinkifyURL项目 https://github.com/jmrware/LinkifyURL
 * http://www.phpexperts.pro
 * http://stackoverflow.com/a/11709412/430062
 * http://stackoverflow.com/questions/8321620/array-unique-vs-array-flip
 * http://shiflett.org/blog/2006/mar/server-name-versus-http-host
 * https://github.com/joomla-framework/string
 * Askar (ARACOOL) https://github.com/ARACOOOL
 * Sebastian Bergmann https://github.com/sebastianbergmann/php-timer
 * Sebastian Bergmann https://github.com/sebastianbergmann/environment
 * Oscar Otero https://github.com/oscarotero/env


## 单元测试和检查代码风格
```sh
make
make test-all

许可证

MIT

参见

  • CI-Report-Converter - 将不同的错误报告转换为与流行CI系统深度兼容的格式。
  • Composer-Diff - 查看“composer update”后哪些包发生了变化。
  • Composer-Graph - 基于mermaid-js的composer.json的依赖图可视化。
  • Mermaid-PHP - 利用mermaid脚本语言生成图表和流程图。
  • Image - 该包提供了一种面向对象的方式来尽可能简单地操作图像。
  • Data - ArrayObject的扩展实现。使用文件作为配置/数组。
  • Retry - 微小的PHP库提供了多个退避策略和抖动支持的重试/退避功能。
  • SimpleTypes - 转换任何值和度量单位 - 货币、重量、汇率、长度等。
标签:工具分享, 学习笔记