定制 patricksavalle/slim-request-params 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

patricksavalle/slim-request-params

Composer 安装命令:

composer require patricksavalle/slim-request-params

包简介

Adds request-parameter validation to the SLIM 3.x PHP framework

README 文档

README

Needs PHP 7.x

Validates request query-parameters and body-parameters ($_GET and $_BODY) and HTTP-headers using regular expressions. Adds a layer of security and self-documentation to your API-code. Uses the same syntax as SLIM uses for route-segments.

Example:

use SlimRequestParams\QueryParameters;

$slimapp->get('', ...)
    ->add(new QueryParameters([
        '{text:\w+}',
        '{fromdate:\date}',
        '{distance:\float},0.0',
        '{orderby:(name|date)},name',
        '{reversed:\bool},false',
        '{offset:\int},1',
        '{count:\int},100',
    ]);

This would for example accept this request:

GET yourdomain.com?text=airplane&fromdate=2016-10-10

And it would for example reject these requests:

GET yourdomain.com?text=airplane&fromdate=2016-10-10&whatever=23
GET yourdomain.com?text=airplane&fromdate=date
GET yourdomain.com?fromdate=2016-10-10&whatever=23
GET yourdomain.com?text=airplane&
GET yourdomain.com

etc.

0. Install with Composer

  • Update your composer.json to require patricksavalle/slim-request-params.

  • Run composer install to add slim-request-params your vendor folder.

    {
      "require": {
        "patricksavalle/slim-request-params": "^1.0"
      }
    }
  • Include in your source.

    <?php
    
    require './vendor/autoload.php';

1. Add the middleware to the SLIM routes

To validate request parameters:

use SlimRequestParams\QueryParameters;

$slimapp->get(...)
    ->add(new QueryParameters([
        '{author:[\w-. @]+}',
        '{orderby:\w+},id',
        '{reversed:1},1',
        '{offset:\int},1',
        '{count:\int},100',
        '{*}',
    ])

To validate body parameters (posted by client as x-www-form-urlencoded):

use SlimRequestParams\BodyParameters;

$slimapp->post(...)
    ->add(new BodyParameters([
        '{recipient:.*}',
        '{sender:.*}',
        '{subject:.*}',
        '{timestamp:.*}',
        '{token:.*}',
        '{signature:.*}',
        '{*}',
    ]));

To validate request headers (make sure they are present and their values follows a specific pattern):

use SlimRequestParams\RequestHeaders;

$slimapp->post(...)
    ->add(new RequestHeaders([
        '{HTTP_REFERER:\url}',
        '{HTTP_CB_SIGNATURE:.*}',
    ]));

To forbid arguments to a route:

$slimapp->get(...)
    ->add(new QueryParameters)

General format of a validation rule:

{<name>:<regex>},<optional_default_value>

Missing parameters are set to the given default.

Explicitely setting a value to null:

/someurl?key=  (leave value empty) 

Extra parameters generate an error unless the wildcard parameter is used: {*} in which case the extra parameters are passed without validation.

Accepts the RFC-standard query parameter array, not the PHP version:

/someurl?a=10&a=11&a=12

For typed parameters and special formats there are the following keywords that can be used instead of the regex:

\boolean
\int
\float
\date
\raw
\base64json
\url
\email
\country
\nationality
\timezone
\currency
\language
\bitcoinaddress
\moneroaddress
\xtext   (a XHTML fragment only using text formatting tags, tidies up the text)

These are only syntax checks! Also there is an accept 'anything else' argument:

{*}

Optional parameters should get the default:

\optional

(See code example above)

The RequestHeaders Middleware always accept 'anything else'.

2. Install the strategy in SLIM3.x for access to the validated arguments

Add the strategy that combines the url-, query- and post-parameters and request-headers into one object.

$slimapp->getContainer()['foundHandler'] = function () {
    return new RequestResponseArgsObject;
};        

3. Adapt your route handlers to the new strategy

A complete example.

<?php

declare(strict_types = 1);

namespace YourApi;

define("BASE_PATH", dirname(__FILE__));

require BASE_PATH . '/vendor/autoload.php';

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \SlimRequestParams\BodyParameters;
use \SlimRequestParams\QueryParameters;
use \SlimRequestParams\RequestResponseArgsObject;

$app = new \Slim\App;

$app->getContainer()['foundHandler'] = function () {
    return new RequestResponseArgsObject;
};

$app->get('/hello/{name}', function (Request $request, Response $response, \stdClass $args) {
    $name = $args->name;
    $text = $args->text;
    $referer = $args->referer;
    $response->getBody()->write("$text, $name, $referer");
    return $response;
})
    ->add(new RequestHeaders(['{HTTP_REFERER:\url']))
    ->add(new QueryParameters(['{text:[\w-.~@]+},Hello']));

$app->run();

To retrieve or inspect the validated parameters from anywhere in your app just use:

\SlimRequestParams\QueryParameters::get();
\SlimRequestParams\BodyParameters::get();
\SlimRequestParams\RequestHeaders::get();

统计信息

  • 总下载量: 1.97k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 11
  • 点击次数: 0
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 9
  • Watchers: 2
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-12-02

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固