smoren/schemator

原理图数据转换器

v2.4.1 2023-11-16 14:08 UTC

README

Packagist PHP Version Support Scrutinizer Code Quality Coverage Status Build and test License: MIT

Schemator logo

原理图数据映射器是一个工具,用于根据给定的转换方案将嵌套数据结构(任何关联数组、非关联数组和对象的组合)进行转换。

如何将安装到您的项目中

composer require smoren/schemator

用法

简单用法

use Smoren\Schemator\Factories\SchematorFactory;

$input = [
    'id' => 100,
    'name' => 'Oxford',
    'country' => [
        'id' => 10,
        'name' => 'UK',
        'neighbours' => ['Ireland', 'Sweden', 'France'],
        'capitals' => [
            'lnd' => 'London',
            'edb' => 'Edinburgh',
        ],
    ],
    'streets' => [
        [
            'id' => 1000,
            'name' => 'Woodstock Rd',
            'houses' => [1, 5, 9],
        ],
        [
            'id' => 1002,
            'name' => 'Banbury Rd',
            'houses' => [22, 35, 49],
        ],
        [
            'id' => 1003,
            'name' => 'Beamont St',
            'houses' => [11, 12, 15],
        ],
    ],
    'lnd_path' => 'country.capitals.lnd',
];

$schema = [
    'city_id' => 'id',
    'city_name' => 'name',
    'city_street_names' => 'streets.*.name',
    'country_id' => 'country.id',
    'country_name' => 'country.name',
    'country_neighbours' => 'country.neighbours',
    'country_neighbour' => 'country.neighbours',
    'country_first_capital' => 'country.capitals.lnd',
    'country_second_capital' => 'country.capitals.edb',
    'country_data.country_id' => 'country.id',
    'country_data.country_name' => 'country.name',
];

$schemator = SchematorFactory::create();
$output = $schemator->convert($input, $schema);

print_r($output);
/* Array
(
    [city_id] => 100
    [city_name] => Oxford
    [city_street_names] => Array
        (
            [0] => Woodstock Rd
            [1] => Banbury Rd
            [2] => Beamont St
        )

    [country_id] => 10
    [country_name] => UK
    [country_neighbours] => Array
        (
            [0] => Ireland
            [1] => Sweden
            [2] => France
        )

    [country_neighbour] => Array
        (
            [0] => Ireland
            [1] => Sweden
            [2] => France
        )

    [country_first_capital] => London
    [country_second_capital] => Edinburgh
    [country_data] => Array
        (
            [country_id] => 10
            [country_name] => UK
        )

)
*/

设置错误级别

use Smoren\Schemator\Factories\SchematorFactory;
use Smoren\Schemator\Structs\ErrorsLevelMask;
use Smoren\Schemator\Exceptions\SchematorException;

$input = [
    'some_key' => null,
];
$schema = [
    'my_value' => ['some_key', ['date', 'Y-m-d']],
];

$schemator = SchematorFactory::createBuilder()
    ->withErrorsLevelMask(
        ErrorsLevelMask::nothing()
            ->add([SchematorException::FILTER_ERROR, SchematorException::CANNOT_GET_VALUE])
    )
    ->get();

try {
    $schemator->convert($input, $schema);
} catch(SchematorException $e) {
    echo $e->getMessage(); // filter error: 'date'
}

使用基本过滤器

use Smoren\Schemator\Factories\SchematorFactory;
use Smoren\Schemator\Filters\BaseFiltersStorage;

$input = [
    'id' => 100,
    'name' => 'Oxford',
    'country' => [
        'id' => 10,
        'name' => 'UK',
        'neighbours' => ['Ireland', 'Sweden', 'France'],
        'capitals' => [
            'lnd' => 'London',
            'edb' => 'Edinburgh',
        ],
    ],
    'streets' => [
        [
            'id' => 1000,
            'name' => 'Woodstock Rd',
            'houses' => [1, 5, 9],
        ],
        [
            'id' => 1002,
            'name' => 'Banbury Rd',
            'houses' => [22, 35, 49],
        ],
        [
            'id' => 1003,
            'name' => 'Beamont St',
            'houses' => [11, 12, 15],
        ],
    ],
    'lnd_path' => 'country.capitals.lnd',
];

$schema = [
    'city_street_names.all' => ['streets.*.name', ['implode', ', ']],
    'city_street_names.sorted' => ['streets.*.name', ['sort'], ['implode', ', ']],
    'city_street_names.filtered' => ['streets.*.name', ['filter', fn (string $candidate) => strpos($candidate, 'Ban') !== false]],
    'lnd' => ['lnd_path', ['path']],
    'city_street_houses' => ['streets.*.houses', ['flatten']],
];

$schemator = SchematorFactory::create();
$output = $schemator->convert($input, $schema);

