evilfreelancer/yaml-php

一个用于导入和导出YAML配置文件的PHP库,支持验证。

0.4.1 2018-03-07 12:34 UTC

This package is auto-updated.

Last update: 2024-08-29 05:00:10 UTC


README

一个用于导入和导出YAML配置文件的PHP库,支持验证。

composer require evilfreelancer/yaml-php

为了正确工作,您需要安装PHP解释器的YAML扩展。

可用方法

  • read - 从文件或URL(自动检测)读取YAML
  • add - 添加参数数组,不替换
  • set - 添加并替换参数数组
  • validate - 使用验证模板检查内存中的参数数组
  • get - 返回准备好的参数数组
  • save - 将参数以YAML格式导出到文件系统上的文件
  • show - 以纯文本格式返回YAML

如何使用

更多示例在此

基本使用示例

<?php
require_once __DIR__ . '/../vendor/autoload.php';
use \EvilFreelancer\Yaml\Yaml;

// Object for work with YAML
$yaml = new Yaml();

// Simple array from which need build YAML
$array = [
    'string' => 'zzz',
    'integer' => 42,
    'bool' => true,
];

// Generate YAML and print to stdOut
$yaml_text = $yaml->set($array)->show();
echo $yaml_text;

输出为

---
string: zzz
integer: 42
bool: true
...

从文件读取YAML

$yaml_array = $yaml->read('example.yaml')->get();
print_r($yaml_array);

输出为

Array
(
    [string] => zzz
    [integer] => 42
    [bool] => 1
)

如何追加数组

$array = [
    'string' => 'zzz',
    'integer' => 42,
    'bool' => true,
];

$append = [
    'array_simple' => [
        'item1',
        'item2',
        'item3'
    ],
    'array_md' => [
        'string1' => 'text',
        'integer' => 42,
        'bool' => true
    ]
];

// Set array, then append additional array and show to stdOut
echo $yaml
    ->set($array)
    ->add($append)
    ->show();

输出为

---
string: zzz
integer: 42
bool: true
array_simple:
- item1
- item2
- item3
array_md:
  string1: text
  integer: 42
  bool: true
...

如何使用验证

// Schema by which we need make validation
$schema = [
    'string' => Types::STRING,
    'integer' => Types::INT,
    'bool' => Types::BOOL,
    'array_simple' => Types::ARRAY,
    'array_md' => [
        'string1' => Types::STRING,
        'integer' => Types::INT,
        'bool' => Types::BOOL
    ]
];

// Array from which we need make YAML
$array = [
    'string' => 'zzz',
    'integer' => 42,
    'bool' => true,
    'array_simple' => [
        'item1',
        'item2',
        'item3'
    ],
    'array_md' => [
        'string1' => 'text',
        'integer' => 42,
        'bool' => true
    ]
];

// Set array and execute validation procedure
echo $yaml
    ->set($array)
    ->validate($schema)
    ->show();

结果应该是YAML,如果有错误将显示详细的“堆栈跟踪”错误。

链接