Skip to content
This repository has been archived by the owner on Jun 28, 2022. It is now read-only.

Commit

Permalink
Refactor PHP discovery snippetgen for MVVM
Browse files Browse the repository at this point in the history
  • Loading branch information
saicheems committed Nov 2, 2016
1 parent 39e3541 commit affbb66
Show file tree
Hide file tree
Showing 14 changed files with 2,018 additions and 2,660 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@
import com.google.api.codegen.discovery.config.go.GoTypeNameGenerator;
import com.google.api.codegen.discovery.config.java.JavaTypeNameGenerator;
import com.google.api.codegen.discovery.config.nodejs.NodeJSTypeNameGenerator;
import com.google.api.codegen.discovery.config.php.PhpTypeNameGenerator;
import com.google.api.codegen.discovery.config.ruby.RubyTypeNameGenerator;
import com.google.api.codegen.discovery.transformer.SampleMethodToViewTransformer;
import com.google.api.codegen.discovery.transformer.go.GoSampleMethodToViewTransformer;
import com.google.api.codegen.discovery.transformer.java.JavaSampleMethodToViewTransformer;
import com.google.api.codegen.discovery.transformer.nodejs.NodeJSSampleMethodToViewTransformer;
import com.google.api.codegen.discovery.transformer.php.PhpSampleMethodToViewTransformer;
import com.google.api.codegen.discovery.transformer.ruby.RubySampleMethodToViewTransformer;
import com.google.api.codegen.php.PhpDiscoveryContext;
import com.google.api.codegen.php.PhpSnippetSetRunner;
import com.google.api.codegen.py.PythonDiscoveryContext;
import com.google.api.codegen.py.PythonDiscoveryInitializer;
import com.google.api.codegen.py.PythonSnippetSetRunner;
Expand Down Expand Up @@ -63,12 +63,14 @@ public class MainDiscoveryProviderFactory implements DiscoveryProviderFactory {
GO, GoSampleMethodToViewTransformer.class,
JAVA, JavaSampleMethodToViewTransformer.class,
NODEJS, NodeJSSampleMethodToViewTransformer.class,
PHP, PhpSampleMethodToViewTransformer.class,
RUBY, RubySampleMethodToViewTransformer.class);
private static final Map<String, Class<? extends TypeNameGenerator>> TYPE_NAME_GENERATOR_MAP =
ImmutableMap.of(
GO, GoTypeNameGenerator.class,
JAVA, JavaTypeNameGenerator.class,
NODEJS, NodeJSTypeNameGenerator.class,
PHP, PhpTypeNameGenerator.class,
RUBY, RubyTypeNameGenerator.class);

