firehed / input
PHP 输入处理工具
2.3.1
2021-10-08 21:50 UTC
Requires
- php: ^7.2 || ^8.0
Requires (Dev)
- phpstan/phpstan: ^0.12.32
- phpstan/phpstan-phpunit: ^0.12
- phpunit/phpunit: ^8.3 || ^9
- squizlabs/php_codesniffer: ^3.6
- dev-master
- v3.x-dev
- v2.x-dev
- 2.3.1
- 2.3.0
- 2.2.0
- 2.1.5
- 2.1.4
- 2.1.3
- 2.1.2
- 2.1.1
- 2.1.0
- 2.0.0
- 1.0.0
- 0.0.4
- 0.0.3
- 0.0.2
- 0.0.1
- dev-dependabot/composer/phpunit/phpunit-tw-11.3.6
- dev-dependabot/composer/phpunit/phpunit-tw-11.3.5
- dev-dependabot/composer/phpstan/phpstan-phpunit-tw-1.4
- dev-dependabot/composer/phpstan/phpstan-tw-1.11.7
- dev-add-validators
- dev-v3-develop
This package is auto-updated.
Last update: 2024-09-19 22:50:45 UTC
README
一个名字平淡无奇的输入验证框架
概念
输入验证是任何Web应用中的重要任务,但始终是一个极其繁琐的任务。它用合适的数据结构取代了交织的检查,清晰地定义了所需和可选的输入。
该设计围绕着API驱动设计理念,其中每个API端点是它自己的对象,但不明确要求此格式。
- 它可以验证任何定义了输入要求的对象。它难以处理的是大型控制器中常见的模式,这些控制器负责许多URL,因为每个URL都有自己的验证要求。当然,您可以结构化代码以使其工作,但这可能会比它提供的利益更复杂。
数据处理步骤
原始输入通过两个主要步骤转换为安全数据
- 解析
- 验证
解析负责将原始输入字符串转换为关联数组。如果您的应用程序结构允许,此步骤可以完全跳过。
验证是库中最有用的部分——接受一组定义的必需和可选参数及其类型,并将输入值与规范进行比较。该实现完全阻止了无效数据被传播;无法从无效数据创建一个SafeInput
对象(您的应用程序将使用)!
完成此过程后,将返回一个包含符合由实现ValidationInterface
的对象定义的规范的SafeInput
对象(缺少的可选值为null)。
由于此库旨在提供可信数据,因此它将积极防止您对其产生怀疑;例如,对数据结构使用isset
或empty
会抛出异常。作者的经验是,不能相信验证数据是一种反模式和代码恶臭;如果您坚持这样做,这不是适合您的工具。这种强制信任往往会导致文档与现实脱节。
示例
以下是一个基本示例
some_controller_file.php
<?php // This would be in its own file use Firehed\Input\Interfaces\ValidationInterface; use Firehed\Input\Containers\SafeInput; use Firehed\Input\Objects as O; class Endpoint implements ValidationInterface { public function getOptionalInputs() { return [ 'bar' => new O\Text(), 'baz' => (new O\Text())->setDefaultValue('my baz'), ]; } public function getRequiredInputs() { return [ 'foo' => new O\Text(), ]; } public function execute(SafeInput $i) { // ... do some magic // $i['foo'] will be a string // $i['bar'] will be a string or null, since it was optional // $i['baz'] will be a string or 'my baz', since it was an optional with a default value } }
index.php
<?php // This is the core of your Front Controller use Firehed\Input\Containers\RawInput; use Firehed\Input\Parsers\URLEncoded; // The endpoint should be detrmined by your router $endpoint = new Endpoint(); // The parser should be determined by the Content-Type header $parser = new URLEncoded(); try { $input = (new RawInput("foo=world")) ->parse($parser) ->validate($endpoint); $endpoint->execute($input); } catch (Firehed\Input\Exceptions\InputException $e) { // The input contained invalid data } catch (Exception $e) { // Do any logging, error responses, etc. echo $e; }