summaryrefslogtreecommitdiff
path: root/grpc/src/compiler/php_generator.cc
blob: 28bbebd10416e45b77d4618089e66979c7354728 (plain)
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
/*
 *
 * Copyright 2016 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <map>

#include <google/protobuf/compiler/php/php_generator.h>
#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
#include "src/compiler/php_generator_helpers.h"

using google::protobuf::compiler::php::GeneratedClassName;
using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using std::map;

namespace grpc_php_generator {
namespace {

std::string ConvertToPhpNamespace(const std::string& name) {
  std::vector<std::string> tokens = grpc_generator::tokenize(name, ".");
  std::ostringstream oss;
  for (unsigned int i = 0; i < tokens.size(); i++) {
    oss << (i == 0 ? "" : "\\")
        << grpc_generator::CapitalizeFirstLetter(tokens[i]);
  }
  return oss.str();
}

std::string PackageName(const FileDescriptor* file) {
  if (file->options().has_php_namespace()) {
    return file->options().php_namespace();
  } else {
    return ConvertToPhpNamespace(file->package());
  }
}

std::string MessageIdentifierName(const std::string& name,
                                  const FileDescriptor* file) {
  std::vector<std::string> tokens = grpc_generator::tokenize(name, ".");
  std::ostringstream oss;
  if (PackageName(file) != "") {
    oss << PackageName(file) << "\\";
  }
  oss << grpc_generator::CapitalizeFirstLetter(tokens[tokens.size() - 1]);
  return oss.str();
}

void PrintMethod(const MethodDescriptor* method, Printer* out) {
  const Descriptor* input_type = method->input_type();
  const Descriptor* output_type = method->output_type();
  map<std::string, std::string> vars;
  vars["service_name"] = method->service()->full_name();
  vars["name"] = method->name();
  vars["input_type_id"] =
      MessageIdentifierName(GeneratedClassName(input_type), input_type->file());
  vars["output_type_id"] = MessageIdentifierName(
      GeneratedClassName(output_type), output_type->file());

  out->Print("/**\n");
  out->Print(GetPHPComments(method, " *").c_str());
  if (method->client_streaming()) {
    if (method->server_streaming()) {
      vars["return_type_id"] = "\\Grpc\\BidiStreamingCall";
    } else {
      vars["return_type_id"] = "\\Grpc\\ClientStreamingCall";
    }
    out->Print(vars,
               " * @param array $$metadata metadata\n"
               " * @param array $$options call options\n"
               " * @return $return_type_id$\n */\n"
               "public function $name$($$metadata = [], "
               "$$options = []) {\n");
    out->Indent();
    out->Indent();
    if (method->server_streaming()) {
      out->Print("return $$this->_bidiRequest(");
    } else {
      out->Print("return $$this->_clientStreamRequest(");
    }
    out->Print(vars,
               "'/$service_name$/$name$',\n"
               "['\\$output_type_id$','decode'],\n"
               "$$metadata, $$options);\n");
  } else {
    if (method->server_streaming()) {
      vars["return_type_id"] = "\\Grpc\\ServerStreamingCall";
    } else {
      vars["return_type_id"] = "\\Grpc\\UnaryCall";
    }
    out->Print(vars,
               " * @param \\$input_type_id$ $$argument input argument\n"
               " * @param array $$metadata metadata\n"
               " * @param array $$options call options\n"
               " * @return $return_type_id$\n */\n"
               "public function $name$(\\$input_type_id$ $$argument,\n"
               "  $$metadata = [], $$options = []) {\n");
    out->Indent();
    out->Indent();
    if (method->server_streaming()) {
      out->Print("return $$this->_serverStreamRequest(");
    } else {
      out->Print("return $$this->_simpleRequest(");
    }
    out->Print(vars,
               "'/$service_name$/$name$',\n"
               "$$argument,\n"
               "['\\$output_type_id$', 'decode'],\n"
               "$$metadata, $$options);\n");
  }
  out->Outdent();
  out->Outdent();
  out->Print("}\n\n");
}

