httpsoft/http-server-request

创建PSR-7 ServerRequest和UploadedFile的基础设施

1.1.0 2023-05-05 19:55 UTC

This package is auto-updated.

Last update: 2024-09-05 23:04:56 UTC


README

License Latest Stable Version Total Downloads GitHub Build Status GitHub Static Analysis Status Scrutinizer Code Coverage Scrutinizer Code Quality

此包简化并增强了创建PSR-7组件ServerRequestUploadedFile的过程。

依赖于httpsoft/http-message包。

文档

安装

此包需要PHP版本7.4或更高版本。

composer require httpsoft/http-server-request

使用ServerRequestCreator

use HttpSoft\ServerRequest\ServerRequestCreator;

// All necessary data will be received automatically:
$request = ServerRequestCreator::createFromGlobals($_SERVER, $_FILES, $_COOKIE, $_GET, $_POST);
// equivalently to:
$request = ServerRequestCreator::createFromGlobals();
// equivalently to:
$request = ServerRequestCreator::create();

默认情况下,使用HttpSoft\ServerRequest\SapiNormalizer进行服务器参数的规范化。您可以使用自己的服务器参数规范化器,为此您需要实现HttpSoft\ServerRequest\ServerNormalizerInterface接口。

$normalizer = new YouCustomServerNormalizer();

$request = ServerRequestCreator::create($normalizer);
// equivalently to:
$request = ServerRequestCreator::createFromGlobals($_SERVER, $_FILES, $_COOKIE, $_GET, $_POST, $normalizer);
// or with custom superglobals:
$request = ServerRequestCreator::createFromGlobals($server, $files, $cookie, $get, $post, $normalizer);

使用UploadedFileCreator

use HttpSoft\ServerRequest\UploadedFileCreator;

/** @var StreamInterface|string|resource $streamOrFile */
$uploadedFile = UploadedFileCreator::create($streamOrFile, 1024, UPLOAD_ERR_OK, 'file.txt', 'text/plain');

// Create a new `HttpSoft\UploadedFile\UploadedFile` instance from array (the item `$_FILES`)
$uploadedFile = UploadedFileCreator::createFromArray([
    'name' => 'filename.jpg', // optional
    'type' => 'image/jpeg', // optional
    'tmp_name' => '/tmp/php/php6hst32',
    'error' => 0, // UPLOAD_ERR_OK
    'size' => 98174,
]);

// Normalizes the superglobal structure and converts each array
// value to an instance of `Psr\Http\Message\UploadedFileInterface`.
$uploadedFiles = UploadedFileCreator::createFromGlobals($_FILES);