carc1n0gen/phrontmatter

v1.0.0 2016-05-09 19:29 UTC

This package is not auto-updated.

Last update: 2024-09-20 01:23:17 UTC


README

一个用于解析具有前文的文档的PHP库。

默认情况下,文档以Markdown格式解析,前文以"---"开头和结尾,例如Jekyll

安装

$ composer require carc1n0gen/phrontmatter

示例

use \Carc1n0gen\PhrontMatter\Parser;

// Create a Parser instance with default options.
$parser = new Parser();

$document = $parser->parse(file_get_contents('path/to/markdown/file'));

// If the front matter contaned:
// ---
// author:
//   firstName: John
//   lastName: Smith
// ---
print_r($document->getFrontMatter());

// Returns:
// Array
// (
//     [author] => Array
//         (
//             [firstName] => John
//             [lastName] => Smith
//         )
// 
// )

可以使用$document->getContent()访问解析后的文档内容。

如果希望保留文档内容而不进行解析,可以将false作为$parser->parse的第二个参数提供。例如,如果文档内容是HTML格式且不需要解析。

不同的前文格式

PhrontMatter允许您以您喜欢的任何格式编写前文,并内置了YAML和JSON的适配器。因此,您也可以用JSON编写前文。

JSON前文

use \Carc1n0gen\PhrontMatter\Parser;
use \Carc1n0gen\PhrontMatter\Adapter\JSONAdapter;

// Create in instance of the JSON parser adapter.
$adapter = new JSONAdapter();

// Create a Parser instance with a custom front matter adapter.
$parser = new Parser($adapter);

$document = $parser->parse(file_get_contents('path/to/markdown/file'));

// If the front matter contaned:
// ---
// {
//     "author": {
//         "firstName": "John",
//         "lastName": "Smith"
//     }
// }
// ---
print_r($document->getFrontMatter());

// Returns:
// stdClass Object
// (
//     [author] => stdClass Object
//         (
//             [firstName] => John
//             [lastName] => Smith
//         )
// 
// )

自定义解析器适配器

解析器的构造函数签名是

public function __construct(ParserInterface $frontMatterParser = null,
                            ParserInterface $contentParser = null,
                            $startSep = '---',
                            $endSep = '---')

如果您想使用YAML或JSON之外的格式,可以提供自己的前文解析器适配器。如果您想以Markdown以外的格式编写文档内容,可以提供自己的内容解析器适配器。您还可以为文档的前文部分提供自定义的开始/结束分隔符。

在编写自定义解析器适配器时,只需满足\Carc1n0gen\PhrontMatter\ParserInterface接口即可。