Toml   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 56
rs 10
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B serialize() 0 43 9
A type() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Rarst\Hugo\wprss2hugo\Serializer;
5
6
use Yosymfony\Toml\TomlBuilder;
7
8
/**
9
 * TOML serializer.
10
 */
11
class Toml implements Data
12
{
13
    /**
14
     * Process an array input into a TOML string.
15
     */
16
    public function serialize(array $input): string
17
    {
18
        $builder = new TomlBuilder();
19
20
        $tables = [];
21
22
        // TOML doesn't support root data array so we add dummy `data` key.
23
        if (is_numeric(array_key_first($input))) {
24
25
            foreach ($input as $item) {
26
27
                $builder->addArrayOfTable('data');
28
29
                foreach ($item as $key => $value) {
30
                    $builder->addValue($key, $value);
31
                }
32
            }
33
34
            return $builder->getTomlString();
35
        }
36
37
        foreach ($input as $key => $value) {
38
39
            // Associative arrays map to TOML tables and shouldn't be mixed between regular values.
40
            if (is_array($value) && !is_numeric(array_key_first($value))) {
41
                $tables[$key] = $value;
42
                continue;
43
            }
44
45
            $builder->addValue((string)$key, $value);
46
        }
47
48
        foreach ($tables as $name => $items) {
49
50
            $builder->addTable($name);
51
52
            foreach ($items as $itemKey => $itemValue) {
53
                $builder->addValue((string)$itemKey, $itemValue);
54
            }
55
56
        }
57
58
        return $builder->getTomlString();
59
    }
60
61
    /**
62
     * TOML file type.
63
     */
64
    public function type(): string
65
    {
66
        return 'toml';
67
    }
68
}
69