承接 brick/json-mapper 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

brick/json-mapper

Composer 安装命令:

composer require brick/json-mapper

包简介

Maps JSON data to strongly typed PHP DTOs

README 文档

README

Maps JSON data to strongly typed PHP DTOs.

Build Status Coverage Status Latest Stable Version Total Downloads License

Introduction

This library provides an easy-to-use, secure, and powerful way to map JSON data to strongly typed PHP objects.

It reads parameter types & annotations defined on your class constructors to map JSON data to your DTOs, and can work with zero configuration.

Installation

This library is installable via Composer:

composer require brick/json-mapper

Requirements

This library requires PHP 8.2 or later.

Project status & release process

While this library is still under development, it is well tested and considered stable enough to use in production environments.

The current releases are numbered 0.x.y. When a non-breaking change is introduced (adding new methods, optimizing existing code, etc.), y is incremented.

When a breaking change is introduced, a new 0.x version cycle is always started.

It is therefore safe to lock your project to a given release cycle, such as 0.1.*.

If you need to upgrade to a newer release cycle, check the release history for a list of changes introduced by each further 0.x.0 version.

Usage

Basic usage

JsonMapper provides a single method, map(), which takes a JSON string and a class name, and returns an instance of the given class.

use Brick\JsonMapper\JsonMapper;

class User
{
    public function __construct(
        public int $id,
        public string $name,
    ) {
    }
}

$json = '{
  "id": 123,
  "name": "John Doe"
}';

$mapper = new JsonMapper();
$user = $mapper->map($json, User::class);

echo $user->name; // John Doe

Nested objects

JsonMapper will read the parameter types and annotations to map nested objects:

class Album
{
    public function __construct(
        public int $id,
        public string $title,
        public Artist $artist,
    ) {
    }
}

class Artist
{
    public function __construct(
        public int $id,
        public string $name,
    ) {
    }
}

$json = '{
  "id": 456,
  "title": "The Wall",
  "artist": {
    "id": 789,
    "name": "Pink Floyd"
  }
}';

$mapper = new JsonMapper();
$album = $mapper->map($json, Album::class);

echo $album->artist->name; // Pink Floyd

Arrays

Arrays can be documented with @param annotations, that will be parsed and used to map the JSON data:

class Customer
{
    /**
     * @param Address[] $addresses
     */
    public function __construct(
        public int $id,
        public string $name,
        public array $addresses,
    ) {
    }
}

class Address
{
    public function __construct(
        public string $street,
        public string $city,
    ) {
    }
}

$json = '{
  "id": 123,
  "name": "John Doe",
  "addresses": [
    {
      "street": "123 Main Street",
      "city": "New York"
    },
    {
      "street": "456 Side Street",
      "city": "New York"
    }
  ]
}';

$mapper = new JsonMapper();
$customer = $mapper->map($json, Customer::class);

foreach ($customer->addresses as $address) {
    var_export($address instanceof Address); // true
}

Union types

If a parameter is a declared as a union of possible types, JsonMapper will automatically attempt to map the JSON data to the correct type:

class Order
{
    public function __construct(
        public readonly int $id,
        public readonly string $amount,
        public readonly Person|Company $customer, // union type
    ) {
    }
}

class Person
{
    public function __construct(
        public readonly int $id,
        public readonly string $firstname,
        public readonly string $lastname,
    ) {
    }
}

class Company
{
    public function __construct(
        public readonly int $id,
        public readonly string $name,
        public readonly string $companyNumber,
    ) {
    }
}

$json = '{
  "id": 1,
  "amount": "24.99",
  "customer": {
    "id": 2,
    "firstname": "John",
    "lastname": "Doe"
  }
}';

$mapper = new JsonMapper();
$order = $mapper->map($json, Order::class);

// JsonMapper automatically determined that the "id", "firstname",
// and "lastname" properties correspond to a Person and not a Company.
var_export($order->customer instanceof Person); // true

To achieve this, JsonMapper attempts to map a JSON object to every possible PHP class in the union. If no class matches, or if several classes match, an exception is thrown.

Complex unions

JsonMapper can parse, map, and verify any combination of possibly nested types:

/**
 * @param (Person|Company|(string|int)[])[]|null $customers
 */
public function __construct(
    public readonly ?array $customers,
) {
}

This currently comes with two limitations:

  • you must use the Type[] syntax for arrays, and not the array<Type> syntax;

  • you cannot use more than one array type per union; for example, this is allowed:

    /**
     * @param (Person|Company)[] $value
     */

    but this is not:

    /**
     * @param Person[]|Company[] $value
     */

Enums

JsonMapper can map JSON strings and integers to backed enums:

class Order
{
    public function __construct(
        public readonly int $id,
        public readonly OrderStatus $status,
    ) {
    }
}

enum OrderStatus: string {
    case PENDING = 'pending';
    case SHIPPED = 'shipped';
    case DELIVERED = 'delivered';
}

$json = '{
  "id": 1,
  "status": "shipped"
}';

$mapper = new JsonMapper();
$order = $mapper->map($json, Order::class);

var_export($order->status === OrderStatus::SHIPPED); // true

Non-backed enums, i.e. enums that do not have a string or int value, are not supported on purpose.

Strictness

The library has very strict defaults (some of which can be overridden by config), and will throw an exception if the JSON data does not exactly match the DTO's constructor signature, or if the DTO contains invalid or unsupported @param annotations.

The types of the parameters must match exactly, with the same semantics as PHP's strict_types.

JsonMapper guarantees that every constructor parameter, even softly-typed with @param, will be passed a value that is compatible with the declared type. The result is a DTO that can be 100% trusted by your static analysis tool.

