Add php protobuffer support for transition to GTFS-realtime
[busui.git] / lib / Protobuf-PHP / library / DrSlump / Protobuf / Compiler / JsonGenerator.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
<?php
 
namespace DrSlump\Protobuf\Compiler;
 
use DrSlump\Protobuf;
use google\protobuf as proto;
 
class JsonGenerator extends AbstractGenerator
{
    public function getNamespace(proto\FileDescriptorProto $proto)
    {
        $namespace = $proto->getPackage();
        $opts = $proto->getOptions();
        if (isset($opts['json.package'])) {
            $namespace = $opts['jsonpackage'];
        }
        if (isset($opts['json.namespace'])) {
            $namespace = $opts['json.namespace'];
        }
 
        $namespace = trim($namespace, '.');
        return $namespace;
    }
 
    public function compileEnum(proto\EnumDescriptorProto $enum, $namespace)
    {
        $s[]= "$namespace.$enum->name = {";
        $lines = array();
        foreach ($enum->getValueList() as $value) {
            $lines[] = "  /** @const */ $value->name: $value->number";
        }
        $s[]= implode(",\n", $lines);
        $s[]= '};';
        $s[]= '';
        return implode("\n", $s);
    }
 
    public function compileExtension(proto\FieldDescriptorProto $field, $ns, $indent)
    {
        $extendee = $this->normalizeReference($field->getExtendee());
        $name = $field->getName();
        if ($ns) {
            $name = $ns . '.' . $name;
        }
        $field->setName($name);
 
        $s[]= "ProtoJson.extend($extendee, {";
        $s[]= "  $field->number: " . $this->generateField($field);
        $s[]= "});";
        $s[]= '';
 
        return $indent . implode("\n$indent", $s);
    }
 
    public function compileMessage(proto\DescriptorProto $msg, $namespace)
    {
        $s[]= "/**";
        $s[]= " * @constructor";
        $s[]= " * @augments {ProtoJson.Message}";
        $s[]= " * @extends ProtoJson.Message";
        $s[]= " * @memberOf $namespace";
        $s[]= " * @param {object} data - Optional, provide initial data to parse";
        $s[]= " */";
        $s[]= "$namespace.$msg->name = ProtoJson.create({";
        $s[]= "  fields: {";
 
        $lines = array();
        foreach ($msg->getFieldList() as $field) {
            $lines[] = "    $field->number: " . $this->generateField($field);
        }
        $s[] = implode(",\n", $lines);
 
        $s[]= "  },";
        $s[]= "  ranges: [";
        // @todo dump extension ranges
        $s[]= "  ]";
        $s[]= "});";
        $s[]= "";
 
        // Compute a new namespace with the message name as suffix
        $namespace .= "." . $msg->getName();
 
        // Generate getters/setters
        foreach ($msg->getFieldList() as $field) {
            $s[]= $this->generateAccessors($field, $namespace);
        }
 
        // Generate Enums
        foreach ($msg->getEnumTypeList() as $enum):
        $s[]= $this->compileEnum($enum, $namespace);
        endforeach;
 
        // Generate nested messages
        foreach ($msg->getNestedTypeList() as $msg):
        $s[]= $this->compileMessage($msg, $namespace);
        endforeach;
 
        // Collect extensions
        foreach ($msg->getExtensionList() as $field) {
            $this->extensions[$field->getExtendee()][] = array($namespace, $field);
        }
 
        return implode("\n", $s);
    }
 
