OJD Commit: Fix node id reset
[eidogo-ojd.git] / php / sgf.php
blob2259b8a24dc2d12d0da0947d8c0af7f848848e9f
1 <?php
3 // Quick and dirty SGF parser.
5 class SGF {
6 var $sgf, $index, $root;
7 function SGF($sgf) {
8 $this->sgf = $sgf;
9 $this->index = 0;
10 $this->tree = $this->parseTree(null);
12 function parseTree($parent) {
13 $tree = array();
14 $tree['nodes'] = array();
15 $tree['trees'] = array();
16 while ($this->index < strlen($this->sgf)) {
17 $char = $this->sgf[$this->index];
18 $this->index++;
19 switch ($char) {
20 case ';':
21 $node = $this->parseNode();
22 //if (is_null($tree['nodes'])) $tree['nodes'] = array();
23 array_push($tree['nodes'], $node);
24 break;
25 case '(':
26 //if (is_null($tree['trees'])) $tree['trees'] = array();
27 array_push($tree['trees'], $this->parseTree($tree));
28 break;
29 case ')':
30 return $tree;
31 break;
34 return $tree;
36 function parseNode() {
37 $node = array();
38 $key = "";
39 $values = array();
40 $i = 0;
41 while ($this->index < strlen($this->sgf)) {
42 $char = $this->sgf[$this->index];
43 if ($char == ';' || $char == '(' || $char == ')')
44 break;
45 if ($char == '[') {
46 while ($this->sgf[$this->index] == '[') {
47 $this->index++;
48 while ($this->sgf[$this->index] != ']' && $this->index < strlen($this->sgf)) {
49 if ($this->sgf[$this->index] == '\\')
50 $this->index++;
51 $values[$i] .= $this->sgf[$this->index];
52 $this->index++;
54 $i++;
55 while ($this->sgf[$this->index] == ']' || $this->sgf[$this->index] == '\r' || $this->sgf[$this->index] == 'n')
56 $this->index++;
58 $node[$key] = count($values) > 1 ? $values : $values[0];
59 $key = "";
60 $values = array();
61 $i = 0;
62 continue;
64 if ($char != " " && $char != "\n" && $char != "\r" && $char != "\t")
65 $key .= $char;
66 $this->index++;
68 return $node;