PHPackages                             tuuz/input - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. tuuz/input

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

tuuz/input
==========

ThinkPHP 8 parameter validation &amp; JSON response package: type-safe Input Post/Get extractors (Int/Float/Bool/DateTime/Json), Ret unified JSON responder (Success/Fail + HTTP shortcuts) and Conventional Commits message analyzer. PHP 8.5+ compatible.

v1.0.0(yesterday)00MITPHPPHP &gt;=8.5

Since Jul 31Pushed yesterdayCompare

[ Source](https://github.com/tobycroft/php_tuuz_input)[ Packagist](https://packagist.org/packages/tuuz/input)[ RSS](/packages/tuuz-input/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

tuuz/input
==========

[](#tuuzinput)

ThinkPHP 8.1+ 参数校验与 JSON 响应一体化组件包。

- **Input**：类型安全的 HTTP 参数提取器（Post / Get / Combi / Raw），自动触发参数缺失或类型错误的失败响应。
- **Ret**：统一 JSON 响应类，包含 Success / Fail 及常用 HTTP 状态码快捷方法。
- **CommitMessage\\Analyzer**：基于 Conventional Commits 规范的提交信息解析与描述生成器。
- **removeXSS()**：基于 HTMLPurifier 的 XSS 清洗助手函数（可选依赖）。

要求 PHP 8.5 及以上。

---

安装
--

[](#安装)

```
composer require tuuz/input
```

ThinkPHP 8 会通过 `extra.think.aliases` **自动注册门面别名** `Input` 与 `Ret`，无需额外配置即可在全局直接使用。

可选依赖（启用高级 XSS 清洗）：

```
composer require ezyang/htmlpurifier:^4.16
```

---

Input：参数提取（Input::）
-------------------

[](#input参数提取input)

所有 `Post*` / `Get*` 方法签名相同：

```
(string $name, bool $must_have = true)

```

- `$must_have = true`：缺失 / 类型不匹配 → 自动 `Ret::Fail(400, ...)` 输出 JSON 并 exit

方法返回类型说明`Input::Post($name, $must, $xss)``string`POST 字符串`Input::PostInt($name, $must)``int`POST 整数`Input::PostFloat($name, $must)``float`POST 浮点数`Input::PostBool($name, $must)``bool`POST 布尔`Input::PostDateTime($name, $must)``string|null`RFC3339 格式时间`Input::PostJson($name, $must)``array`JSON 字符串 → 数组`Input::Get($name, $must, $xss)``string`GET 字符串`Input::GetInt($name, $must)``int`GET 整数`Input::GetFloat($name, $must)``float`GET 浮点数`Input::GetBool($name, $must)``bool`GET 布尔`Input::GetDateTime($name, $must)``string|null`RFC3339 格式时间`Input::GetJson($name, $must)``array`JSON 字符串 → 数组`Input::Combi($name, $must, $xss)``string`POST 优先，其次 GET`Input::Raw()``string`原始 `php://input``Post/Get/Combi` 的第三个参数 `$xss = true` 会对值调用 `strip_tags` 做基础 XSS 过滤。

示例：

```
$id      = Input::PostInt('id');                              // 0 也合法（严格判空）
$name    = Input::Post('name', true, true);                   // 必须且 XSS 过滤
$page    = Input::GetInt('page', false) ?: 1;                 // 非必须，默认 1
$enabled = Input::PostBool('enabled');                        // true / false 皆合法
$tags    = Input::PostJson('tags');                           // 解析为数组
```

### 替换默认失败响应类

[](#替换默认失败响应类)

`Input` 默认使用包内的 `Ret::Fail`。若需改用项目自定义响应类：

```
Input::setRetClass(\app\common\MyRet::class);
```

目标类需具备静态方法 `Fail(int $code, mixed $data, string $msg): void`。

---

Ret：JSON 响应（Ret::）
------------------

[](#retjson-响应ret)

### 基础

[](#基础)

```
Ret::Success(0, ['id' => 1, 'name' => 'x'], '操作成功');
Ret::Ok(['list' => [...]]);               // code=0 简写

Ret::Fail(400, [], '参数错误');
Ret::Error(400, '缺少字段 id');
```

输出格式统一：

```
{"code":0,"data":[],"echo":"成功"}
```

### HTTP 快捷方法

[](#http-快捷方法)

方法默认 code默认 echo`Ret::Ok($data, $echo)`0成功`Ret::BadRequest($echo, $data)`400参数错误`Ret::Unauthorized($echo, $data)`401鉴权失败`Ret::Forbidden($echo, $data)`403权限不足`Ret::NotFound($echo, $data)`404未找到数据`Ret::ServerError($echo, $data)`500数据库错误`Ret::Error($code, $echo, $data)`任意失败### 内置 code → 默认提示词对照表

[](#内置-code--默认提示词对照表)

code文案0成功-1登录失效请重新登录400参数错误401鉴权失败403权限不足404未找到数据406 / 407数据不符合期待500数据库错误其他失败### 运行时配置

[](#运行时配置)

```
// 覆盖或追加状态码文案（i18n / 项目自定义）
Ret::setMessage(1001, '库存不足');
Ret::setMessages([-2 => '签名过期', 1002 => '频率超限']);
Ret::getMessages();

// 单元测试 / SSE 等特殊场景：只输出不 exit
Ret::setExitAfterSend(false);
Ret::setExitAfterSend(true, 0);    // 第二个参数是 exit code

// 自定义 Content-Type（传 null 则不发送任何头）
Ret::setContentType('application/json; charset=utf-8');
Ret::setContentType(null);
```

### 纯构造（不 exit / 不 echo）

[](#纯构造不-exit--不-echo)

```
$array = Ret::build(0, ['a' => 1]);
// ['code'=>0, 'data'=>['a'=>1], 'echo'=>'成功']

$json = Ret::toJson(400, [], '缺少参数 id');
// 直接返回 JSON 字符串，供队列/日志/测试使用
```

---

removeXSS() 助手函数
----------------

[](#removexss-助手函数)

```
$cleanHtml = removeXSS($userInput);
```

- 未安装 `ezyang/htmlpurifier` 时原样返回。
- 非字符串入参原样返回。
- 白名单标签：`div,b,strong,i,em,a[href|title],ul,ol,li,p[style],br,span[style],img[width|height|alt|src]`。
- 白名单 CSS 属性：`font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align`。
- `HTML.TargetBlank = true`。

---

CommitMessage\\Analyzer：提交信息解析与描述生成
-----------------------------------

[](#commitmessageanalyzer提交信息解析与描述生成)

基于 [Conventional Commits](https://www.conventionalcommits.org/) 规范。

```
use Tuuz\Input\CommitMessage\Analyzer;

$msg = "feat(input)!: add GetInt method

Adds a typed getter for query-string integers

BREAKING CHANGE: minimum PHP version bumped to 8.5
Refs: #123";

$a = Analyzer::from($msg);
```

### 基础 API

[](#基础-api)

方法说明`$a->isValid()`是否符合规范`$a->getType()``feat` / `fix` / ...`$a->getTypeDescription()`类型英文描述`$a->getScope()``input` 或 null`$a->isBreakingChange()`是否破坏性变更（header `!` 或 footer `BREAKING CHANGE`）`$a->getSubject()`主语`$a->getBody()`正文`$a->getFooter()`页脚`$a->getErrors()`校验错误数组`$a->getMessage()`原始消息`$a->toArray()`数组导出`$a->generateDescription()`生成带 Markdown 格式的人类可读描述`$a->getBumpLevel()`SemVer 升级级别：`major` / `minor` / `patch`，无法判断返回 null### generateDescription() 示例输出

[](#generatedescription-示例输出)

```
**Type:** feat (A new feature)

**Scope:** input

⚠️ **BREAKING CHANGE**

**Subject:** add GetInt method

**Body:**
Adds a typed getter for query-string integers

**Footer:**
BREAKING CHANGE: minimum PHP version bumped to 8.5
Refs: #123

```

### SemVer 升级级别判定

[](#semver-升级级别判定)

条件级别`!` 或 footer `BREAKING CHANGE``major``type === feat``minor``type === fix` 或 `type === perf``patch`其他类型`null`### 支持的提交类型

[](#支持的提交类型)

```
Analyzer::getTypeDescriptions();
```

typedescriptionfeatA new featurefixA bug fixdocsDocumentation only changesstyleChanges that do not affect the meaning of the coderefactorA code change that neither fixes a bug nor adds a featureperfA code change that improves performancetestAdding missing tests or correcting existing testschoreChanges to the build process or auxiliary toolsbuildChanges that affect the build system or external dependenciesciChanges to CI configuration files and scriptsrevertReverts a previous commit### 校验规则

[](#校验规则)

- Header 必须满足：`type(scope)!: subject`
- `subject` 长度 ≤ 50，不允许以 `.` 结尾
- body / footer 每行 ≤ 72 字符
- 错误信息通过 `getErrors()` 返回

---

命名空间类名对照
--------

[](#命名空间类名对照)

用途推荐调用方式完全限定名（FQSEN）门面 Input`Input::xxx()``Tuuz\Input\Facade\Input`门面 Ret`Ret::xxx()``Tuuz\Input\Facade\Ret`核心 Input`use Tuuz\Input\Input``Tuuz\Input\Input`核心 Ret`use Tuuz\Input\Ret``Tuuz\Input\Ret`提交解析器`use Tuuz\Input\CommitMessage\Analyzer``Tuuz\Input\CommitMessage\Analyzer`XSS 助手全局函数`removeXSS()`（`Tuuz\Input\Helper\functions.php`）---

License
-------

[](#license)

MIT

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/04f1f999374b5cfe445b20e876e6f22d89fa91bce2f421295cd43ba0f8095865?d=identicon)[tobycroft](/maintainers/tobycroft)

---

Top Contributors

[![tobycroft](https://avatars.githubusercontent.com/u/24893075?v=4)](https://github.com/tobycroft "tobycroft (4 commits)")

---

Tags

requestvalidatorvalidationsemverparameterxssinputcommit messagephp85conventional-commitsthinkphptype-safetythinkphp8tuuz

### Embed Badge

![Health badge](/badges/tuuz-input/health.svg)

```
[![Health](https://phpackages.com/badges/tuuz-input/health.svg)](https://phpackages.com/packages/tuuz-input)
```

###  Alternatives

[vlucas/valitron

Simple, elegant, stand-alone validation library with NO dependencies

1.7k4.7M143](/packages/vlucas-valitron)[wixel/gump

A fast, extensible &amp; stand-alone PHP input validation class that allows you to validate any data.

1.2k1.4M33](/packages/wixel-gump)[z4kn4fein/php-semver

Semantic Versioning library for PHP. It implements the full semantic version 2.0.0 specification and provides ability to parse, compare, and increment semantic versions along with validation against constraints.

271.8M19](/packages/z4kn4fein-php-semver)[phpexperts/datatype-validator

An easy to use data type validator (both strict and fuzzy).

131.2M2](/packages/phpexperts-datatype-validator)[dragon-code/card-number

Generation and verification of card numbers using Luhn's algorithm.

6813.9k](/packages/dragon-code-card-number)[workerman/validation

The most awesome validation engine ever created for PHP. Respect/Validation 汉化版本

2236.5k9](/packages/workerman-validation)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