    public function compileProtoFile(proto\FileDescriptorProto $proto)
    {
        $file = new proto\compiler\CodeGeneratorResponse\File();
 
        $opts = $proto->getOptions();
        $name = pathinfo($proto->getName(), PATHINFO_FILENAME);
        $name .= isset($opts['json.suffix'])
                 ? $opts['json.suffix']
                 : '.js';
        $file->setName($name);
 
        $namespace = $this->getNamespace($proto);
 
        $s[]= "// DO NOT EDIT! Generated by Protobuf for PHP protoc plugin " . Protobuf::VERSION;
        $s[]= "// Source: " . $proto->getName();
        $s[]= "//   Date: " . date('Y-m-d H:i:s');
        $s[]= "";
 
        $s[]= "(function(){";
        $s[]= "/** @namespace */";
        $s[]= "var $namespace = $namespace || {};";
        $s[]= "";
        $s[]= "// Make it CommonJS compatible";
        $s[]= "if (typeof exports !== 'undefined') {";
        $s[]= "  var ProtoJson = this.ProtoJson;";
        $s[]= "  if (!ProtoJson && typeof require !== 'undefined')";
        $s[]= "    ProtoJson = require('ProtoJson');";
        $s[]= "  $namespace = exports;";
        $s[]= "} else {";
        $s[]= "  this.$namespace = $namespace;";
        $s[]= "}";
        $s[]= "";
 
 
        // Generate Enums
        foreach ($proto->getEnumTypeList() as $enum) {
            $s[]= $this->compileEnum($enum, $namespace);
        }
 
        // Generate Messages
        foreach ($proto->getMessageTypeList() as $msg) {
            $s[] = $this->compileMessage($msg, $namespace);
        }
 
        // Collect extensions
        if ($proto->hasExtension()) {
            foreach ($proto->getExtensionList() as $field) {
                $this->extensions[$field->getExtendee()][] = array($namespace, $field);
            }
        }
 
        // Dump all extensions found in this proto file
        if (count($this->extensions)) {
            foreach ($this->extensions as $extendee => $fields) {
                foreach ($fields as $pair) {
                    list($ns, $field) = $pair;
                    $s[]= $this->compileExtension($field, $ns, '');
                }
            }
        }
 
        $s[]= "})();";
 
        $src = implode("\n", $s);
        $file->setContent($src);
        return array($file);
    }
 
    public function generateField(proto\FieldDescriptorProto $field)
    {
        $reference = 'null';
        if ($field->hasTypeName()) {
            $reference = $field->getTypeName();
            if (substr($reference, 0, 1) !== '.') {
                throw new \RuntimeException('Only fully qualified names are supported: ' . $reference);
            }
            $reference = "'" . $this->normalizeReference($reference) . "'";
        }
 
        $default = 'null';
        if ($field->hasDefaultValue()):
            switch ($field->getType()) {
            case Protobuf::TYPE_BOOL:
                $default = $field->getDefaultValue() ? 'true' : 'false';
                break;
            case Protobuf::TYPE_STRING:
                $default = '"' . addcslashes($field->getDefaultValue(), '"\\') . '"';
                break;
            case Protobuf::TYPE_ENUM:
                $default = $this->normalizeReference($field->getTypeName()) . '.' . $field->getDefaultValue();
                break;
            default: // Numbers
                $default = $field->getDefaultValue();
            }
        endif;
 
        $data = array(
            "'" . $field->getName() . "'",
            $field->getLabel(),
            $field->getType(),
            $reference,
            $default,
            '{}'
        );
 
        return '[' . implode(', ', $data) . ']';
    }
 
    public function generateAccessors($field, $namespace)
    {
        $camel = $this->comp->camelize(ucfirst($field->getName()));
 
        $s[]= "/**";
        $s[]= " * Check <$field->name> value";
        $s[]= " * @return {Boolean}";
        $s[]= " */";
        $s[]= "$namespace.prototype.has$camel = function(){";
        $s[]= "  return this._has($field->number);";
        $s[]= "};";
        $s[]= "";
 
        $s[]= "/**";
        $s[]= " * Set a value for <$field->name>";
        $s[]= " * @param {" . $this->getJsDoc($field) . "} value";
        $s[]= " * @return {".  $namespace . "}";
        $s[]= " */";
        $s[]= "$namespace.prototype.set$camel = function(value){";
        $s[]= "  return this._set($field->number, value);";
        $s[]= "};";
        $s[]= "";
 
 
        $s[]= "/**";
        $s[]= " * Clear the value of <$field->name>";
        $s[]= " * @return {".  $namespace . "}";
        $s[]= " */";
        $s[]= "$namespace.prototype.clear$camel = function(){";
        $s[]= "  return this._clear($field->number);";
        $s[]= "};";
        $s[]= "";
 
 
        if ($field->getLabel() !== Protobuf::RULE_REPEATED):
 
        $s[]= "/**";
        $s[]= " * Get <$field->name> value";
        $s[]= " * @return {" . $this->getJsDoc($field) . "}";
        $s[]= " */";
        $s[]= "$namespace.prototype.get$camel = function(){";
        $s[]= "  return this._get($field->number);";
        $s[]= "};";
        $s[]= "";
 
        else:
 
        $s[]= "/**";
        $s[]= " * Get an item from <$field->name>";
        $s[]= " * @param {int} idx";
        $s[]= " * @return {" . $this->getJsDoc($field) . "}";
        $s[]= " */";
        $s[]= "$namespace.prototype.get$camel = function(idx){";
        $s[]= "  return this._get($field->number, idx);";
        $s[]= "};";
        $s[]= "";
 
 
        $s