-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyValueParser.php
66 lines (51 loc) · 1.71 KB
/
KeyValueParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
class KeyValueParser {
private $file;
private $result;
const COMMA = ',';
const L_BKT = '{';
const R_BKT = '}';
const COLON = ':';
const QUOTE = '"';
public function __construct() {}
public function load ($file) {
$this->file = file($file);
}
public function parse () {
$result = [];
$fileCount = count($this->file);
for ($i = 0; $i < $fileCount; $i++) {
$exploded = explode(static::QUOTE, trim($this->file[$i]));
$count = count($exploded);
if($count === 1) { // } or {
$bkt = $exploded[0];
$result[] = $bkt;
if($bkt === static::R_BKT && $fileCount > $i + 1) {
$next = $this->file[$i + 1];
$next = trim($next);
if($next !== static::R_BKT) {
$result[] = static::COMMA;
}
}
}
else if($count === 3) { // key of object
$result[] = static::QUOTE . $exploded[1] . static::QUOTE . static::COLON;
}
else if($count === 5) { // key - value
$result[] = static::QUOTE . $exploded[1] . static::QUOTE . static::COLON;
$result[] = static::QUOTE . $exploded[3] . static::QUOTE;
if($fileCount > $i + 1) {
$next = $this->file[$i + 1];
$next = trim($next);
if($next !== static::R_BKT) {
$result[] = static::COMMA;
}
}
}
}
$this->result = static::L_BKT . implode('', $result) . static::R_BKT;
}
public function toObj () {
return json_decode($this->result);
}
}