public static DiscoveryProvider defaultCreate(
Expand All @@ -90,14 +92,6 @@ public static DiscoveryProvider defaultCreate(
.setSnippetFileName(id + "/" + DEFAULT_SNIPPET_FILE)
.build();

} else if (id.equals(PHP)) {
return CommonDiscoveryProvider.newBuilder()
.setContext(new PhpDiscoveryContext(service, apiaryConfig))
.setSnippetSetRunner(
new PhpSnippetSetRunner<Method>(SnippetSetRunner.SNIPPET_RESOURCE_ROOT))
.setSnippetFileName(id + "/" + DEFAULT_SNIPPET_FILE)
.build();

} else if (id.equals(PYTHON)) {
return CommonDiscoveryProvider.newBuilder()
.setContext(new PythonDiscoveryContext(service, apiaryConfig))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/* Copyright 2016 Google Inc
*
* 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.
*/
package com.google.api.codegen.discovery.config.php;

import com.google.api.codegen.discovery.config.TypeNameGenerator;
import com.google.api.codegen.util.Name;
import com.google.common.collect.ImmutableSet;
import java.util.List;

public class PhpTypeNameGenerator extends TypeNameGenerator {

/**
* Set of method names that must have the previous name components as upper-camel suffixes.
*
* <p>For example: "foo.bar.list" to "foo.bar.listFooBar"
*/
ImmutableSet<String> RENAMED_METHODS = ImmutableSet.of("list", "clone");

@Override
public String stringDelimiter() {
return "'";
}

@Override
public String getApiTypeName(String apiName) {
return "Google_Service_" + apiName.replace(" ", "");
}

@Override
public List<String> getMethodNameComponents(List<String> nameComponents) {
nameComponents = super.getMethodNameComponents(nameComponents);
String verb = nameComponents.remove(nameComponents.size() - 1); // Pop the last element.
if (RENAMED_METHODS.contains(verb)) {
for (String s : nameComponents) {
verb += Name.lowerCamel(s).toUpperCamel();
}
}
nameComponents.add(verb);
return nameComponents;
}

@Override
public String getMessageTypeName(String messageTypeName) {
// Avoid cases like "DatasetList.Datasets"
String pieces[] = messageTypeName.split("\\.");
return pieces[pieces.length - 1];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
*/
package com.google.api.codegen.discovery.config.ruby;

import com.google.api.codegen.DiscoveryImporter;
import com.google.api.codegen.discovery.config.TypeNameGenerator;
import com.google.api.codegen.ruby.RubyApiaryNameMap;
import com.google.api.codegen.util.Name;
Expand Down Expand Up @@ -89,15 +88,6 @@ public String getApiTypeName(String apiName) {
return Name.upperCamel(apiName.replace(" ", ""), "Service").toUpperCamel();
}

@Override
public String getResponseTypeUrl(String responseTypeUrl) {
if (responseTypeUrl.equals(DiscoveryImporter.EMPTY_TYPE_NAME)
|| responseTypeUrl.equals(DiscoveryImporter.EMPTY_TYPE_URL)) {
return "";
}
return responseTypeUrl;
}

@Override
public String getMessageTypeName(String messageTypeName) {
// Avoid cases like "DatasetList.Datasets"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ public class NodeJSSampleTypeNameConverter implements SampleTypeNameConverter {
/** A map from primitive types in proto to NodeJS counterparts. */
private static final ImmutableMap<Field.Kind, String> PRIMITIVE_TYPE_MAP =
ImmutableMap.<Field.Kind, String>builder()
.put(Field.Kind.TYPE_UNKNOWN, "Object")
.put(Field.Kind.TYPE_BOOL, "boolean")
.put(Field.Kind.TYPE_INT32, "number")
.put(Field.Kind.TYPE_INT64, "number")
Expand All @@ -41,7 +40,6 @@ public class NodeJSSampleTypeNameConverter implements SampleTypeNameConverter {
/** A map from primitive types in proto to zero value in NodeJS */
private static final ImmutableMap<Field.Kind, String> PRIMITIVE_ZERO_VALUE =
ImmutableMap.<Field.Kind, String>builder()
.put(Field.Kind.TYPE_UNKNOWN, "{}")
.put(Field.Kind.TYPE_BOOL, "false")
.put(Field.Kind.TYPE_INT32, "0")
.put(Field.Kind.TYPE_INT64, "''")
Expand Down Expand Up @@ -80,6 +78,9 @@ public TypeName getTypeName(TypeInfo typeInfo) {

@Override
public TypeName getTypeNameForElementType(TypeInfo typeInfo) {
if (typeInfo.kind() == Field.Kind.TYPE_UNKNOWN) {
return new TypeName("Object");
}
String primitiveTypeName = PRIMITIVE_TYPE_MAP.get(typeInfo.kind());
if (primitiveTypeName != null) {
return new TypeName(primitiveTypeName);
Expand All @@ -90,7 +91,7 @@ public TypeName getTypeNameForElementType(TypeInfo typeInfo) {
@Override
public TypedValue getZeroValue(TypeInfo typeInfo) {
// Don't call getTypeName; we don't need to import these.
if (typeInfo.isMap()) {
if (typeInfo.isMap() || typeInfo.kind() == Field.Kind.TYPE_UNKNOWN) {
return TypedValue.create(new TypeName("Object"), "{}");
}
if (typeInfo.isArray()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
/* Copyright 2016 Google Inc
*
* 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.
*/
package com.google.api.codegen.discovery.transformer.php;

import com.google.api.codegen.discovery.config.FieldInfo;
import com.google.api.codegen.discovery.config.MethodInfo;
import com.google.api.codegen.discovery.config.SampleConfig;
import com.google.api.codegen.discovery.transformer.SampleMethodToViewTransformer;
import com.google.api.codegen.discovery.transformer.SampleNamer;
import com.google.api.codegen.discovery.transformer.SampleTransformerContext;
import com.google.api.codegen.discovery.transformer.SampleTypeTable;
import com.google.api.codegen.discovery.viewmodel.SampleAuthView;
import com.google.api.codegen.discovery.viewmodel.SampleFieldView;
import com.google.api.codegen.discovery.viewmodel.SamplePageStreamingView;
import com.google.api.codegen.discovery.viewmodel.SampleView;
import com.google.api.codegen.util.Name;
import com.google.api.codegen.util.SymbolTable;
import com.google.api.codegen.util.php.PhpTypeTable;
import com.google.api.codegen.viewmodel.ViewModel;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.Method;
import java.util.ArrayList;
import java.util.List;

public class PhpSampleMethodToViewTransformer implements SampleMethodToViewTransformer {

private static final String TEMPLATE_FILENAME = "php/sample.snip";

// Map of rename rules for fields.
// Could be done through overrides, but this is a rule implemented in the PHP
// client library generator.
private static final ImmutableMap<String, String> FIELD_RENAMES =
ImmutableMap.of("objectId", "object_id_");

public PhpSampleMethodToViewTransformer() {}

@Override
public ViewModel transform(Method method, SampleConfig config) {
SampleTypeTable typeTable =
new SampleTypeTable(
new PhpTypeTable(""), new PhpSampleTypeNameConverter(config.apiTypeName()));
SampleNamer namer = new PhpSampleNamer();
SampleTransformerContext context =
SampleTransformerContext.create(config, typeTable, namer, method.getName());
return createSampleView(context);
}

private SampleView createSampleView(SampleTransformerContext context) {
SampleConfig config = context.getSampleConfig();
MethodInfo methodInfo = config.methods().get(context.getMethodName());
SampleNamer namer = context.getSampleNamer();
SampleTypeTable typeTable = context.getSampleTypeTable();
SymbolTable symbolTable = SymbolTable.fromSeed(PhpTypeTable.RESERVED_IDENTIFIER_SET);

SampleView.Builder builder = SampleView.newBuilder();

String serviceVarName = symbolTable.getNewSymbol(namer.getServiceVarName(config.apiTypeName()));
String serviceTypeName = typeTable.getServiceTypeName(config.apiTypeName()).getNickname();

if (methodInfo.isPageStreaming()) {
builder.pageStreaming(createSamplePageStreamingView(context, symbolTable));
}

// Created before the fields in-case there are naming conflicts in the symbol table.
SampleAuthView sampleAuthView = createSampleAuthView(context);

List<SampleFieldView> fields = new ArrayList<>();
List<String> fieldVarNames = new ArrayList<>();
for (FieldInfo field : methodInfo.fields().values()) {
String name = namer.localVarName(Name.lowerCamel(field.name()));
if (FIELD_RENAMES.containsKey(field.name())) {
name = FIELD_RENAMES.get(field.name());
}
SampleFieldView sampleFieldView =
SampleFieldView.newBuilder()
.name(name)
.defaultValue(typeTable.getZeroValueAndSaveNicknameFor(field.type()))
.example(field.example())
.description(field.description())
.build();
fields.add(sampleFieldView);
fieldVarNames.add(sampleFieldView.name());
}

boolean hasRequestBody = methodInfo.requestBodyType() != null;
if (hasRequestBody) {
String requestBodyVarName = symbolTable.getNewSymbol(namer.getRequestBodyVarName());
builder.requestBodyVarName(requestBodyVarName);
builder.requestBodyTypeName(
typeTable.getTypeName(methodInfo.requestBodyType()).getNickname());
fieldVarNames.add(requestBodyVarName);
}

boolean hasResponse = methodInfo.responseType() != null;
if (hasResponse) {
builder.responseVarName(symbolTable.getNewSymbol(namer.getResponseVarName()));
}

String optParamsVarName = "";
if (methodInfo.isPageStreaming() || methodInfo.hasMediaDownload()) {
optParamsVarName = namer.localVarName(Name.lowerCamel("optParams"));
fieldVarNames.add(optParamsVarName);
}

return builder
.templateFileName(TEMPLATE_FILENAME)
.outputPath(context.getMethodName() + ".frag.php")
.apiTitle(config.apiTitle())
.apiName(config.apiName())
.apiVersion(config.apiVersion())
.appName(namer.getSampleApplicationName(config.apiTypeName()))
.auth(sampleAuthView)
.serviceVarName(serviceVarName)
.serviceTypeName(serviceTypeName)
.methodVerb(methodInfo.verb())
.methodNameComponents(methodInfo.nameComponents())
.hasRequestBody(hasRequestBody)
.hasResponse(hasResponse)
.fields(fields)
.fieldVarNames(fieldVarNames)
.isPageStreaming(methodInfo.isPageStreaming())
.hasMediaUpload(methodInfo.hasMediaUpload())
.hasMediaDownload(methodInfo.hasMediaDownload())
.clientVarName(namer.localVarName(Name.lowerCamel("client")))
.optParamsVarName(optParamsVarName)
.build();
}

private SampleAuthView createSampleAuthView(SampleTransformerContext context) {
SampleConfig config = context.getSampleConfig();
MethodInfo methodInfo = config.methods().get(context.getMethodName());

return SampleAuthView.newBuilder()
.type(config.authType())
.instructionsUrl(config.authInstructionsUrl())
.scopes(methodInfo.authScopes())
.isScopesSingular(methodInfo.authScopes().size() == 1)
.build();
}

private SamplePageStreamingView createSamplePageStreamingView(
SampleTransformerContext context, SymbolTable symbolTable) {
MethodInfo methodInfo = context.getSampleConfig().methods().get(context.getMethodName());
FieldInfo fieldInfo = methodInfo.pageStreamingResourceField();
SampleNamer namer = context.getSampleNamer();
if (fieldInfo == null) {
throw new IllegalArgumentException("pageStreamingResourceField cannot be null");
}

SamplePageStreamingView.Builder builder = SamplePageStreamingView.newBuilder();

builder.resourceFieldName(namer.publicFieldName(Name.lowerCamel(fieldInfo.name())));
if (fieldInfo.type().isMap()) {
// Assume that the value in the map is a message.
if (!fieldInfo.type().mapValue().isMessage()) {
throw new IllegalArgumentException("expected map value to be a message");
}
builder.resourceKeyVarName(
symbolTable.getNewSymbol(namer.localVarName(Name.lowerCamel("name"))));
String resourceValueVarName =
namer.localVarName(Name.upperCamel(fieldInfo.type().mapValue().message().typeName()));
builder.resourceValueVarName(symbolTable.getNewSymbol(resourceValueVarName));
} else {
String resourceVarName =
namer.getResourceVarName(
fieldInfo.type().isMessage() ? fieldInfo.type().message().typeName() : "");
builder.resourceVarName(symbolTable.getNewSymbol(resourceVarName));
}
builder.isResourceMap(fieldInfo.type().isMap());
builder.pageVarName(
symbolTable.getNewSymbol(namer.localVarName(Name.lowerCamel(fieldInfo.name()))));
return builder.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/* Copyright 2016 Google Inc
*
* 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.
*/
package com.google.api.codegen.discovery.transformer.php;

import com.google.api.codegen.discovery.transformer.SampleNamer;
import com.google.api.codegen.util.Name;
import com.google.api.codegen.util.php.PhpNameFormatter;

public class PhpSampleNamer extends SampleNamer {

public PhpSampleNamer() {
super(new PhpNameFormatter());
}

@Override
public String getSampleApplicationName(String apiTypeName) {
// Unfortunate replacement that's necessary because the API type name is of a special format.
return "Google-" + apiTypeName.replace("Google_Service_", "") + "Sample/0.1";
}

@Override
public String getServiceVarName(String apiTypeName) {
return localVarName(Name.lowerCamel("service"));
}
}
Loading

0 comments on commit affbb66

Please sign in to comment.