print_r($output);
/*
Array
(
    [city_street_names] => Array
        (
            [all] => Woodstock Rd, Banbury Rd, Beamont St
            [sorted] => Banbury Rd, Beamont St, Woodstock Rd
            [filtered] => Array
                (
                    [0] => Banbury Rd
                )

        )

    [lnd] => London
    [city_street_houses] => Array
        (
            [0] => 1
            [1] => 5
            [2] => 9
            [3] => 22
            [4] => 35
            [5] => 49
            [6] => 11
            [7] => 12
            [8] => 15
        )

)
*/

使用智能过滤和替换

use Smoren\Schemator\Factories\SchematorFactory;
use Smoren\Schemator\Filters\BaseFiltersStorage;

$schemator = SchematorFactory::create();
$input = [
    'numbers' => [-1, 10, 5, 22, -10, 0, 35, 7, 8, 9, 0],
];

$output = $schemator->convert($input, [
    'positive' => [
        'numbers',
        ['filter', [['>', 0]]],
        ['sort'],
    ],
    'negative' => [
        'numbers',
        ['filter', [['<', 0]]],
        ['sort'],
    ],
    'complicated' => [
        'numbers',
        ['filter', [['>=', 8], ['<', 0]]],
        ['filter', [['<', 22]]],
        ['sort'],
    ],
]);

print_r($output);
/*
Array
(
    [positive] => Array
        (
            [0] => 5
            [1] => 7
            [2] => 8
            [3] => 9
            [4] => 10
            [5] => 22
            [6] => 35
        )

    [negative] => Array
        (
            [0] => -10
            [1] => -1
        )

    [complicated] => Array
        (
            [0] => -10
            [1] => -1
            [2] => 8
            [3] => 9
            [4] => 10
        )

)
*/

$output = $schemator->convert($input, [
    'number_types' => ['numbers', [
        'replace',
        [
            ['=0', '=', 0],
            ['>9', '>', 9],
            ['<0', '<', 0],
            ['1-8', 'between', 1, 8],
        ]
    ]]
]);

print_r($output);
/*
Array
(
    [number_types] => Array
        (
            [0] => <0
            [1] => >9
            [2] => 1-8
            [3] => >9
            [4] => <0
            [5] => =0
            [6] => >9
            [7] => 1-8
            [8] => 1-8
            [9] => 9
            [10] => =0
        )

)
*/

使用自定义过滤器

use Smoren\Schemator\Factories\SchematorFactory;
use Smoren\Schemator\Interfaces\FilterContextInterface;

$schemator = SchematorFactory::createBuilder()
    ->withFilters([
        'startsWith' => function (FilterContextInterface $context, string $start) {
            return array_filter($context->getSource(), function (string $candidate) use ($start) {
                return strpos($candidate, $start) === 0;
            });
        },
    ])
    ->get();

$input = [
    'streets' => ['Woodstock Rd', 'Banbury Rd', 'Beamont St'],
];

$schema = [
    'street_names' => ['streets', ['startsWith', 'T'], ['implode', ', ']],
];

$output = $schemator->convert($input, $schema);

print_r($output);
/*
Array
(
    [street_names] => Woodstock Rd, Beamont St
)
*/

大量使用

use Smoren\Schemator\Factories\SchematorFactory;

$massSchemator = SchematorFactory::createMass();

$cities = [
    [
        'id' => 100,
        'name' => 'London',
        'country' => [
            'id' => 10,
            'name' => 'UK',
        ],
        'streets' => [
            [
                'id' => 1001,
                'name' => 'The Mall',
            ],
            [
                'id' => 1002,
                'name' => 'Carnaby Street',
            ],
        ],
    ],
    [
        'id' => 101,
        'name' => 'Oxford',
        'country' => [
            'id' => 10,
            'name' => 'UK',
        ],
        'streets' => [
            [
                'id' => 1003,
                'name' => 'Turl Street',
            ],
            [
                'id' => 1004,
                'name' => 'Holywell Street',
            ],
        ],
    ],
];

$schema = [
    'city_id' => 'id',
    'city_name' => 'name',
    'city_street_names' => 'streets.*.name',
    'country_id' => 'country.id',
    'country_name' => 'country.name',
];

$gen = $massSchemator->generate($cities, $schema);

$result = [];
foreach($gen as $item) {
    $result[] = $item;
}

print_r($result);
/*
Array
(
    [0] => Array
        (
            [city_id] => 100
            [city_name] => London
            [city_street_names] => Array
                (
                    [0] => The Mall
                    [1] => Carnaby Street
                )

            [country_id] => 10
            [country_name] => UK
        )
    [1] => Array
        (
            [city_id] => 101
            [city_name] => Oxford
            [city_street_names] => Array
                (
                    [0] => Turl Street
                    [1] => Holywell Street
                )

            [country_id] => 10
            [country_name] => UK
        )
)
*/

过滤器

const

设置从 const 参数的值。

Schema

["value" => [["const", "My const value"]]]

结果

["value" => "My const value"]

sum

返回给定数组的总和。

给定

["numbers" => [1, 2, 3, 4, 5]]

Schema

["value" => ["numbers", ["sum"]]]

结果

["value" => 15]

average

返回给定数组的平均值。

给定

["numbers" => [1, 2, 3, 4, 5]]

