hpatoio/jsg

从 JSON 模式定义生成对象,反之亦然

0.1.1 2020-01-09 09:29 UTC

This package is auto-updated.

Last update: 2024-09-17 21:51:21 UTC


README

此包允许您将 JSON Schema 表示为 PHP 对象,并将其导出为 JSON 格式,反之亦然。

Continuous Integration

codecov

用法

从模型创建 JSON

  1. 定义表示模式的模型。

    $myJsonSchema = new JsonSchema('foo', 'My schema', "Test schema description", ...[
            new OptionalObjectProperty(new TypeBoolean("top", "Is a top developer ?")),
            new RequiredObjectProperty(new TypeDate("birthdate", "Birthdate ?")),
            new OptionalObjectProperty(new TypeDateTime("interview_at", "Interview planned for ?")),
            new RequiredObjectProperty(new TypeEmail("email", "Email address ?")),
            new RequiredObjectProperty(TypeInteger::from(100, "minimum_salary", "Minimum salary ?")),
            new OptionalObjectProperty(TypeInteger::to(200, "max_days_in_office", "Max number of days in office ?")),
            new OptionalObjectProperty(new TypeObject("address", "Address", ...[
                new OptionalObjectProperty(TypeString::withMinLength("street", "Street", 0)),
                new OptionalObjectProperty(TypeString::withMinLength("city", "City", 0))
            ]))
        ]);
  2. 将对象序列化为 JSON。

    echo JsonSchemaGenerator::generate($myJsonSchema);

    结果将是类似以下 JSON 的格式:https://github.com/hpatoio/jsg/blob/develop/test/fixtures/all-types-schema.json

从 JSON 创建模型

  1. 从 JSON 生成模型
    $hydratedSchema = JsonSchemaHydrator::hydrate("/path/to/the/file.json");
  2. 访问元素
    $hydratedSchema->getProperties()['id_of_the_property'];

安装

使用以下命令在您的项目中安装此包:

composer require hpatoio/jsg

创建开发环境

  1. 克隆仓库
git clone git@github.com:hpatoio/jsg.git
cd jsg
  1. 构建镜像
docker build -t jsg .docker
  1. 运行 composer install 以获取依赖项
docker run --rm -v `pwd`:/var/jsg jsg composer install

运行测试

docker run --rm -v `pwd`:/var/jsg jsg vendor/bin/phpunit

运行突变测试

此项目使用 PHP 突变测试

要运行突变测试,请使用

docker run --rm -v `pwd`:/var/jsg jsg ./infection.phar run

应用 CS

在推送前请修复应用编码标准

docker run --rm -v `pwd`:/var/jsg jsg vendor/bin/ecs check src --no-progress-bar -vvv --fix

许可协议

此包使用 MIT 许可协议许可。