loophp/unaltered-psr-http-message-bridge-bundle

symfony/psr-http-message-bridge 的即插即用替代品,不修改查询参数。

2.0.5 2022-05-11 07:30 UTC

README

Latest Stable Version GitHub stars Total Downloads GitHub Workflow Status Scrutinizer code quality Type Coverage Code Coverage License Donate! Donate!

未修改的 PSR HTTP 消息桥接包

一个可选的、即插即用的 symfony/psr-http-message-bridge 替代包,它不会修改查询参数。

此包将在您的 Symfony 应用程序中为服务 PsrHttpFactory 注册一个装饰器。

symfony/psr-http-message-bridge 的原始类唯一的区别是,当将 Symfony 请求转换为 PSR7 请求时,它不会修改查询参数。

上下文

TL;DR

Symfony 的 Request 类 使用 parse_str() 函数来解析查询字符串,但是 parse_str() 会修改包含 . 的参数键,并将它们替换为 _。这个问题使得当需要大量依赖查询参数的某些逻辑时(例如 API PlatformCAS 等),Request 对象更难处理。

需求

  • PHP >= 7.1.3
  • Symfony >= 4

安装

composer require loophp/unaltered-psr-http-message-bridge-bundle

使用

<?php

declare(strict_types=1);

namespace App\Controller;

use Psr\Http\Message\RequestInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bridge\PsrHttpMessage\HttpMessageFactoryInterface;

final class MainController {
    /**
     * @Route("/api/offers", name="api_offers")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function __invoke(
        Request $request,
        HttpMessageFactoryInterface $httpMessageFactory,
        RequestInterface $psrRequest
    ): Response {
        // Using Symfony's request object.
        $uri = $request->getUri(); // http://localhost:8000/api/offers?product_color=red
        $params = $request->query->all(); // [ 'product_color' => 'red' ]

        // Using PSR Request.
        $psrRequest = $httpMessageFactory->createRequest($request);
        $uri = (string) $psrRequest->getUri(); // http://localhost:8000/api/offers?product.color=red
        $params = $psrRequest->getUri()->getQuery(); // 'product.color=red'

        // Or directly by requesting the PSR request through RequestInterface parameter.

        return new Response('');
    }
}

请注意,当使用 Symfony Request 对象时,查询字符串参数已被修改,从 field.filter 变为 field_filter

配置

没有配置,您只需在应用程序中引入此包即可。

代码质量、测试和基准测试

每次向库中引入更改时,Github 都会运行测试和基准测试。

库使用 PHPSpec 编写了测试。您可以在 spec 目录中自由查看它们。运行 composer phpspec 以触发测试。

在每次提交之前,都会使用 GrumPHP 执行一些检查,运行 ./vendor/bin/grumphp run 以手动检查。

PHPInfection 用于确保您的代码得到了适当的测试,运行 composer infection 以测试您的代码。

贡献

请随时通过发送 Github pull 请求来贡献。我相当有反应 :-)

变更日志

请参阅 CHANGELOG.md,以获取基于 git 提交 的变更日志。

有关更详细的变更日志,请查看 发布变更日志