f3ebebafd8035ea95ce2b2a24fba4ab7308bd0f0
[auerswald-callnotifier.git] / src / callnotifier / EDSS1 / Parser.php
1 <?php
2 namespace callnotifier;
3
4 class EDSS1_Parser
5 {
6     const PARAM = 0;
7     const PARAMLENGTH = 1;
8     const PARAMVAL = 2;
9
10     public function parse($bytes)
11     {
12         $m = new EDSS1_Message();
13         $m->sapi = ord($bytes{0}) >> 2;
14         $m->callResponse = (int) ((ord($bytes{0}) & 2) == 2);
15         $m->tei  = ord($bytes{1}) >> 1;
16
17         $curpos = 4;
18         list($curpos, $cCallRef, $crLen) = $this->readLengthData($bytes, ++$curpos);
19         if ($crLen == 0xFF) {
20             return $m;
21         }
22         $m->callRefType = ord($cCallRef{0}) >> 7;
23         $nCallRef = ord($cCallRef{0}) & 127;
24         if ($crLen > 1) {
25             $nCallRef = ord($cCallRef{1}) + ($nCallRef << 8);
26             if ($crLen > 2) {
27                 $nCallRef = ord($cCallRef{2}) + ($nCallRef << 8);
28             }
29         }
30         $m->callRef = $nCallRef;
31         //var_dump($curpos, dechex($m->callRef));
32         $m->type = ord($bytes{++$curpos});
33
34         $complete = false;
35         do {
36             //parameter type
37             $curbit = $bytes{++$curpos};
38             if ($curbit == "\xFF" && $bytes{$curpos + 1} == "\n") {
39                 $complete = true;
40                 break;
41             }
42
43             $paramType = ord($curbit);
44             $param = $this->getParameterByType($paramType);
45             $m->parameters[] = $param;
46
47             //parameter length
48             $curbit = $bytes{++$curpos};
49             $param->length = ord($curbit);
50
51             //parameter data
52             $param->setData(substr($bytes, $curpos + 1, $param->length));
53             $curpos += $param->length;
54         } while ($curpos < strlen($bytes) - 1);
55
56         return $m;
57     }
58
59     /**
60      * Read a datablock preceded with a length byte.
61      *
62      * @return array Array with new cursor position, data and data length
63      */
64     public function readLengthData($bytes, $curpos)
65     {
66         //var_dump('old' . $curpos);
67         $length = ord($bytes{$curpos});
68         if ($length != 0xFF) {
69             $data = substr($bytes, $curpos + 1, $length);
70         } else {
71             $data = null;
72         }
73         return array($curpos + $length, $data, $length);
74     }
75
76     /**
77      * @param integer $type Parameter type ID
78      */
79     public function getParameterByType($type)
80     {
81         $supported = array(0x28, 0x2C, 0x4C, 0x6C, 0x70);
82         if (!in_array($type, $supported)) {
83             return new EDSS1_Parameter($type);
84         }
85
86         $typeHex = sprintf('%02X', $type);
87         $class = 'callnotifier\EDSS1_Parameter_' . $typeHex;
88
89         return new $class($type);
90     }
91 }
92
93 ?>