Schema

["value" => ["numbers", ["average"]]]

结果

["value" => 3]

date

返回从给定的 Unix 时间戳格式化的日期。

参数

  1. 日期格式
  2. GMT 时间偏移量
    • 可选
    • 数据类型 — 整数
    • 默认 — 0

给定

["some_date" => 1651481881]

Schema

["value" => ["some_date", ["date", "d.m.Y H:i:s", 3]]]

结果

["value" => "02.05.2022 11:58:01"]

implode

返回使用从参数列表中的分隔符连接给定数组项的字符串。

参数

  1. 分隔符
    • 必需
    • 数据类型 — 字符串
    • 示例: ;

给定

["numbers" => [1, 2, 3, 4, 5]]

Schema

["value" => ["numbers", ["implode", "; "]]]

结果

["value" => "1; 2; 3; 4; 5"]

explode

返回使用从参数列表中的分隔符拆分给定字符串的字符串数组

参数

  1. 分隔符
    • 必需
    • 数据类型 — 字符串
    • 示例: ;

给定

["numbers" => "1; 2; 3; 4; 5"]

Schema

["value" => ["numbers", ["explode", "; "]]]

结果

["value" => ["1", "2", "3", "4", "5"]]

flatten

返回包含所有树数组末端的叶子节点的扁平数组。

给定

[
   "numbers" => [
      [
         [1, 2, 3],
         [4, 5, 6]
      ],
      [7, 8, 9]
   ],
]

Schema

["value" => ["numbers", ["flatten"]]]

结果

["value" => [1, 2, 3, 4, 5, 6, 7, 8, 9]]

sort

排序并返回给定的数组。

给定

["numbers" => [3, 5, 4, 1, 2]]

Schema

["value" => ["numbers", ["sort"]]]

结果

["value" => [1, 2, 3, 4, 5]]

rsort

逆序排序并返回给定的数组。

给定

["numbers" => [3, 5, 4, 1, 2]]

Schema

["value" => ["numbers", ["sort"]]]

结果

["value" => [5, 4, 3, 2, 1]]

filter

返回包含与参数列表中的谓词匹配的给定数组元素的数组。

规则

  • 每个谓词都具有以下格式 ["predicate name", ...parans]
  • 一个过滤器中的谓词按“或”逻辑应用。
  • 要应用“与”逻辑,请使用 过滤器链
  • 可用的谓词
    • ["=", 10] 表示 value = 10
    • [">", 10] 表示 value > 10
    • [">=", 10] 表示 value >= 10
    • ["<", 10] 表示 value < 10
    • ["<=", 10] 表示 value <= 10
    • ["in", [1, 2]] 表示 value = 1 OR value = 2
    • ["not in", [1, 2]] 表示 value != 1 AND value != 2
    • ["between", 1, 5] 表示 1 <= value <= 5
    • ["between strict", 1, 5] 表示 1 < value < 5

给定

["numbers" => [-5, -3, -1, 1, 3, 5]]

Schema

[
   "value" => [
      "numbers",
      [
         "filter",
         [[">", 1], ["<", -1]] // value > 1 OR value < -1
      ],
   ],
]

结果

["value" => [-5, -3, 3, 5]]

replace

返回根据参数列表中的规则替换值的元素数组。

规则

  • 每个规则具有以下格式 ["value to replace", "rule name", ...params]
  • 一个过滤器中的规则按“或”逻辑应用。
  • 要应用“与”逻辑,请使用 过滤器链
  • 可用的规则
    • ["=", 10] 表示 value = 10
    • [">", 10] 表示 value > 10
    • [">=", 10] 表示 value >= 10
    • ["<", 10] 表示 value < 10
    • ["<=", 10] 表示 value <= 10
    • ["in", [1, 2]] 表示 value = 1 или value = 2
    • ["not in", [1, 2]] 表示 value != 1 и value != 2
    • ["between", 1, 5] 表示 1 <= value <= 5
    • ["between strict", 1, 5] 表示 1 < value < 5
    • ["else"] — 对于值没有匹配的规则 (如果未使用规则 else,则默认将这些值替换为 null)

给定

["numbers" => [-5, -3, -1, 0, 1, 3, 5]]

Schema

[
   "value" => [
      "numbers",
      [
         "replace",
         [
            ["positive", ">", 0],
            ["negative", "<", 0],
            ["zero", "else"]
         ],
      ],
   ],
]

结果

["value" => ["negative", "negative", "negative", "zero", "positive", "positive", "positive"]]

过滤器链

给定

["numbers" => [-5, -3, -1, 1, 3, 5]]

Schema

[
   "value" => [
      "numbers",
      [
         "filter",
         [[">", 1], ["<", -1]] // (value > 1 OR value < -1)
      ],
      // AND
      [
         "filter",
         [[">=", -3]] // value >= -3
      ],
   ],
]

结果

["value" => [-3, 3, 5]]

单元测试

composer install
composer test-init
composer test

标准

Schemator 符合以下标准

许可证

Schemator 遵循 MIT 许可证。