Mecha CMS

Updates.

YAML Parser

Author: Taufik Nurrohman · 135 Views

Tweet

YAML-like string parser.

To store array in YAML format or to convert YAML-like data format into array is possible with Mecha but it is limited only to key: value-based syntax to mimic array keys and their values. You can’t parse external YAML files anyway with Mecha’s internal string parser. But the YAML-like data generated by To::yaml() method basically can be treated as a valid YAML data in most cases.

Converter 

String to Array 

$test = From::yaml('foo: bar');

Related: Class From

Array to String 

$test = To::yaml(['foo' => 'bar']);

Related: Class To

Syntax 

Keys and Values 

foo: bar
baz: qux
{
  "foo": "bar",
  "baz": "qux"
}

Empty Values 

foo:
bar: ''
baz: ""
{
  "foo": [],
  "bar": "",
  "baz": ""
}

Empty Data 

[]

Comments 

# comment
test_1: foo
test_2: foo # comment
test_3: 'foo # comment' # comment
test_4: "foo # comment" # comment
test_5: # comment 'foo'
test_6: # comment "foo"
{
  "test_1": "foo",
  "test_2": "foo",
  "test_3": "foo # comment",
  "test_4": "foo # comment",
  "test_5": [],
  "test_6": []
}

Nesting 

a: b
c: d
e:
    f: g
    h: i
j: k
{
  "a": "b",
  "c": "d",
  "e": {
    "f": "g",
    "h": "i"
  },
  "j": "k"
}

Sequential Arrays 

Arrays with numeric keys.

Manual 
0: a
1: b
2: c
["a", "b", "c"]
Automatic 
- a
- b
- c
["a", "b", "c"]

No Keys 

List of data without keys will be converted into key: key.

a
b
c
{
  "a": "a",
  "b": "b",
  "c": "c"
}

Data Types 

All data types will be converted automatically by the e.

string: a
integer: 1
float: 1.5
boolean: true
null: null
JSON: {"foo":"bar","baz":"qux","string_integer":"1","string_boolean":"false"}
string_integer: "1"
string_float: "1.5"
string_boolean: "true"
string_null: "null"
single_quote: 'foo\nbar'
double_quote: "foo\nbar"
{
  "string": "a",
  "integer": 1,
  "float": 1.5,
  "boolean": true,
  "null": null,
  "JSON": {
    "foo": "bar",
    "baz": "qux",
    "string_integer": "1",
    "string_boolean": "false"
  },
  "string_integer": "1",
  "string_float": "1.5",
  "string_boolean": "true",
  "string_null": "null",
  "single_quote": "foo\\nbar",
  "double_quote": "foo\nbar"
}
[
    'string' => 'a',
    'integer' => 1,
    'float' => 1.5,
    'boolean' => true,
    'null' => null,
    'JSON' => [
        'foo' => 'bar',
        'baz' => 'qux',
        'integer' => 1,
        'boolean' => false
    ],
    'string_integer' => '1',
    'string_float' => '1.5',
    'string_boolean' => 'true',
    'string_null' => 'null',
    'single_quote' => 'foo\nbar',
    'double_quote' => 'foo
bar'
]

Escaping 

foo\: bar: baz
foo: bar: baz
{
  "foo: bar": "baz",
  "foo": "bar: baz"
}
"foo: bar": baz
foo: bar: baz
{
  "foo: bar": "baz",
  "foo": "bar: baz"
}
'foo: bar': baz
foo: bar: baz
{
  "foo: bar": "baz",
  "foo": "bar: baz"
}

Compact Array 

Still experimental.

foo: [bar, baz, 0, true]
{
  "foo": ["bar", "baz", 0, true]
}

0001000000

0 Comments

No comments yet.