void PrintServerMethod(const MethodDescriptor* method, Printer* out) {
  map<std::string, std::string> vars;
  const Descriptor* input_type = method->input_type();
  const Descriptor* output_type = method->output_type();
  vars["service_name"] = method->service()->full_name();
  vars["method_name"] = method->name();
  vars["input_type_id"] =
      MessageIdentifierName(GeneratedClassName(input_type), input_type->file());
  vars["output_type_id"] = MessageIdentifierName(
      GeneratedClassName(output_type), output_type->file());

  out->Print("/**\n");
  out->Print(GetPHPComments(method, " *").c_str());

  const char* method_template;
  if (method->client_streaming() && method->server_streaming()) {
    method_template =
        " * @param \\Grpc\\ServerCallReader $$reader read client request data "
        "of \\$input_type_id$\n"
        " * @param \\Grpc\\ServerCallWriter $$writer write response data of "
        "\\$output_type_id$\n"
        " * @param \\Grpc\\ServerContext $$context server request context\n"
        " * @return void\n"
        " */\n"
        "public function $method_name$(\n"
        "    \\Grpc\\ServerCallReader $$reader,\n"
        "    \\Grpc\\ServerCallWriter $$writer,\n"
        "    \\Grpc\\ServerContext $$context\n"
        "): void {\n"
        "    $$context->setStatus(\\Grpc\\Status::unimplemented());\n"
        "    $$writer->finish();\n"
        "}\n\n";
  } else if (method->client_streaming()) {
    method_template =
        " * @param \\Grpc\\ServerCallReader $$reader read client request data "
        "of \\$input_type_id$\n"
        " * @param \\Grpc\\ServerContext $$context server request context\n"
        " * @return \\$output_type_id$ for response data, null if if error "
        "occured\n"
        " *     initial metadata (if any) and status (if not ok) should be set "
        "to $$context\n"
        " */\n"
        "public function $method_name$(\n"
        "    \\Grpc\\ServerCallReader $$reader,\n"
        "    \\Grpc\\ServerContext $$context\n"
        "): ?\\$output_type_id$ {\n"
        "    $$context->setStatus(\\Grpc\\Status::unimplemented());\n"
        "    return null;\n"
        "}\n\n";
  } else if (method->server_streaming()) {
    method_template =
        " * @param \\$input_type_id$ $$request client request\n"
        " * @param \\Grpc\\ServerCallWriter $$writer write response data of "
        "\\$output_type_id$\n"
        " * @param \\Grpc\\ServerContext $$context server request context\n"
        " * @return void\n"
        " */\n"
        "public function $method_name$(\n"
        "    \\$input_type_id$ $$request,\n"
        "    \\Grpc\\ServerCallWriter $$writer,\n"
        "    \\Grpc\\ServerContext $$context\n"
        "): void {\n"
        "    $$context->setStatus(\\Grpc\\Status::unimplemented());\n"
        "    $$writer->finish();\n"
        "}\n\n";
  } else {
    method_template =
        " * @param \\$input_type_id$ $$request client request\n"
        " * @param \\Grpc\\ServerContext $$context server request context\n"
        " * @return \\$output_type_id$ for response data, null if if error "
        "occured\n"
        " *     initial metadata (if any) and status (if not ok) should be set "
        "to $$context\n"
        " */\n"
        "public function $method_name$(\n"
        "    \\$input_type_id$ $$request,\n"
        "    \\Grpc\\ServerContext $$context\n"
        "): ?\\$output_type_id$ {\n"
        "    $$context->setStatus(\\Grpc\\Status::unimplemented());\n"
        "    return null;\n"
        "}\n\n";
  }
  out->Print(vars, method_template);
}

