kristos80/super-reader

0.1.0 2024-06-27 11:41 UTC

This package is auto-updated.

Last update: 2024-09-05 16:04:12 UTC


README

SuperReader 包提供了一种强大且灵活的方式来读取和操作 PHP 中的超全局变量。它允许轻松检索和比较超全局值,支持严格比较、类型转换和清理,以确保安全可靠地处理输入数据。

正在进行中(WIP)——请不要在生产环境中使用

  • 它尚未经过广泛的测试。
  • 主要用于内部项目,可能会在事先通知的情况下进行破坏性更改。
  • 可能缺少许多功能。

Coverage Status Mutation testing badge

功能

  • 灵活的源选择:从各种 PHP 超全局变量($_GET、$_POST、$_SERVER、$_ENV、$_COOKIE、$_SESSION)或直接从 php://input 中检索值。
  • 严格比较:对键执行大小写敏感或大小写不敏感的检查。
  • 类型转换:自动将值转换为指定的类型(例如,数组、对象、字符串、整数)。
  • 清理:确保值得到适当的清理,以防止 XSS 和其他安全问题。

安装

使用 Composer 安装包

composer require kristos80/super-reader

示例用法

use Kristos80\SuperReader\SuperReader;

$superReader = new SuperReader();

// Set the source superglobal to $_POST
$superReader->from(SuperReader::POST);

// Retrieve a variable with optional strict comparison and type casting
$userInput = $superReader->get(['user_input', 'user-input'], 'default_value', true, 'string');

// Check if a superglobal value matches one of the possible values
$isAdmin = $superReader->equals('user_role', ['admin', 'superadmin'], true);
// or
$isAdmin = $superReader->equals(['user_role', 'user-role'], ['admin', 'superadmin'], true);

// Retrieve raw input from php://input and cast it to an array
$jsonInput = $superReader->getFromInput(SuperReader::STDIN, 'array');

类参考

SuperReader

这个最终的只读类实现了 SuperReaderInterface。

方法

from

public function from(string $from = self::GET): SuperReaderInterface

参数

  • $from (string): 要读取的源超全局变量(默认为 $_GET)。

返回: (SuperReaderInterface): 当前实例,用于方法链。

equals

public function equals(
  string|array $possibleEnvNames,
  mixed $possibleEnvValues,
  bool $strict = FALSE,
  ?string $cast = NULL
): bool

参数

  • $possibleEnvNames (string|array): 要检查的环境变量名称。
  • $possibleEnvValues (mixed): 要比较的值。
  • $strict (bool): 是否在变量名称上执行大小写敏感的比较。
  • $cast (string|null): 可选的类型,将环境变量值转换为(例如,'array'、'object'、'string')。

返回: (bool): 如果环境变量值与可能的值之一匹配,则返回 true;否则返回 false。

get

public function get(
  string|array $possibleEnvNames,
  mixed $default = NULL,
  bool $strict = FALSE,
  ?string $cast = NULL
): mixed

参数

  • $possibleEnvNames (string|array): 要检索的环境变量名称。
  • $default (mixed|null): 如果未设置环境变量,则返回的默认值。
  • $strict (bool): 是否在变量名称上执行大小写敏感的搜索。
  • $cast (string|null): 可选的类型,将环境变量值转换为(例如,'array'、'object'、'string')。

返回: (mixed): 环境变量的值,如果提供了类型,则转换为指定类型,或返回默认值。

getFromInput

public function getFromInput(
  string $input = self::PHP_INPUT,
  ?string $cast = NULL
): mixed

参数

  • $input (string): 要读取的输入流(默认为 php://input)。
  • $cast (string|null): 可选的类型,将输入转换为(例如,'array'、'object')。

返回: (mixed): 原始输入值,如果提供了类型,则转换为指定类型。

贡献

请随时通过提交问题或拉取请求来贡献。确保您的代码遵循项目的编码标准,并包括适当的测试。