slifin / edn

可扩展数据表示法解析器。

维护者

详细信息

github.com/slifin/edn

源代码

1.0 2020-02-13 13:45 UTC

This package is auto-updated.

Last update: 2024-09-14 00:06:59 UTC


README

用于解析 edn 格式的解析器。用 PHP 编写。

解析器内部依赖于 Phlexy 进行词法分析。

用法

解析

要解析 edn,只需使用 parse 函数

$edn = file_get_contents('examples/sample.edn');
$data = igorw\edn\parse($edn);

print_r($data);

您还可以定义自定义标签处理程序,并将它们作为第二个参数传递给 parse

use igorw\edn;

class Person {
    public $firstName;
    public $lastName;

    function __construct($firstName, $lastName) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }
}

$edn = '#myapp/Person {:first "Fred" :last "Mertz"}';

$data = edn\parse($edn, [
    'myapp/Person' => function ($node) {
        return new Person(
            $node[edn\keyword('first')],
            $node[edn\keyword('last')]
        );
    },
]);

// [new Person('Fred', 'Mertz')]

编码

如果您想要将内存中的数据结构编码为 edn,可以使用 encode 函数

use igorw\edn;

$person = new edn\Map();
$person[edn\keyword('name')] = 'igorw';

$list = new edn\LinkedList([
    edn\symbol('foo'),
    edn\symbol('bar'),
    edn\symbol('baz'),
    edn\keyword('qux'),
    1.0,
    $person,
]);

$edn = edn\encode([$list]);
// (foo bar baz :qux 1.0 {:name "igorw"})

测试

此库针对 shaunxcode/edn-tests 套件进行测试。