void PrintServerMethodDescriptors(const ServiceDescriptor* service,
                                  Printer* out) {
  map<std::string, std::string> vars;
  vars["service_name"] = service->full_name();

  out->Print(
      "/**\n"
      " * Get the method descriptors of the service for server registration\n"
      " *\n"
      " * @return array of \\Grpc\\MethodDescriptor for the service methods\n"
      " */\n"
      "public final function getMethodDescriptors(): array\n{\n");
  out->Indent();
  out->Indent();
  out->Print("return [\n");
  out->Indent();
  out->Indent();
  for (int i = 0; i < service->method_count(); i++) {
    auto method = service->method(i);
    auto input_type = method->input_type();
    vars["method_name"] = method->name();
    vars["input_type_id"] = MessageIdentifierName(
        GeneratedClassName(input_type), input_type->file());
    if (method->client_streaming() && method->server_streaming()) {
      vars["call_type"] = "BIDI_STREAMING_CALL";
    } else if (method->client_streaming()) {
      vars["call_type"] = "CLIENT_STREAMING_CALL";
    } else if (method->server_streaming()) {
      vars["call_type"] = "SERVER_STREAMING_CALL";
    } else {
      vars["call_type"] = "UNARY_CALL";
    }
    out->Print(
        vars,
        "'/$service_name$/$method_name$' => new \\Grpc\\MethodDescriptor(\n"
        "    $$this,\n"
        "    '$method_name$',\n"
        "    '\\$input_type_id$',\n"
        "    \\Grpc\\MethodDescriptor::$call_type$\n"
        "),\n");
  }
  out->Outdent();
  out->Outdent();
  out->Print("];\n");
  out->Outdent();
  out->Outdent();
  out->Print("}\n\n");
}

// Prints out the service descriptor object
void PrintService(const ServiceDescriptor* service,
                  const std::string& class_suffix, bool is_server,
                  Printer* out) {
  map<std::string, std::string> vars;
  out->Print("/**\n");
  out->Print(GetPHPComments(service, " *").c_str());
  out->Print(" */\n");
  vars["name"] = GetPHPServiceClassname(service, class_suffix, is_server);
  vars["extends"] = is_server ? "" : "extends \\Grpc\\BaseStub ";
  out->Print(vars, "class $name$ $extends${\n\n");
  out->Indent();
  out->Indent();
  if (!is_server) {
    out->Print(
        "/**\n * @param string $$hostname hostname\n"
        " * @param array $$opts channel options\n"
        " * @param \\Grpc\\Channel $$channel (optional) re-use channel object\n"
        " */\n"
        "public function __construct($$hostname, $$opts, "
        "$$channel = null) {\n");
    out->Indent();
    out->Indent();
    out->Print("parent::__construct($$hostname, $$opts, $$channel);\n");
    out->Outdent();
    out->Outdent();
    out->Print("}\n\n");
  }
  for (int i = 0; i < service->method_count(); i++) {
    if (is_server) {
      PrintServerMethod(service->method(i), out);
    } else {
      PrintMethod(service->method(i), out);
    }
  }
  if (is_server) {
    PrintServerMethodDescriptors(service, out);
  }
  out->Outdent();
  out->Outdent();
  out->Print("}\n");
}
}  // namespace

std::string GenerateFile(const FileDescriptor* file,
                         const ServiceDescriptor* service,
                         const std::string& class_suffix, bool is_server) {
  std::string output;
  {
    StringOutputStream output_stream(&output);
    Printer out(&output_stream, '$');

    out.Print("<?php\n");
    out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");

    std::string leading_comments = GetPHPComments(file, "//");
    if (!leading_comments.empty()) {
      out.Print("// Original file comments:\n");
      out.PrintRaw(leading_comments.c_str());
    }

    map<std::string, std::string> vars;
    std::string php_namespace = PackageName(file);
    vars["package"] = php_namespace;
    out.Print(vars, "namespace $package$;\n\n");

    PrintService(service, class_suffix, is_server, &out);
  }
  return output;
}

}  // namespace grpc_php_generator