定制 proklung/request-log-bundle 二次开发

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

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

proklung/request-log-bundle

Composer 安装命令:

composer require proklung/request-log-bundle

包简介

Бандл для создания и использования моков Response.

README 文档

README

Форк пакета. Доработан под личные нужды, плюс добавил некоторые экспериментальные битриксовые наработки (получилось не стабильно).

Зачем?

Удобно генерировать фикстуры для функциональных тестов из ответов внешнего API.

Основное

  1. Добавляешь заголовок x-generate-response-mock к запросу - получаешь мок в виде файла. Если мок уже существует, то отдаются данные из него

Известные ограничения

Если GET запрос очень длинный - превышает 255 символов, - то облом, сохранить мок не удается.

Битриксовые дела

Если бандл грузится не из под Битрикса, то соответствующие сервисы удаляются из контейнера.

Идея - создавать моки по url, использующим нативные битриксовые средства (или даже статические страницы).

В конфигурации бандла (файл /local/config/packages/request_log.yaml) в секции bitrix_uri_list указываются regex паттерны страниц, подвергающихся обработке.

Установка

composer require proklung/request-log-bundle

Оригинальная документация

Description

This bundle allows to log HTTP requests and associated responses as json files. This generated json files can be used as API mock in order to test a front app without running the api.

How it works ?

After each request (Kernel::TERMINATE event) containing the x-generate-response-mock header, a json file is created containing the request and the response.

Examples :

GET /categories

app/log/mocks/categories/GET__.json

{
    "request": {
        "uri": "/categories",
        "method": "GET",
        "parameters": [],
        "content": ""
    },
    "response": {
        "statusCode": 200,
        "contentType": "application/json",
        "content": {
            "@context": "/contexts/Category",
            "@id": "/categories",
            "hydra:member": [
                {"name": "foo"},
                {"name": "bar"}
            ]
        }
    }
}

PUT /categories/1 {"foo": "bar"}

app/log/mocks/categories/PUT__1-a5e74.json

{
    "request": {
        "uri": "/categories/1",
        "method": "PUT",
        "parameters": [],
        "content": {
            "foo": "bar"
        }
    },
    "response": {
        "statusCode": 204,
        "contentType": "application/json",
        "content": ""
    }
}

File naming strategy

All files are created with the following convention :

uri/METHOD__segments{--sorted-query=string&others}{__<sha1_substr5(sortedJsonContent)>}{__<sha1_substr5(sortedPostParameters)>}.json

Examples :

URL Filename
GET / GET__.json
GET /categories categories/GET__.json
GET /categories/1 categories/GET__1.json
GET /categories?search[category][]=foo categories/GET__--search%5Bcategory%5D%5B%5D=foo.json
GET /categories?order[foo]=asc&order[bar]=desc categories/GET__--order%5Bbar%5D=desc&order%5Bfoo%5D=asc.json
GET /categories?parent=/my/iri categories/GET__--parent=%2Fmy%2Firi.json
POST /categories PARAMS: foo1=bar1; foo2=bar2 categories/POST____3e038.json
POST /categories CONTENT: {"foo1":"bar1", "foo2":"bar2"} categories/POST____3e038.json
PUT /categories/1 CONTENT: {"foo2":"bar2", "foo1":"bar1"} categories/POST__1__3e038.json
The filenames query strings can be hashed by setting the `hash_query_params` option to `true`.
For example, `categories/GET__--order[bar]=desc&order[foo]=asc.json` will be `categories/GET__--b0324.json`

The filenames query strings with non-asssocitive arrays are not indexed by default : `?foo[]=bar`.
You can use the indexed format by setting the `use_indexed_associative_array` option to `true` : `?foo[0]=bar`.

If necessary, configure the bundle to your needs (example with default values):

# app/config/config_dev.yml

request_log:
    mocks_dir: %kernel.logs_dir%/mocks/
    hash_query_params: false
    use_indexed_associative_array: false
    # Битриксовые URL (нестабильный функционал)
    bitrix_uri_list:
     # - '/^\/clubs\/$/'
     #  - '/^\/about\/$/'
     # - '/^\/xxx\/$/'

If your are using the NelmioCorsBundle or another CORS protection, you must add the header in the allowed ones :

nelmio_cors:
    defaults:
        allow_headers: ['x-generate-response-mock']

Usage

The request & response logger is not always activated. To log a request, add the x-generate-response-mock header into your request :

GET /categories HTTP/1.1
Host: api.my.domain
x-generate-response-mock: true

Commands

Some useful commands are available to manager your mocks :

Clear all mocks

app/console mroca:request-log:clear 

Save mocks in a target directory

app/console mroca:request-log:dump /tmp/mocksdirtarget

proklung/request-log-bundle 适用场景与选型建议

proklung/request-log-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 17 次下载、GitHub Stars 达 1, 最近一次更新时间为 2021 年 05 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 proklung/request-log-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 proklung/request-log-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 proklung/request-log-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-05-03