1 /*
2  *
3  * Copyright 2016 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 // Generates PHP gRPC service interface out of Protobuf IDL.
20 
21 #include <memory>
22 
23 #include "src/compiler/config.h"
24 #include "src/compiler/php_generator.h"
25 #include "src/compiler/php_generator_helpers.h"
26 
27 using google::protobuf::compiler::ParseGeneratorParameter;
28 using grpc_php_generator::GenerateFile;
29 using grpc_php_generator::GetPHPServiceFilename;
30 
31 class PHPGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
32  public:
PHPGrpcGenerator()33   PHPGrpcGenerator() {}
~PHPGrpcGenerator()34   ~PHPGrpcGenerator() {}
35 
Generate(const grpc::protobuf::FileDescriptor * file,const grpc::string & parameter,grpc::protobuf::compiler::GeneratorContext * context,grpc::string * error) const36   bool Generate(const grpc::protobuf::FileDescriptor* file,
37                 const grpc::string& parameter,
38                 grpc::protobuf::compiler::GeneratorContext* context,
39                 grpc::string* error) const {
40     if (file->service_count() == 0) {
41       return true;
42     }
43 
44     std::vector<std::pair<grpc::string, grpc::string> > options;
45     ParseGeneratorParameter(parameter, &options);
46 
47     grpc::string class_suffix;
48     for (size_t i = 0; i < options.size(); ++i) {
49       if (options[i].first == "class_suffix") {
50         class_suffix = options[i].second;
51       } else {
52         *error = "unsupported options: " + options[i].first;
53         return false;
54       }
55     }
56 
57     for (int i = 0; i < file->service_count(); i++) {
58       grpc::string code = GenerateFile(file, file->service(i), class_suffix);
59 
60       // Get output file name
61       grpc::string file_name =
62           GetPHPServiceFilename(file, file->service(i), class_suffix);
63 
64       std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output(
65           context->Open(file_name));
66       grpc::protobuf::io::CodedOutputStream coded_out(output.get());
67       coded_out.WriteRaw(code.data(), code.size());
68     }
69 
70     return true;
71   }
72 };
73 
main(int argc,char * argv[])74 int main(int argc, char* argv[]) {
75   PHPGrpcGenerator generator;
76   return grpc::protobuf::compiler::PluginMain(argc, argv, &generator);
77 }
78