• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<?php
2
3// Protocol Buffers - Google's data interchange format
4// Copyright 2008 Google Inc.  All rights reserved.
5//
6// Use of this source code is governed by a BSD-style
7// license that can be found in the LICENSE file or at
8// https://developers.google.com/open-source/licenses/bsd
9
10namespace Google\Protobuf\Internal;
11
12use Google\Protobuf\Internal\GPBLabel;
13use Google\Protobuf\Internal\GPBType;
14use Google\Protobuf\Internal\Descriptor;
15use Google\Protobuf\Internal\FieldDescriptor;
16
17class MessageBuilderContext
18{
19
20    private $descriptor;
21    private $pool;
22
23    public function __construct($full_name, $klass, $pool)
24    {
25        $this->descriptor = new Descriptor();
26        $this->descriptor->setFullName($full_name);
27        $this->descriptor->setClass($klass);
28        $this->pool = $pool;
29    }
30
31    private function getFieldDescriptor($name, $label, $type,
32                                      $number, $type_name = null)
33    {
34        $field = new FieldDescriptor();
35        $field->setName($name);
36        $camel_name = implode('', array_map('ucwords', explode('_', $name)));
37        $field->setGetter('get' . $camel_name);
38        $field->setSetter('set' . $camel_name);
39        $field->setType($type);
40        $field->setNumber($number);
41        $field->setLabel($label);
42
43        // At this time, the message/enum type may have not been added to pool.
44        // So we use the type name as place holder and will replace it with the
45        // actual descriptor in cross building.
46        switch ($type) {
47        case GPBType::MESSAGE:
48          $field->setMessageType($type_name);
49          break;
50        case GPBType::ENUM:
51          $field->setEnumType($type_name);
52          break;
53        default:
54          break;
55        }
56
57        return $field;
58    }
59
60    public function optional($name, $type, $number, $type_name = null)
61    {
62        $this->descriptor->addField($this->getFieldDescriptor(
63            $name,
64            GPBLabel::OPTIONAL,
65            $type,
66            $number,
67            $type_name));
68        return $this;
69    }
70
71    public function repeated($name, $type, $number, $type_name = null)
72    {
73        $this->descriptor->addField($this->getFieldDescriptor(
74            $name,
75            GPBLabel::REPEATED,
76            $type,
77            $number,
78            $type_name));
79        return $this;
80    }
81
82    public function required($name, $type, $number, $type_name = null)
83    {
84        $this->descriptor->addField($this->getFieldDescriptor(
85            $name,
86            GPBLabel::REQUIRED,
87            $type,
88            $number,
89            $type_name));
90        return $this;
91    }
92
93    public function finalizeToPool()
94    {
95        $this->pool->addDescriptor($this->descriptor);
96    }
97}
98