pilov-pa/class-from-json

此包用于根据json结构生成类代码

v0.1.1 2022-04-12 22:01 UTC

This package is auto-updated.

Last update: 2024-09-13 03:22:01 UTC


README

此包用于根据json生成类代码。

基本用法

$generator = new \PilovPa\ClassFromJson\ClassMapGenerator();
$renderer = new \PilovPa\ClassFromJson\ClassRenderer('8.1');
$classMap = $generator->generate('Some\Root\Ns', $someJson);

foreach ($classMap as $cls) {
    $classTemplate = $renderer->renderClass($cls);
    file_put_contents(__DIR__ . '/Some/Root/Ns/' . $cls->getName() . '.php', $classTemplate);
}

示例

您可以使用任何json生成类文件。例如

{
    "booleanField": true,
    "stringField": "some string",
    "objectField": {
        "intField": 123,
        "nullField": null
    }
}

将被转换为几个文件

<?php

declare(strict_types=1);

namespace Some\Root\Ns;

class RootClass
{
    private bool $booleanField;
    private string $stringField;
    private ObjectField $objectField;

    public function getBooleanField(): bool
    {
        return $this->booleanField;
    }

    public function setBooleanField(bool $booleanField): RootClass
    {
        $this->booleanField = $booleanField;
        return $this;
    }

    public function getStringField(): string
    {
        return $this->stringField;
    }

    public function setStringField(string $stringField): RootClass
    {
        $this->stringField = $stringField;
        return $this;
    }

    public function getObjectField(): ObjectField
    {
        return $this->objectField;
    }

    public function setObjectField(ObjectField $objectField): RootClass
    {
        $this->objectField = $objectField;
        return $this;
    }
}

<?php

declare(strict_types=1);

namespace Some\Root\Ns;

class ObjectField
{
    private int $intField;
    private mixed $nullField;

    public function getIntField(): int
    {
        return $this->intField;
    }

    public function setIntField(int $intField): RootClass
    {
        $this->intField = $intField;
        return $this;
    }

    public function getNullField(): mixed
    {
        return $this->nullField;
    }

    public function setNullField(mixed $nullField): RootClass
    {
        $this->nullField = $nullField;
        return $this;
    }
}

生成的属性

在生成的类中,每个属性都将有private修饰符、getter和流畅的setter。

属性名称

类的属性名称由json字段名称生成。下划线名称将转换为camelCase。

属性类型

类的属性类型由json字段值类型生成。支持以下json类型

在json结构的不同位置有相同名称和不同结构的两个json字段将转换为两个不同的类。