Passed
Push — master ( 7e7ce9...effeb7 )
by stéphane
02:19
created

Dumper::dump()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
dl 0
loc 11
ccs 10
cts 10
cp 1
rs 9.9666
c 1
b 0
f 0
cc 2
nc 1
nop 4
crap 2
1
<?php
2
3
namespace Dallgoot\Yaml;
4
5
use Dallgoot\Yaml\Types\YamlObject;
6
7
/**
8
 *  Convert PHP datatypes to a YAML string syntax
9
 *
10
 * @author  Stéphane Rebai <[email protected]>
11
 * @license Apache 2.0
12
 * @link    https://github.com/dallgoot/yaml
13
 */
14
class Dumper
15
{
16
    public const INDENT = 2;
17
    private const OPTIONS = 0b00000;
18
    public const DATE_FORMAT = 'Y-m-d';
19
20
    public $options;
21
    //options
22
    public const EXPAND_SHORT = 0b00001;
23
    public const SERIALIZE_CUSTOM_OBJECTS = 0b00010;
24
    public const USE_TILDE_AS_NULL = 0b00100;
25
26
    public int $floatPrecision = 4;
27
28
    private bool $multipleDocs = false;
29
30
    public bool $_compactMode = false;
31
32
    private DumperHandlers $handler;
33
34
    public const KEY_MASK_SEQ = '- %s';
35
    public const KEY_MASK_MAP = '%s: %s';
36
37 5
    public function __construct($options = null)
38
    {
39 5
        $this->options = is_int($options) ? $options : self::OPTIONS;
40 5
        $this->handler = new DumperHandlers($this);
41
    }
42
    /**
43
     * Returns (as a string) the YAML representation of the $dataType provided
44
     *
45
     * @param mixed    $dataType The data type
46
     *
47
     * @throws \Exception datatype cannot be null
48
     *
49
     * @return string The Yaml string content
50
     */
51 2
    public function toString($dataType, ?int $options = null): string
52
    {
53 2
        if (empty($dataType)) throw new \Exception(self::class . ": No content to convert to Yaml");
54 2
        if (is_scalar($dataType)) {
55 1
            return "--- " . $this->handler->dumpScalar($dataType) . PHP_EOL;
56
        }
57 2
        return $this->dump($dataType, 0, false, true);
58
    }
59
60
    /**
61
     * Calls and saves the result of Dumper::toString to the file $filePath provided
62
     *
63
     * @param mixed    $dataType The data type
64
     *
65
     * @throws \Exception datatype cannot be null
66
     *
67
     * @return bool true = if the file has been correctly saved  ( return value from 'file_put_contents')
68
     */
69 1
    public function toFile(string $filePath, $dataType, ?int $options = null): bool
70
    {
71 1
        return !is_bool(file_put_contents($filePath, $this->toString($dataType, $options)));
72
    }
73
74
75
76 4
    public function dump(mixed $dataType, int $indent, bool $isCompact = false, $isRoot = false): string
77
    {
78 4
        return match(true) {
79 4
            $dataType instanceof YamlObject => $this->dumpYamlObject($dataType),
80 4
            is_null($dataType) => $this->options & self::USE_TILDE_AS_NULL ? '~' : '',
81 4
            is_scalar($dataType) => $this->handler->dumpScalar($dataType),
82 4
            is_array($dataType) => $this->handler->dumpArray($dataType, $indent, $isCompact, $isRoot),
83 4
            is_object($dataType) => $this->handler->dumpObject($dataType, $indent, $isCompact, $isRoot),
84 4
            is_resource($dataType) => get_resource_type($dataType),
85 4
            is_callable($dataType, false, $callable_name) => $callable_name,
86 4
            default => '[Unknown Type]',
87 4
        };
88
    }
89
90
91
    public function dumpMultiDoc(array $arrayOfYamlObject): string
92
    {
93
        $docs = [];
94
        foreach ($arrayOfYamlObject as $yamlObject) {
95
            $docs[] = $this->dumpYamlObject($yamlObject);
96
        }
97
        return "---\n" . implode("\n---\n", $docs);
98
    }
99
100
    /**
101
     * Dumps an yaml object to a YAML string
102
     *
103
     * @todo  export comment from YamlObject
104
     */
105 1
    public function dumpYamlObject(YamlObject $obj): string
106
    {
107 1
        if ($this->multipleDocs || $obj->hasDocStart() || $obj->isTagged()) {
108
            $this->multipleDocs = true;
109
            // && $this->$result instanceof DLL) $this->$result->push("---");
110
        }
111
        // $this->insertComments($obj->getComment());
112 1
        if (count(get_object_vars($obj)) === 0) {
113 1
            return $this->handler->dumpArray($obj->getArrayCopy(), 0, false, true);
114
        }else {
115 1
            return $this->handler->dumpObject($obj, 0, false, true);
116
        }
117
    }
118
119
120
    // public function iteratorToString(
121
    //     $compound,
122
    //     string $keyMask,
123
    //     string $itemSeparator,
124
    //     int $indent,
125
    //     bool $compact = false
126
    // ): string {
127
    //     $pairs = [];
128
    //     $valueIndent = $indent + self::INDENT;
129
    //     if(is_object($compound)) {
130
    //         $compound = get_object_vars($compound);
131
    //     }
132
    //     foreach ($compound as $key => $value) {
133
    //         $separator = "\n";
134
    //         if (is_scalar($value) || $value instanceof \DateTime) {
135
    //             $separator   = ' ';
136
    //             $valueIndent = 0;
137
    //         }
138
    //         if ($compact) {
139
    //             $pairs[] = sprintf($keyMask, $key) . $this->dump($value, $valueIndent);
140
    //         } else {
141
    //             $pairs[] = str_repeat(' ', $indent) . sprintf($keyMask, $key) . $separator . $this->dump($value, $valueIndent);
142
    //         }
143
    //     }
144
    //     return implode($itemSeparator, $pairs);
145
    // }
146
}
147