Options

The JsonMapper constructor accepts the following options:

  • $allowUntypedArrays

    By default, JsonMapper will throw an exception if the parameter is declared as array without a corresponding @param annotation, or is just documented as @param array.

    By setting this option to true, JsonMapper will allow such parameters, and accept to pass a JSON array as is, without checking or mapping its contents:

    $mapper = new JsonMapper(
        allowUntypedArrays: true,
    );
  • $allowUntypedObjects

    By default, JsonMapper will throw an exception if a parameter is declared as object or stdClass.

    By setting this option to true, JsonMapper will allow such parameters, and accept to pass a JSON object as an stdClass instance, without checking or mapping its contents:

    $mapper = new JsonMapper(
        allowUntypedObjects: true,
    );
  • $allowMixed

    By default, JsonMapper will throw an exception if a parameter is declared as mixed.

    By setting this option to true, JsonMapper will allow such parameters, and accept to pass a JSON value as is, without checking or mapping its contents:

    $mapper = new JsonMapper(
        allowMixed: true,
    );
  • $onExtraProperties

    This option accepts an OnExtraProperties enum value, and controls how JsonMapper reacts if a JSON object contains a property that does not have a matching parameter in the corresponding DTO's constructor signature:

    • OnExtraProperties::ThrowException

      JsonMapper will throw a JsonMapperException. This is the default value.

    • OnExtraProperties::Ignore

      JsonMapper will ignore any extra properties:

      use Brick\JsonMapper\JsonMapper;
      use Brick\JsonMapper\OnExtraProperties;
      
      class Order
      {
          public function __construct(
              public readonly int $id,
              public readonly string $amount,
          ) {
          }
      }
      
      $json = '{
        "id": 1,
        "amount": "100.00",
        "extraProperty": "foo",
        "otherExtraProperty": "bar"
      }';
      
      $mapper = new JsonMapper(
          onExtraProperties: OnExtraProperties::Ignore,
      );
      
      // extra properties "extraProperty" and "otherExtraProperty" are ignored,
      // and do not throw an exception anymore.
      $order = $mapper->map($json, Order::class);
  • $onMissingProperties

    This option accepts an OnMissingProperties enum value, and controls how JsonMapper reacts if a JSON object is missing a property that is declared in the corresponding DTO's constructor signature:

    • OnMissingProperties::ThrowException

      JsonMapper will throw a JsonMapperException. This is the default value.

    • OnMissingProperties::SetNull

      JsonMapper will set the parameter to null if the JSON property is missing and the parameter is nullable:

      use Brick\JsonMapper\JsonMapper;
      use Brick\JsonMapper\OnMissingProperties;
      
      class Order
      {
          public function __construct(
              public readonly int $id,
              public readonly ?string $customerName,
          ) {
          }
      }
      
      $json = '{
        "id": 1
      }';
      
      $mapper = new JsonMapper(
          onMissingProperties: OnMissingProperties::SetNull,
      );
      
      $order = $mapper->map($json, Order::class);
      var_export($order->customerName); // NULL

      If the property is missing and the parameter is not nullable, an exception will be thrown regardless of this option.

    • OnMissingProperties::SetDefault

      JsonMapper will set the parameter to its default value if the JSON property is missing and the parameter has a default value:

      use Brick\JsonMapper\JsonMapper;
      use Brick\JsonMapper\OnMissingProperties;
      
      class Order
      {
          public function __construct(
              public readonly int $id,
              public readonly string $customerName = 'no name',
          ) {
          }
      }
      
      $json = '{
        "id": 1
      }';
      
      $mapper = new JsonMapper(
          onMissingProperties: OnMissingProperties::SetDefault,
      );
      
      $order = $mapper->map($json, Order::class);
      var_export($order->customerName); // 'no name'

      If the property is missing and the parameter does not have a default value, an exception will be thrown regardless of this option.

  • $jsonToPhpNameMapper & $phpToJsonNameMapper

    By default, JsonMapper assumes that the JSON property names are the same as the PHP parameter names.

    By providing implementations of the NameMapper interface, you can customize the mapping between the two.

    The library comes with two implementations for a common use case:

    • SnakeCaseToCamelCaseMapper will convert snake_case camelCase
    • CamelCaseToSnakeCaseMapper will convert camelCase to snake_case

    Example:

    use Brick\JsonMapper\JsonMapper;
    use Brick\JsonMapper\NameMapper\CamelCaseToSnakeCaseMapper;
    use Brick\JsonMapper\NameMapper\SnakeCaseToCamelCaseMapper;
    
    class Order
    {
        public function __construct(
            public readonly int $id,
            public readonly int $amountInCents,
            public readonly string $customerName,
        ) {
        }
    }
    
    $json = '{
      "id": 1,
      "amount_in_cents": 2499,
      "customer_name": "John Doe"
    }';
    
    $mapper = new JsonMapper(
        jsonToPhpNameMapper: new SnakeCaseToCamelCaseMapper(),
        phpToJsonNameMapper: new CamelCaseToSnakeCaseMapper(),
    );
    
    $order = $mapper->map($json, Order::class);
    
    echo $order->amountInCents; // 2499
    echo $order->customerName; // 'John Doe'

brick/json-mapper 适用场景与选型建议

brick/json-mapper 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 63.91k 次下载、GitHub Stars 达 206, 最近一次更新时间为 2023 年 02 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「mapper」 「dto」 「brick」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

围绕 brick/json-mapper 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 63.91k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 206
  • 点击次数: 27
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 206
  • Watchers: 7
  • Forks: 10
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-02-15