Merge branch 'develop_2.0' into ruby-object-type

Conflicts:
	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java
This commit is contained in:
xhh 2015-06-18 09:56:58 +08:00
commit d6d707543d
94 changed files with 1408 additions and 246 deletions

3
.gitignore vendored
View File

@ -41,3 +41,6 @@ atlassian-ide-plugin.xml
samples/client/petstore/php/SwaggerClient-php/composer.lock
samples/client/petstore/php/SwaggerClient-php/vendor/
samples/client/petstore/silex/SwaggerServer/composer.lock
samples/client/petstore/silex/SwaggerServer/venodr/

View File

@ -32,5 +32,6 @@ cd $APP_DIR
./bin/ruby-petstore.sh
./bin/objc-petstore.sh
./bin/scala-petstore.sh
./bin/silex-petstore-server.sh
./bin/spring-mvc-petstore-server.sh
./bin/tizen-petstore.sh

31
bin/silex-petstore-server.sh Executable file
View File

@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/silex -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l silex -o samples/client/petstore/silex"
java $JAVA_OPTS -jar $executable $ags

View File

@ -60,10 +60,10 @@ public abstract class AbstractGenerator {
throw new RuntimeException("can't load template " + name);
}
private String getCPResourcePath(String name) {
public String getCPResourcePath(String name) {
if (!"/".equals(File.separator)) {
return name.replaceAll(Pattern.quote(File.separator), "/");
}
return name;
}
}
}

View File

@ -268,11 +268,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
// continue
}
if (in == null) {
in = this.getClass().getClassLoader().getResourceAsStream(config.templateDir() + File.separator + support.templateFile);
in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(config.templateDir() + File.separator + support.templateFile));
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if (in != null && out != null) {
System.out.println("writing file " + outputFile);
IOUtils.copy(in, out);
} else {
if (in == null) {

View File

@ -20,7 +20,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
protected Set<String> foundationClasses = new HashSet<String>();
protected String sourceFolder = "client";
protected String classPrefix = "SWG";
protected String projectName = "swaggerClient";
protected String projectName = "SwaggerClient";
public ObjcClientCodegen() {
super();

View File

@ -46,10 +46,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("long", "int");
typeMapping.put("double", "float");
typeMapping.put("array", "list");
typeMapping.put("map", "map");
typeMapping.put("map", "dict");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "str");
typeMapping.put("date", "datetime");
typeMapping.put("object", "object");
// from https://docs.python.org/release/2.5.4/ref/keywords.html
reservedWords = new HashSet<String>(
@ -111,7 +112,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")";
return getSwaggerType(p) + "(str, " + getTypeDeclaration(inner) + ")";
}
return super.getTypeDeclaration(p);
}

View File

@ -1,5 +1,6 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
@ -13,16 +14,16 @@ import java.util.Arrays;
import java.util.HashSet;
public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String gemName = "swagger_client";
protected String gemName = null;
protected String moduleName = null;
protected String gemVersion = "1.0.0";
protected String libFolder = "lib";
public RubyClientCodegen() {
super();
moduleName = generateModuleName();
modelPackage = gemName + "/models";
apiPackage = gemName + "/api";
outputFolder = "generated-code" + File.separatorChar + "ruby";
modelPackage = "models";
apiPackage = "api";
outputFolder = "generated-code" + File.separator + "ruby";
modelTemplateFiles.put("model.mustache", ".rb");
apiTemplateFiles.put("api.mustache", ".rb");
templateDir = "ruby";
@ -39,9 +40,6 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
"if", "not", "return", "undef", "yield")
);
additionalProperties.put("gemName", gemName);
additionalProperties.put("moduleName", moduleName);
languageSpecificPrimitives.add("int");
languageSpecificPrimitives.add("array");
languageSpecificPrimitives.add("map");
@ -64,18 +62,59 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("map", "Hash");
typeMapping.put("object", "Object");
String baseFolder = "lib" + File.separatorChar + gemName;
String swaggerFolder = baseFolder + File.separatorChar + "swagger";
String modelFolder = baseFolder + File.separatorChar + "models";
// remove modelPackage and apiPackage added by default
cliOptions.clear();
cliOptions.add(new CliOption("gemName", "gem name (convention: underscore_case), default: swagger_client"));
cliOptions.add(new CliOption("moduleName", "top module name (convention: CamelCase, usually corresponding to gem name), default: SwaggerClient"));
cliOptions.add(new CliOption("gemVersion", "gem version, default: 1.0.0"));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey("gemName")) {
setGemName((String) additionalProperties.get("gemName"));
}
if (additionalProperties.containsKey("moduleName")) {
setModuleName((String) additionalProperties.get("moduleName"));
}
if (gemName == null && moduleName == null) {
setGemName("swagger_client");
setModuleName(generateModuleName(gemName));
} else if (gemName == null) {
setGemName(generateGemName(moduleName));
} else if (moduleName == null) {
setModuleName(generateModuleName(gemName));
}
additionalProperties.put("gemName", gemName);
additionalProperties.put("moduleName", moduleName);
if (additionalProperties.containsKey("gemVersion")) {
setGemVersion((String) additionalProperties.get("gemVersion"));
} else {
// not set, pass the default value to template
additionalProperties.put("gemVersion", gemVersion);
}
// use constant model/api package (folder path)
setModelPackage("models");
setApiPackage("api");
supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec"));
supportingFiles.add(new SupportingFile("swagger_client.mustache", "lib", gemName + ".rb"));
supportingFiles.add(new SupportingFile("swagger_client.mustache", libFolder, gemName + ".rb"));
String baseFolder = libFolder + File.separator + gemName;
supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb"));
supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "request.mustache", swaggerFolder, "request.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "response.mustache", swaggerFolder, "response.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "api_error.mustache", swaggerFolder, "api_error.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "version.mustache", swaggerFolder, "version.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "configuration.mustache", swaggerFolder, "configuration.rb"));
String swaggerFolder = baseFolder + File.separator + "swagger";
supportingFiles.add(new SupportingFile("swagger" + File.separator + "request.mustache", swaggerFolder, "request.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "response.mustache", swaggerFolder, "response.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "api_error.mustache", swaggerFolder, "api_error.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "version.mustache", swaggerFolder, "version.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "configuration.mustache", swaggerFolder, "configuration.rb"));
String modelFolder = baseFolder + File.separator + modelPackage.replace("/", File.separator);
supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb"));
}
@ -94,10 +133,17 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
/**
* Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client".
*/
public String generateModuleName() {
public String generateModuleName(String gemName) {
return camelize(gemName.replaceAll("[^\\w]+", "_"));
}
/**
* Generate Ruby gem name from the module name, e.g. use "swagger_client" for "SwaggerClient".
*/
public String generateGemName(String moduleName) {
return underscore(moduleName.replaceAll("[^\\w]+", ""));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -105,11 +151,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String apiFileFolder() {
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api";
return outputFolder + File.separator + libFolder + File.separator + gemName + File.separator + apiPackage.replace("/", File.separator);
}
public String modelFileFolder() {
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models";
return outputFolder + File.separator + libFolder + File.separator + gemName + File.separator + modelPackage.replace("/", File.separator);
}
@Override
@ -230,12 +276,23 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelImport(String name) {
return modelPackage() + "/" + toModelFilename(name);
return gemName + "/" + modelPackage() + "/" + toModelFilename(name);
}
@Override
public String toApiImport(String name) {
return apiPackage() + "/" + toApiFilename(name);
return gemName + "/" + apiPackage() + "/" + toApiFilename(name);
}
public void setGemName(String gemName) {
this.gemName = gemName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public void setGemVersion(String gemVersion) {
this.gemVersion = gemVersion;
}
}

View File

@ -0,0 +1,192 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage;
protected String groupId = "io.swagger";
protected String artifactId = "swagger-server";
protected String artifactVersion = "1.0.0";
public SilexServerCodegen() {
super();
invokerPackage = camelize("SwaggerServer");
String packagePath = "SwaggerServer";
modelPackage = packagePath + "/lib/models";
apiPackage = packagePath + "/lib";
outputFolder = "generated-code/silex";
// no model, api files
modelTemplateFiles.clear();
apiTemplateFiles.clear();
templateDir = "silex";
reservedWords = new HashSet<String>(
Arrays.asList(
"__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor")
);
additionalProperties.put("invokerPackage", invokerPackage);
additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
// ref: http://php.net/manual/en/language.types.intro.php
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"boolean",
"int",
"integer",
"double",
"float",
"string",
"object",
"DateTime",
"mixed",
"number")
);
instantiationTypes.put("array", "array");
instantiationTypes.put("map", "map");
// ref: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#data-types
typeMapping = new HashMap<String, String>();
typeMapping.put("integer", "int");
typeMapping.put("long", "int");
typeMapping.put("float", "float");
typeMapping.put("double", "double");
typeMapping.put("string", "string");
typeMapping.put("byte", "int");
typeMapping.put("boolean", "boolean");
typeMapping.put("date", "DateTime");
typeMapping.put("datetime", "DateTime");
typeMapping.put("file", "string");
typeMapping.put("map", "map");
typeMapping.put("array", "array");
typeMapping.put("list", "array");
typeMapping.put("object", "object");
supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', File.separatorChar), "README.md"));
supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', File.separatorChar), "composer.json"));
supportingFiles.add(new SupportingFile("index.mustache", packagePath.replace('/', File.separatorChar), "index.php"));
supportingFiles.add(new SupportingFile(".htaccess", packagePath.replace('/', File.separatorChar), ".htaccess"));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "silex";
}
public String getHelp() {
return "Generates a Silex server library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar);
}
public String modelFileFolder() {
return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
} else if (instantiationTypes.containsKey(type)) {
return type;
}
} else {
type = swaggerType;
}
if (type == null) {
return null;
}
return toModelName(type);
}
public String toDefaultValue(Property p) {
return "null";
}
@Override
public String toVarName(String name) {
// parameter name starting with number won't compile
// need to escape it by appending _ at the beginning
if (name.matches("^[0-9]")) {
name = "_" + name;
}
// return the name in underscore style
// PhoneNumber => phone_number
return underscore(name);
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword
if (reservedWords.contains(name)) {
escapeReservedWord(name); // e.g. return => _return
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
}

View File

@ -14,6 +14,7 @@ io.swagger.codegen.languages.RetrofitClientCodegen
io.swagger.codegen.languages.RubyClientCodegen
io.swagger.codegen.languages.ScalaClientCodegen
io.swagger.codegen.languages.ScalatraServerCodegen
io.swagger.codegen.languages.SilexServerCodegen
io.swagger.codegen.languages.SpringMVCServerCodegen
io.swagger.codegen.languages.StaticDocCodegen
io.swagger.codegen.languages.StaticHtmlGenerator

View File

@ -198,33 +198,53 @@ sub deserialize
{
my ($self, $class, $data) = @_;
$log->debugf("deserializing %s for %s", $data, $class);
my $_result;
if (not defined $data) {
return undef;
} elsif ( lc(substr($class, 0, 4)) eq 'map[') { #hash
$_result = \(json_decode $data);
} elsif ( lc(substr($class, 0, 6)) eq 'array[' ) { # array of data
} elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash
if ($class =~ /^HASH\[(.*),(.*)\]$/) {
my ($key_type, $type) = ($1, $2);
my %hash;
my $decoded_data = decode_json $data;
foreach my $key (keys %$decoded_data) {
if (ref $decoded_data->{$key} eq 'HASH') {
$hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key});
} else {
$hash{$key} = $self->deserialize($type, $decoded_data->{$key});
}
}
return \%hash;
} else {
#TODO log error
}
} elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data
return $data if $data eq '[]'; # return if empty array
my $_sub_class = substr($class, 6, -1);
my @_json_data = json_decode $data;
my $_json_data = decode_json $data;
my @_values = ();
foreach my $_value (@_json_data) {
push @_values, $self->deserialize($_sub_class, $_value);
foreach my $_value (@$_json_data) {
if (ref $_value eq 'ARRAY') {
push @_values, $self->deserialize($_sub_class, encode_json $_value);
} else {
push @_values, $self->deserialize($_sub_class, $_value);
}
}
$_result = \@_values;
return \@_values;
} elsif ($class eq 'DateTime') {
$_result = DateTime->from_epoch(epoch => str2time($data));
} elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { #TODO revise the primitive type
$_result= $data;
return DateTime->from_epoch(epoch => str2time($data));
} elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) {
return $data;
} else { # model
my $_instance = use_module("WWW::{{invokerPackage}}::Object::$class")->new;
$_result = $_instance->from_hash(decode_json $data);
my $_instance = use_module("WWW::SwaggerClient::Object::$class")->new;
if (ref $data eq "HASH") {
return $_instance->from_hash($data);
} else { # string, need to json decode first
return $_instance->from_hash(decode_json $data);
}
}
return $_result;
}
# return 'Accept' based on an array of accept provided

View File

@ -25,7 +25,7 @@ class ApiClient {
public static $PUT = "PUT";
public static $DELETE = "DELETE";
private static $default_header = array();
private $default_header = array();
/*
* @var string timeout (second) of the HTTP request, by default set to 0, no timeout
@ -58,7 +58,7 @@ class ApiClient {
if (!is_string($header_name))
throw new \InvalidArgumentException('Header name must be a string.');
self::$default_header[$header_name] = $header_value;
$this->default_header[$header_name] = $header_value;
}
/**
@ -67,7 +67,7 @@ class ApiClient {
* @return array default header
*/
public function getDefaultHeader() {
return self::$default_header;
return $this->default_header;
}
/**
@ -76,7 +76,7 @@ class ApiClient {
* @param string $header_name header name (e.g. Token)
*/
public function deleteDefaultHeader($header_name) {
unset(self::$default_header[$header_name]);
unset($this->default_header[$header_name]);
}
/**
@ -182,7 +182,7 @@ class ApiClient {
$this->updateParamsForAuth($headerParams, $queryParams, $authSettings);
# construct the http header
$headerParams = array_merge((array)self::$default_header, (array)$headerParams);
$headerParams = array_merge((array)$this->default_header, (array)$headerParams);
foreach ($headerParams as $key => $val) {
$headers[] = "$key: $val";
@ -307,8 +307,8 @@ class ApiClient {
* @param string $value a string which will be part of the path
* @return string the serialized object
*/
public static function toPathValue($value) {
return rawurlencode(self::toString($value));
public function toPathValue($value) {
return rawurlencode($this->toString($value));
}
/**
@ -319,11 +319,11 @@ class ApiClient {
* @param object $object an object to be serialized to a string
* @return string the serialized object
*/
public static function toQueryValue($object) {
public function toQueryValue($object) {
if (is_array($object)) {
return implode(',', $object);
} else {
return self::toString($object);
return $this->toString($object);
}
}
@ -334,8 +334,8 @@ class ApiClient {
* @param string $value a string which will be part of the header
* @return string the header string
*/
public static function toHeaderValue($value) {
return self::toString($value);
public function toHeaderValue($value) {
return $this->toString($value);
}
/**
@ -345,8 +345,8 @@ class ApiClient {
* @param string $value the value of the form parameter
* @return string the form string
*/
public static function toFormValue($value) {
return self::toString($value);
public function toFormValue($value) {
return $this->toString($value);
}
/**
@ -356,7 +356,7 @@ class ApiClient {
* @param string $value the value of the parameter
* @return string the header string
*/
public static function toString($value) {
public function toString($value) {
if ($value instanceof \DateTime) { // datetime in ISO8601 format
return $value->format(\DateTime::ISO8601);
}
@ -372,7 +372,7 @@ class ApiClient {
* @param string $class class name is passed as a string
* @return object an instance of $class
*/
public static function deserialize($data, $class)
public function deserialize($data, $class)
{
if (null === $data) {
$deserialized = null;
@ -383,14 +383,14 @@ class ApiClient {
$subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1];
foreach ($data as $key => $value) {
$deserialized[$key] = self::deserialize($value, $subClass);
$deserialized[$key] = $this->deserialize($value, $subClass);
}
}
} elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) {
$subClass = substr($class, 6, -1);
$values = array();
foreach ($data as $key => $value) {
$values[] = self::deserialize($value, $subClass);
$values[] = $this->deserialize($value, $subClass);
}
$deserialized = $values;
} elseif ($class == 'DateTime') {
@ -404,7 +404,7 @@ class ApiClient {
foreach ($instance::$swaggerTypes as $property => $type) {
$original_property_name = $instance::$attributeMap[$property];
if (isset($original_property_name) && isset($data->$original_property_name)) {
$instance->$property = self::deserialize($data->$original_property_name, $type);
$instance->$property = $this->deserialize($data->$original_property_name, $type);
}
}
$deserialized = $instance;
@ -419,7 +419,7 @@ class ApiClient {
* @param array[string] $accept Array of header
* @return string Accept (e.g. application/json)
*/
public static function selectHeaderAccept($accept) {
public function selectHeaderAccept($accept) {
if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) {
return NULL;
} elseif (preg_grep("/application\/json/i", $accept)) {
@ -435,7 +435,7 @@ class ApiClient {
* @param array[string] content_type_array Array fo content-type
* @return string Content-Type (e.g. application/json)
*/
public static function selectHeaderContentType($content_type) {
public function selectHeaderContentType($content_type) {
if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) {
return 'application/json';
} elseif (preg_grep("/application\/json/i", $content_type)) {

View File

@ -100,7 +100,7 @@ class {{classname}} {
}{{/pathParams}}
{{#formParams}}// form params
if (${{paramName}} !== null) {
$formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->toFormValue(${{paramName}});
$formParams['{{baseName}}'] = {{#isFile}}'@'.{{/isFile}}$this->apiClient->toFormValue(${{paramName}});
}{{/formParams}}
{{#bodyParams}}// body params
$_tempBody = null;

View File

@ -65,6 +65,14 @@ class {{classname}} implements ArrayAccess {
public function offsetUnset($offset) {
unset($this->$offset);
}
public function __toString() {
if (defined('JSON_PRETTY_PRINT')) {
return json_encode($this, JSON_PRETTY_PRINT);
} else {
return json_encode($this);
}
}
}
{{/model}}
{{/models}}

View File

@ -168,13 +168,20 @@ class ApiClient(object):
sub_class = match.group(1)
return [self.deserialize(sub_obj, sub_class) for sub_obj in obj]
if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']:
if 'dict(' in obj_class:
match = re.match('dict\((.*), (.*)\)', obj_class)
sub_class = match.group(2)
return {k: self.deserialize(v, sub_class) for k, v in iteritems(obj)}
if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime', "object"]:
obj_class = eval(obj_class)
else: # not a native type, must be model class
obj_class = eval('models.' + obj_class)
if obj_class in [int, float, dict, list, str, bool]:
return obj_class(obj)
elif obj_class == object:
return object()
elif obj_class == datetime:
return self.__parse_string_to_datetime(obj)

View File

@ -1,5 +1,5 @@
module {{moduleName}}
module Swagger
VERSION = "{{appVersion}}"
VERSION = "{{gemVersion}}"
end
end

View File

@ -8,7 +8,7 @@ require '{{gemName}}/swagger/response'
require '{{gemName}}/swagger/version'
# Models
require '{{modelPackage}}/base_object'
require '{{gemName}}/{{modelPackage}}/base_object'
{{#models}}
require '{{importPath}}'
{{/models}}

View File

@ -0,0 +1,5 @@
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

View File

@ -0,0 +1,10 @@
# Swagger generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the
[swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a PHP server.
This example uses the [Silex](http://silex.sensiolabs.org/) micro-framework. To see how to make this your own, please take a look at the template here:
[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/silex/)

View File

@ -0,0 +1,5 @@
{
"require": {
"silex/silex": "~1.2"
}
}

View File

@ -0,0 +1,26 @@
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Silex\Application;
$app = new Silex\Application();
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
$app->{{httpMethod}}('{{path}}', function(Application $app, Request $request{{#pathParams}}, ${{paramName}}{{/pathParams}}) {
{{#queryParams}}${{paramName}} = $request->get('{{paramName}}');{{newline}} {{/queryParams}}
{{#formParams}}${{paramName}} = $request->get('{{paramName}}');{{newline}} {{/formParams}}
return new Response('How about implementing {{nickname}} as a {{httpMethod}} method ?');
});
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
$app->run();

View File

@ -500,7 +500,7 @@ namespace IO.Swagger.Api {
// authentication setting, if any
String[] authSettings = new String[] { "petstore_auth", "api_key" };
String[] authSettings = new String[] { "api_key", "petstore_auth" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
@ -540,7 +540,7 @@ namespace IO.Swagger.Api {
// authentication setting, if any
String[] authSettings = new String[] { "petstore_auth", "api_key" };
String[] authSettings = new String[] { "api_key", "petstore_auth" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

View File

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDESourceControlProjectFavoriteDictionaryKey</key>
<false/>
<key>IDESourceControlProjectIdentifier</key>
<string>81EB09FA-DD8C-4FE1-82D3-1FB6FF0D9C43</string>
<key>IDESourceControlProjectName</key>
<string>PetstoreClient</string>
<key>IDESourceControlProjectOriginsDictionary</key>
<dict>
<key>E5BBF0AA85077C865C95437976D06D819733A208</key>
<string>ssh://github.com/wordnik/swagger-codegen.git</string>
</dict>
<key>IDESourceControlProjectPath</key>
<string>samples/client/petstore/objc/PetstoreClient.xcworkspace</string>
<key>IDESourceControlProjectRelativeInstallPathDictionary</key>
<dict>
<key>E5BBF0AA85077C865C95437976D06D819733A208</key>
<string>../../../../..</string>
</dict>
<key>IDESourceControlProjectURL</key>
<string>ssh://github.com/wordnik/swagger-codegen.git</string>
<key>IDESourceControlProjectVersion</key>
<integer>111</integer>
<key>IDESourceControlProjectWCCIdentifier</key>
<string>E5BBF0AA85077C865C95437976D06D819733A208</string>
<key>IDESourceControlProjectWCConfigurations</key>
<array>
<dict>
<key>IDESourceControlRepositoryExtensionIdentifierKey</key>
<string>public.vcs.git</string>
<key>IDESourceControlWCCIdentifierKey</key>
<string>E5BBF0AA85077C865C95437976D06D819733A208</string>
<key>IDESourceControlWCCName</key>
<string>swagger-codegen</string>
</dict>
</array>
</dict>
</plist>

View File

@ -1,5 +1,5 @@
platform :ios, '6.0'
xcodeproj 'swaggerClient/PetstoreClient.xcodeproj'
xcodeproj 'SwaggerClient/SwaggerClient.xcodeproj'
pod 'AFNetworking', '~> 2.1'
pod 'JSONModel', '~> 1.0'
pod 'ISO8601'

View File

@ -1,11 +1,11 @@
PODS:
- AFNetworking (2.5.4):
- AFNetworking/NSURLConnection
- AFNetworking/NSURLSession
- AFNetworking/Reachability
- AFNetworking/Security
- AFNetworking/Serialization
- AFNetworking/UIKit
- AFNetworking/NSURLConnection (= 2.5.4)
- AFNetworking/NSURLSession (= 2.5.4)
- AFNetworking/Reachability (= 2.5.4)
- AFNetworking/Security (= 2.5.4)
- AFNetworking/Serialization (= 2.5.4)
- AFNetworking/UIKit (= 2.5.4)
- AFNetworking/NSURLConnection (2.5.4):
- AFNetworking/Reachability
- AFNetworking/Security
@ -33,4 +33,4 @@ SPEC CHECKSUMS:
ISO8601: 8d8a22d5edf0554a1cf75bac028c76c1dc0ffaef
JSONModel: ec77e9865236a7a09d9cf7668df6b4b328d9ec1d
COCOAPODS: 0.33.1
COCOAPODS: 0.37.1

View File

@ -2,7 +2,7 @@
<Workspace
version = "1.0">
<FileRef
location = "group:PetstoreClient/PetstoreClient.xcodeproj">
location = "group:SwaggerClient/SwaggerClient.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">

View File

@ -63,14 +63,14 @@
CFD1B66E1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "JSONValueTransformer+ISO8601.h"; sourceTree = "<group>"; };
CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "JSONValueTransformer+ISO8601.m"; sourceTree = "<group>"; };
E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = "<group>"; };
EA6699961811D2FA00A70D03 /* PetstoreClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PetstoreClient.app; sourceTree = BUILT_PRODUCTS_DIR; };
EA6699961811D2FA00A70D03 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; };
EA6699991811D2FA00A70D03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
EA66999D1811D2FA00A70D03 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
EA6699A11811D2FA00A70D03 /* PetstoreClient-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "PetstoreClient-Info.plist"; sourceTree = "<group>"; };
EA6699A11811D2FA00A70D03 /* SwaggerClient-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "SwaggerClient-Info.plist"; sourceTree = "<group>"; };
EA6699A31811D2FA00A70D03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
EA6699A51811D2FA00A70D03 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
EA6699A71811D2FA00A70D03 /* PetstoreClient-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-Prefix.pch"; sourceTree = "<group>"; };
EA6699A71811D2FA00A70D03 /* SwaggerClient-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "SwaggerClient-Prefix.pch"; sourceTree = "<group>"; };
EA6699A81811D2FA00A70D03 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
EA6699A91811D2FA00A70D03 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
EA6699AC1811D2FA00A70D03 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main_iPhone.storyboard; sourceTree = "<group>"; };
@ -78,8 +78,8 @@
EA6699B11811D2FA00A70D03 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = "<group>"; };
EA6699B21811D2FA00A70D03 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = "<group>"; };
EA6699B41811D2FA00A70D03 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = "<group>"; };
EA6699BA1811D2FB00A70D03 /* PetstoreClientTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PetstoreClientTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
EA6699C31811D2FB00A70D03 /* PetstoreClientTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "PetstoreClientTests-Info.plist"; sourceTree = "<group>"; };
EA6699BA1811D2FB00A70D03 /* SwaggerClientTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwaggerClientTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
EA6699C31811D2FB00A70D03 /* SwaggerClientTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "SwaggerClientTests-Info.plist"; sourceTree = "<group>"; };
EA6699C51811D2FB00A70D03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
EA6699C71811D2FB00A70D03 /* PetApiTest.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PetApiTest.m; sourceTree = "<group>"; };
EA8B8AA21AC6683700638FBB /* SWGQueryParamCollection.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGQueryParamCollection.h; sourceTree = "<group>"; };
@ -151,8 +151,8 @@
isa = PBXGroup;
children = (
EAEA85CB1811D3AE00F06E69 /* client */,
EA66999F1811D2FA00A70D03 /* PetstoreClient */,
EA6699C11811D2FB00A70D03 /* PetstoreClientTests */,
EA66999F1811D2FA00A70D03 /* SwaggerClient */,
EA6699C11811D2FB00A70D03 /* SwaggerClientTests */,
EA6699981811D2FA00A70D03 /* Frameworks */,
EA6699971811D2FA00A70D03 /* Products */,
1A15B3DE4358A178ABAEC251 /* Pods */,
@ -162,8 +162,8 @@
EA6699971811D2FA00A70D03 /* Products */ = {
isa = PBXGroup;
children = (
EA6699961811D2FA00A70D03 /* PetstoreClient.app */,
EA6699BA1811D2FB00A70D03 /* PetstoreClientTests.xctest */,
EA6699961811D2FA00A70D03 /* SwaggerClient.app */,
EA6699BA1811D2FB00A70D03 /* SwaggerClientTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@ -181,7 +181,7 @@
name = Frameworks;
sourceTree = "<group>";
};
EA66999F1811D2FA00A70D03 /* PetstoreClient */ = {
EA66999F1811D2FA00A70D03 /* SwaggerClient */ = {
isa = PBXGroup;
children = (
EA6699A81811D2FA00A70D03 /* AppDelegate.h */,
@ -193,22 +193,22 @@
EA6699B41811D2FA00A70D03 /* Images.xcassets */,
EA6699A01811D2FA00A70D03 /* Supporting Files */,
);
path = PetstoreClient;
path = SwaggerClient;
sourceTree = "<group>";
};
EA6699A01811D2FA00A70D03 /* Supporting Files */ = {
isa = PBXGroup;
children = (
EAFBEABA1A925B8500A27431 /* test-1.png */,
EA6699A11811D2FA00A70D03 /* PetstoreClient-Info.plist */,
EA6699A11811D2FA00A70D03 /* SwaggerClient-Info.plist */,
EA6699A21811D2FA00A70D03 /* InfoPlist.strings */,
EA6699A51811D2FA00A70D03 /* main.m */,
EA6699A71811D2FA00A70D03 /* PetstoreClient-Prefix.pch */,
EA6699A71811D2FA00A70D03 /* SwaggerClient-Prefix.pch */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
EA6699C11811D2FB00A70D03 /* PetstoreClientTests */ = {
EA6699C11811D2FB00A70D03 /* SwaggerClientTests */ = {
isa = PBXGroup;
children = (
EA8CD3EB1AC274BE00C47D0B /* PetApiTest.h */,
@ -216,13 +216,13 @@
EA6699C71811D2FB00A70D03 /* PetApiTest.m */,
EA6699C21811D2FB00A70D03 /* Supporting Files */,
);
path = PetstoreClientTests;
path = SwaggerClientTests;
sourceTree = "<group>";
};
EA6699C21811D2FB00A70D03 /* Supporting Files */ = {
isa = PBXGroup;
children = (
EA6699C31811D2FB00A70D03 /* PetstoreClientTests-Info.plist */,
EA6699C31811D2FB00A70D03 /* SwaggerClientTests-Info.plist */,
EA6699C41811D2FB00A70D03 /* InfoPlist.strings */,
);
name = "Supporting Files";
@ -267,9 +267,9 @@
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
EA6699951811D2FA00A70D03 /* PetstoreClient */ = {
EA6699951811D2FA00A70D03 /* SwaggerClient */ = {
isa = PBXNativeTarget;
buildConfigurationList = EA6699CB1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClient" */;
buildConfigurationList = EA6699CB1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "SwaggerClient" */;
buildPhases = (
04DAA264FD78471BBAD25173 /* Check Pods Manifest.lock */,
EA6699921811D2FA00A70D03 /* Sources */,
@ -281,14 +281,14 @@
);
dependencies = (
);
name = PetstoreClient;
name = SwaggerClient;
productName = PetstoreClient;
productReference = EA6699961811D2FA00A70D03 /* PetstoreClient.app */;
productReference = EA6699961811D2FA00A70D03 /* SwaggerClient.app */;
productType = "com.apple.product-type.application";
};
EA6699B91811D2FB00A70D03 /* PetstoreClientTests */ = {
EA6699B91811D2FB00A70D03 /* SwaggerClientTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = EA6699CE1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */;
buildConfigurationList = EA6699CE1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */;
buildPhases = (
EA6699B61811D2FB00A70D03 /* Sources */,
EA6699B71811D2FB00A70D03 /* Frameworks */,
@ -299,9 +299,9 @@
dependencies = (
EA6699C01811D2FB00A70D03 /* PBXTargetDependency */,
);
name = PetstoreClientTests;
name = SwaggerClientTests;
productName = PetstoreClientTests;
productReference = EA6699BA1811D2FB00A70D03 /* PetstoreClientTests.xctest */;
productReference = EA6699BA1811D2FB00A70D03 /* SwaggerClientTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
@ -319,7 +319,7 @@
};
};
};
buildConfigurationList = EA6699911811D2FA00A70D03 /* Build configuration list for PBXProject "PetstoreClient" */;
buildConfigurationList = EA6699911811D2FA00A70D03 /* Build configuration list for PBXProject "SwaggerClient" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
@ -332,8 +332,8 @@
projectDirPath = "";
projectRoot = "";
targets = (
EA6699951811D2FA00A70D03 /* PetstoreClient */,
EA6699B91811D2FB00A70D03 /* PetstoreClientTests */,
EA6699951811D2FA00A70D03 /* SwaggerClient */,
EA6699B91811D2FB00A70D03 /* SwaggerClientTests */,
);
};
/* End PBXProject section */
@ -435,7 +435,7 @@
/* Begin PBXTargetDependency section */
EA6699C01811D2FB00A70D03 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = EA6699951811D2FA00A70D03 /* PetstoreClient */;
target = EA6699951811D2FA00A70D03 /* SwaggerClient */;
targetProxy = EA6699BF1811D2FB00A70D03 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
@ -557,13 +557,13 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch";
INFOPLIST_FILE = "PetstoreClient/PetstoreClient-Info.plist";
GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch";
INFOPLIST_FILE = "SwaggerClient/SwaggerClient-Info.plist";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"/Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/objc/Pods/../build/Debug-iphoneos",
);
PRODUCT_NAME = "$(TARGET_NAME)";
PRODUCT_NAME = SwaggerClient;
WRAPPER_EXTENSION = app;
};
name = Debug;
@ -575,13 +575,13 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch";
INFOPLIST_FILE = "PetstoreClient/PetstoreClient-Info.plist";
GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch";
INFOPLIST_FILE = "SwaggerClient/SwaggerClient-Info.plist";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"/Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/objc/Pods/../build/Debug-iphoneos",
);
PRODUCT_NAME = "$(TARGET_NAME)";
PRODUCT_NAME = SwaggerClient;
WRAPPER_EXTENSION = app;
};
name = Release;
@ -591,24 +591,24 @@
baseConfigurationReference = E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/PetstoreClient.app/PetstoreClient";
BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient";
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
"$(DEVELOPER_FRAMEWORKS_DIR)",
);
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch";
GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch";
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = "PetstoreClientTests/PetstoreClientTests-Info.plist";
INFOPLIST_FILE = "SwaggerClientTests/SwaggerClientTests-Info.plist";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"/Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/objc/Pods/../build/Debug-iphoneos",
);
PRODUCT_NAME = "$(TARGET_NAME)";
PRODUCT_NAME = SwaggerClientTests;
TEST_HOST = "$(BUNDLE_LOADER)";
WRAPPER_EXTENSION = xctest;
};
@ -619,20 +619,20 @@
baseConfigurationReference = A425648B5C0A4849C7668069 /* Pods.release.xcconfig */;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)";
BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/PetstoreClient.app/PetstoreClient";
BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/SwaggerClient.app/SwaggerClient";
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
"$(DEVELOPER_FRAMEWORKS_DIR)",
);
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch";
INFOPLIST_FILE = "PetstoreClientTests/PetstoreClientTests-Info.plist";
GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch";
INFOPLIST_FILE = "SwaggerClientTests/SwaggerClientTests-Info.plist";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"/Users/tony/dev/projects/swagger-api/swagger-codegen/samples/client/petstore/objc/Pods/../build/Debug-iphoneos",
);
PRODUCT_NAME = "$(TARGET_NAME)";
PRODUCT_NAME = SwaggerClientTests;
TEST_HOST = "$(BUNDLE_LOADER)";
WRAPPER_EXTENSION = xctest;
};
@ -641,7 +641,7 @@
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
EA6699911811D2FA00A70D03 /* Build configuration list for PBXProject "PetstoreClient" */ = {
EA6699911811D2FA00A70D03 /* Build configuration list for PBXProject "SwaggerClient" */ = {
isa = XCConfigurationList;
buildConfigurations = (
EA6699C91811D2FB00A70D03 /* Debug */,
@ -650,7 +650,7 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
EA6699CB1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = {
EA6699CB1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "SwaggerClient" */ = {
isa = XCConfigurationList;
buildConfigurations = (
EA6699CC1811D2FB00A70D03 /* Debug */,
@ -659,7 +659,7 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
EA6699CE1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */ = {
EA6699CE1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
EA6699CF1811D2FB00A70D03 /* Debug */,

View File

@ -15,9 +15,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EA6699951811D2FA00A70D03"
BuildableName = "PetstoreClient.app"
BlueprintName = "PetstoreClient"
ReferencedContainer = "container:PetstoreClient.xcodeproj">
BuildableName = "SwaggerClient.app"
BlueprintName = "SwaggerClient"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
@ -29,9 +29,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EA6699B91811D2FB00A70D03"
BuildableName = "PetstoreClientTests.xctest"
BlueprintName = "PetstoreClientTests"
ReferencedContainer = "container:PetstoreClient.xcodeproj">
BuildableName = "SwaggerClientTests.xctest"
BlueprintName = "SwaggerClientTests"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@ -47,9 +47,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EA6699B91811D2FB00A70D03"
BuildableName = "PetstoreClientTests.xctest"
BlueprintName = "PetstoreClientTests"
ReferencedContainer = "container:PetstoreClient.xcodeproj">
BuildableName = "SwaggerClientTests.xctest"
BlueprintName = "SwaggerClientTests"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
@ -57,9 +57,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EA6699951811D2FA00A70D03"
BuildableName = "PetstoreClient.app"
BlueprintName = "PetstoreClient"
ReferencedContainer = "container:PetstoreClient.xcodeproj">
BuildableName = "SwaggerClient.app"
BlueprintName = "SwaggerClient"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
@ -77,9 +77,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EA6699951811D2FA00A70D03"
BuildableName = "PetstoreClient.app"
BlueprintName = "PetstoreClient"
ReferencedContainer = "container:PetstoreClient.xcodeproj">
BuildableName = "SwaggerClient.app"
BlueprintName = "SwaggerClient"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
@ -96,9 +96,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "EA6699951811D2FA00A70D03"
BuildableName = "PetstoreClient.app"
BlueprintName = "PetstoreClient"
ReferencedContainer = "container:PetstoreClient.xcodeproj">
BuildableName = "SwaggerClient.app"
BlueprintName = "SwaggerClient"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>

View File

@ -4,7 +4,7 @@
<dict>
<key>SchemeUserState</key>
<dict>
<key>PetstoreClient.xcscheme</key>
<key>SwaggerClient.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>4</integer>

View File

Before

Width:  |  Height:  |  Size: 717 KiB

After

Width:  |  Height:  |  Size: 717 KiB

View File

@ -1,7 +1,7 @@
#import <Foundation/Foundation.h>
#import "SWGObject.h"
#import "SWGCategory.h"
#import "SWGTag.h"
#import "SWGCategory.h"
@protocol SWGPet

View File

@ -544,7 +544,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[@"petstore_auth", @"api_key"];
NSArray *authSettings = @[@"api_key", @"petstore_auth"];
id bodyDictionary = nil;

View File

@ -49,9 +49,9 @@
<executable>xcodebuild</executable>
<arguments>
<argument>-workspace</argument>
<argument>PetstoreClient.xcworkspace</argument>
<argument>SwaggerClient.xcworkspace</argument>
<argument>-scheme</argument>
<argument>PetstoreClient</argument>
<argument>SwaggerClient</argument>
<argument>test</argument>
<argument>-destination</argument>
<argument>platform=iOS Simulator,name=iPhone 6,OS=8.3</argument>

View File

@ -198,33 +198,53 @@ sub deserialize
{
my ($self, $class, $data) = @_;
$log->debugf("deserializing %s for %s", $data, $class);
my $_result;
if (not defined $data) {
return undef;
} elsif ( lc(substr($class, 0, 4)) eq 'map[') { #hash
$_result = \(json_decode $data);
} elsif ( lc(substr($class, 0, 6)) eq 'array[' ) { # array of data
} elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash
if ($class =~ /^HASH\[(.*),(.*)\]$/) {
my ($key_type, $type) = ($1, $2);
my %hash;
my $decoded_data = decode_json $data;
foreach my $key (keys %$decoded_data) {
if (ref $decoded_data->{$key} eq 'HASH') {
$hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key});
} else {
$hash{$key} = $self->deserialize($type, $decoded_data->{$key});
}
}
return \%hash;
} else {
#TODO log error
}
} elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data
return $data if $data eq '[]'; # return if empty array
my $_sub_class = substr($class, 6, -1);
my @_json_data = json_decode $data;
my $_json_data = decode_json $data;
my @_values = ();
foreach my $_value (@_json_data) {
push @_values, $self->deserialize($_sub_class, $_value);
foreach my $_value (@$_json_data) {
if (ref $_value eq 'ARRAY') {
push @_values, $self->deserialize($_sub_class, encode_json $_value);
} else {
push @_values, $self->deserialize($_sub_class, $_value);
}
}
$_result = \@_values;
return \@_values;
} elsif ($class eq 'DateTime') {
$_result = DateTime->from_epoch(epoch => str2time($data));
} elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { #TODO revise the primitive type
$_result= $data;
return DateTime->from_epoch(epoch => str2time($data));
} elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) {
return $data;
} else { # model
my $_instance = use_module("WWW::SwaggerClient::Object::$class")->new;
$_result = $_instance->from_hash(decode_json $data);
if (ref $data eq "HASH") {
return $_instance->from_hash($data);
} else { # string, need to json decode first
return $_instance->from_hash(decode_json $data);
}
}
return $_result;
}
# return 'Accept' based on an array of accept provided

View File

@ -317,7 +317,7 @@ sub new {
# authentication setting, if any
my $auth_settings = ['petstore_auth', 'api_key'];
my $auth_settings = ['api_key', 'petstore_auth'];
# make the API Call
my $response = $self->{api_client}->call_api($_resource_path, $_method,

View File

@ -27,7 +27,7 @@
<version>1.2.1</version>
<executions>
<execution>
<id>Test::More</id>
<id>Test::More for Pet</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
@ -39,6 +39,19 @@
</arguments>
</configuration>
</execution>
<execution>
<id>Test::More for Store</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>perl</executable>
<arguments>
<argument>t/02_store_api.t</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>

View File

@ -0,0 +1,88 @@
use Test::More tests => 22;
use Test::Exception;
use lib 'lib';
use strict;
use warnings;
use JSON;
use_ok('WWW::SwaggerClient::StoreApi');
use_ok('WWW::SwaggerClient::ApiClient');
use_ok('WWW::SwaggerClient::Object::Pet');
use_ok('WWW::SwaggerClient::Object::Tag');
use_ok('WWW::SwaggerClient::Object::Category');
my $api_client = WWW::SwaggerClient::ApiClient->new();
my $store_api = WWW::SwaggerClient::StoreApi->new('api_client' => $api_client);
is $store_api->{api_client}->{base_url}, 'http://petstore.swagger.io/v2', 'get the default base URL from api client';
my $get_inventory_response = $store_api->get_inventory();
like ($get_inventory_response->{pending}, qr/^\d+$/, "pending is numeric");
like ($get_inventory_response->{sold}, qr/^\d+$/, "sold is numeric");
my $pet_json = <<JSON;
{
"pet": {
"id": 0,
"category": {
"id": 0,
"name": "string"
},
"name": "doggie",
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "tag string"
}
],
"status": "available"
}
}
JSON
is ref(decode_json $pet_json), "HASH", "the decoded json string is a hash";
is ref $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}, "WWW::SwaggerClient::Object::Pet", "get Pet object from hash";
is $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}->{name}, "doggie", "get the name of the Pet object";
is $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}->{category}->{name}, "string", "get the category name of the Pet object";
is ref $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}->{category}, "WWW::SwaggerClient::Object::Category", "get the Category the Pet object";
is ref $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}->{tags}[0], "WWW::SwaggerClient::Object::Tag", "get the Tag of the Pet object";
is $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}->{tags}[0]->{name}, "tag string", "get the Tag name of the Pet object";
my $array_json = <<JSON;
[
{
"id": 0,
"category": {
"id": 0,
"name": "string"
},
"name": "doggie",
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "tag string"
}
],
"status": "available"
}
]
JSON
is ref(decode_json $array_json), "ARRAY", "the decoded json string is an array";
is ref $api_client->deserialize("ARRAY[Pet]", $array_json)->[0], "WWW::SwaggerClient::Object::Pet", "get Pet object from hash";
is $api_client->deserialize("ARRAY[Pet]", $array_json)->[0]->{name}, "doggie", "get the name of the Pet object";
is $api_client->deserialize("ARRAY[Pet]", $array_json)->[0]->{category}->{name}, "string", "get the category name of the Pet object";
is ref $api_client->deserialize("ARRAY[Pet]", $array_json)->[0]->{category}, "WWW::SwaggerClient::Object::Category", "get the Category the Pet object";
is ref $api_client->deserialize("ARRAY[Pet]", $array_json)->[0]->{tags}->[0], "WWW::SwaggerClient::Object::Tag", "get the Tag[0] the Pet object";
is $api_client->deserialize("ARRAY[Pet]", $array_json)->[0]->{tags}->[0]->{name}, "tag string", "get the tag name the Pet object";

View File

@ -5,6 +5,7 @@ use lib 'lib';
use strict;
use warnings;
use WWW::SwaggerClient::PetApi;
use WWW::SwaggerClient::StoreApi;
use WWW::SwaggerClient::ApiClient;
use WWW::SwaggerClient::Configuration;
use WWW::SwaggerClient::Object::Pet;
@ -45,4 +46,30 @@ print "\nget_pet_by_id:".Dumper $api->get_pet_by_id(pet_id => $pet_id);
print "\nupdate_pet_with_form:".Dumper $api->update_pet_with_form(pet_id => $pet_id, name => 'test_name', status => 'test status');
print "\ndelete_pet:".Dumper $api->delete_pet(pet_id => $pet_id);
my $store_api = WWW::SwaggerClient::StoreApi->new();
print "\nget_inventory:".Dumper $store_api->get_inventory();
my $pet_json = <<JSON;
{
"pet": {
"id": 0,
"category": {
"id": 0,
"name": "string"
},
"name": "doggie",
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "tag string"
}
],
"status": "available"
}
}
JSON
print "\napi_client->deserialize:".Dumper($api->{api_client}->deserialize("HASH[string,Pet]", $pet_json));

View File

@ -25,7 +25,7 @@ class ApiClient {
public static $PUT = "PUT";
public static $DELETE = "DELETE";
private static $default_header = array();
private $default_header = array();
/*
* @var string timeout (second) of the HTTP request, by default set to 0, no timeout
@ -58,7 +58,7 @@ class ApiClient {
if (!is_string($header_name))
throw new \InvalidArgumentException('Header name must be a string.');
self::$default_header[$header_name] = $header_value;
$this->default_header[$header_name] = $header_value;
}
/**
@ -67,7 +67,7 @@ class ApiClient {
* @return array default header
*/
public function getDefaultHeader() {
return self::$default_header;
return $this->default_header;
}
/**
@ -76,7 +76,7 @@ class ApiClient {
* @param string $header_name header name (e.g. Token)
*/
public function deleteDefaultHeader($header_name) {
unset(self::$default_header[$header_name]);
unset($this->default_header[$header_name]);
}
/**
@ -187,7 +187,7 @@ class ApiClient {
$this->updateParamsForAuth($headerParams, $queryParams, $authSettings);
# construct the http header
$headerParams = array_merge((array)self::$default_header, (array)$headerParams);
$headerParams = array_merge((array)$this->default_header, (array)$headerParams);
foreach ($headerParams as $key => $val) {
$headers[] = "$key: $val";
@ -312,8 +312,8 @@ class ApiClient {
* @param string $value a string which will be part of the path
* @return string the serialized object
*/
public static function toPathValue($value) {
return rawurlencode(self::toString($value));
public function toPathValue($value) {
return rawurlencode($this->toString($value));
}
/**
@ -324,11 +324,11 @@ class ApiClient {
* @param object $object an object to be serialized to a string
* @return string the serialized object
*/
public static function toQueryValue($object) {
public function toQueryValue($object) {
if (is_array($object)) {
return implode(',', $object);
} else {
return self::toString($object);
return $this->toString($object);
}
}
@ -339,8 +339,8 @@ class ApiClient {
* @param string $value a string which will be part of the header
* @return string the header string
*/
public static function toHeaderValue($value) {
return self::toString($value);
public function toHeaderValue($value) {
return $this->toString($value);
}
/**
@ -350,8 +350,8 @@ class ApiClient {
* @param string $value the value of the form parameter
* @return string the form string
*/
public static function toFormValue($value) {
return self::toString($value);
public function toFormValue($value) {
return $this->toString($value);
}
/**
@ -361,7 +361,7 @@ class ApiClient {
* @param string $value the value of the parameter
* @return string the header string
*/
public static function toString($value) {
public function toString($value) {
if ($value instanceof \DateTime) { // datetime in ISO8601 format
return $value->format(\DateTime::ISO8601);
}
@ -377,7 +377,7 @@ class ApiClient {
* @param string $class class name is passed as a string
* @return object an instance of $class
*/
public static function deserialize($data, $class)
public function deserialize($data, $class)
{
if (null === $data) {
$deserialized = null;
@ -388,14 +388,14 @@ class ApiClient {
$subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1];
foreach ($data as $key => $value) {
$deserialized[$key] = self::deserialize($value, $subClass);
$deserialized[$key] = $this->deserialize($value, $subClass);
}
}
} elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) {
$subClass = substr($class, 6, -1);
$values = array();
foreach ($data as $key => $value) {
$values[] = self::deserialize($value, $subClass);
$values[] = $this->deserialize($value, $subClass);
}
$deserialized = $values;
} elseif ($class == 'DateTime') {
@ -409,7 +409,7 @@ class ApiClient {
foreach ($instance::$swaggerTypes as $property => $type) {
$original_property_name = $instance::$attributeMap[$property];
if (isset($original_property_name) && isset($data->$original_property_name)) {
$instance->$property = self::deserialize($data->$original_property_name, $type);
$instance->$property = $this->deserialize($data->$original_property_name, $type);
}
}
$deserialized = $instance;
@ -424,7 +424,7 @@ class ApiClient {
* @param array[string] $accept Array of header
* @return string Accept (e.g. application/json)
*/
public static function selectHeaderAccept($accept) {
public function selectHeaderAccept($accept) {
if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) {
return NULL;
} elseif (preg_grep("/application\/json/i", $accept)) {
@ -440,7 +440,7 @@ class ApiClient {
* @param array[string] content_type_array Array fo content-type
* @return string Content-Type (e.g. application/json)
*/
public static function selectHeaderContentType($content_type) {
public function selectHeaderContentType($content_type) {
if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) {
return 'application/json';
} elseif (preg_grep("/application\/json/i", $content_type)) {

View File

@ -327,7 +327,7 @@ class PetApi {
}
// authentication setting, if any
$authSettings = array('petstore_auth', 'api_key');
$authSettings = array('api_key', 'petstore_auth');
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
@ -516,7 +516,7 @@ class PetApi {
$formParams['additionalMetadata'] = $this->apiClient->toFormValue($additional_metadata);
}// form params
if ($file !== null) {
$formParams['file'] = '@' . $this->apiClient->toFormValue($file);
$formParams['file'] = '@'.$this->apiClient->toFormValue($file);
}

View File

@ -61,4 +61,12 @@ class Category implements ArrayAccess {
public function offsetUnset($offset) {
unset($this->$offset);
}
public function __toString() {
if (defined('JSON_PRETTY_PRINT')) {
return json_encode($this, JSON_PRETTY_PRINT);
} else {
return json_encode($this);
}
}
}

View File

@ -80,4 +80,12 @@ class Order implements ArrayAccess {
public function offsetUnset($offset) {
unset($this->$offset);
}
public function __toString() {
if (defined('JSON_PRETTY_PRINT')) {
return json_encode($this, JSON_PRETTY_PRINT);
} else {
return json_encode($this);
}
}
}

View File

@ -80,4 +80,12 @@ class Pet implements ArrayAccess {
public function offsetUnset($offset) {
unset($this->$offset);
}
public function __toString() {
if (defined('JSON_PRETTY_PRINT')) {
return json_encode($this, JSON_PRETTY_PRINT);
} else {
return json_encode($this);
}
}
}

View File

@ -61,4 +61,12 @@ class Tag implements ArrayAccess {
public function offsetUnset($offset) {
unset($this->$offset);
}
public function __toString() {
if (defined('JSON_PRETTY_PRINT')) {
return json_encode($this, JSON_PRETTY_PRINT);
} else {
return json_encode($this);
}
}
}

View File

@ -88,4 +88,12 @@ class User implements ArrayAccess {
public function offsetUnset($offset) {
unset($this->$offset);
}
public function __toString() {
if (defined('JSON_PRETTY_PRINT')) {
return json_encode($this, JSON_PRETTY_PRINT);
} else {
return json_encode($this);
}
}
}

View File

@ -7,6 +7,13 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
// add a new pet (id 10005) to ensure the pet object is available for all the tests
public static function setUpBeforeClass() {
// for error reporting (need to run with php5.3 to get no warning)
//ini_set('display_errors', 1);
//error_reporting(~0);
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
// enable debugging
//SwaggerClient\Configuration::$debug = true;
@ -38,25 +45,26 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
public function testApiClient()
{
// test selectHeaderAccept
$this->assertSame('application/json', SwaggerClient\ApiClient::selectHeaderAccept(array('application/xml','application/json')));
$this->assertSame(NULL, SwaggerClient\ApiClient::selectHeaderAccept(array()));
$this->assertSame('application/yaml,application/xml', SwaggerClient\ApiClient::selectHeaderAccept(array('application/yaml','application/xml')));
$api_client = new SwaggerClient\ApiClient();
$this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml','application/json')));
$this->assertSame(NULL, $api_client->selectHeaderAccept(array()));
$this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml','application/xml')));
// test selectHeaderContentType
$this->assertSame('application/json', SwaggerClient\ApiClient::selectHeaderContentType(array('application/xml','application/json')));
$this->assertSame('application/json', SwaggerClient\ApiClient::selectHeaderContentType(array()));
$this->assertSame('application/yaml,application/xml', SwaggerClient\ApiClient::selectHeaderContentType(array('application/yaml','application/xml')));
$this->assertSame('application/json', $api_client->selectHeaderContentType(array('application/xml','application/json')));
$this->assertSame('application/json', $api_client->selectHeaderContentType(array()));
$this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml')));
// test addDefaultHeader and getDefaultHeader
SwaggerClient\ApiClient::addDefaultHeader('test1', 'value1');
SwaggerClient\ApiClient::addDefaultHeader('test2', 200);
$defaultHeader = SwaggerClient\ApiClient::getDefaultHeader();
$api_client->addDefaultHeader('test1', 'value1');
$api_client->addDefaultHeader('test2', 200);
$defaultHeader = $api_client->getDefaultHeader();
$this->assertSame('value1', $defaultHeader['test1']);
$this->assertSame(200, $defaultHeader['test2']);
// test deleteDefaultHeader
SwaggerClient\ApiClient::deleteDefaultHeader('test2');
$defaultHeader = SwaggerClient\ApiClient::getDefaultHeader();
$api_client->deleteDefaultHeader('test2');
$defaultHeader = $api_client->getDefaultHeader();
$this->assertFalse(isset($defaultHeader['test2']));
$pet_api = new SwaggerClient\PetAPI();

View File

@ -0,0 +1,32 @@
<?php
require_once('SwaggerClient.php');
class StoreApiTest extends \PHPUnit_Framework_TestCase
{
// add a new pet (id 10005) to ensure the pet object is available for all the tests
public static function setUpBeforeClass() {
// for error reporting (need to run with php5.3 to get no warning)
//ini_set('display_errors', 1);
//error_reporting(~0);
}
// test get inventory
public function testGetInventory()
{
// initialize the API client
$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2');
$store_api = new SwaggerClient\StoreAPI($api_client);
// get inventory
$get_response = $store_api->getInventory();
$this->assertInternalType("int", $get_response['sold']);
$this->assertInternalType("int", $get_response['pending']);
}
}
?>

View File

@ -0,0 +1,32 @@
<?php
require_once('SwaggerClient.php');
class UserApiTest extends \PHPUnit_Framework_TestCase
{
// add a new pet (id 10005) to ensure the pet object is available for all the tests
public static function setUpBeforeClass() {
// for error reporting (need to run with php5.3 to get no warning)
//ini_set('display_errors', 1);
//error_reporting(~0);
}
// test login user
public function testLoginUser()
{
// initialize the API client
$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2');
$user_api = new SwaggerClient\UserAPI($api_client);
// login
$response = $user_api->loginUser("xxxxx", "yyyyyyyy");
$this->assertInternalType("string", $response);
$this->assertRegExp("/^logged in user session/", $response, "response string starts with 'logged in user session'");
}
}
?>

View File

@ -0,0 +1,5 @@
main: Contrib
title: php-coveralls
internal: yes
todo: yes
wipeout: yes

View File

@ -0,0 +1,31 @@
<?xml version="1.0"?>
<ruleset name="PHP">
<description>The coding standard for standard PHP application</description>
<exclude-pattern>*/img/*</exclude-pattern>
<exclude-pattern>*/images/*</exclude-pattern>
<exclude-pattern>*/less/*</exclude-pattern>
<exclude-pattern>*/css/*</exclude-pattern>
<exclude-pattern>*/js/*</exclude-pattern>
<exclude-pattern>*.html</exclude-pattern>
<exclude-pattern>*.twig</exclude-pattern>
<exclude-pattern>*.yml</exclude-pattern>
<exclude-pattern>*.xml</exclude-pattern>
<exclude-pattern>*.txt</exclude-pattern>
<exclude-pattern>*.less</exclude-pattern>
<exclude-pattern>*.css</exclude-pattern>
<exclude-pattern>*.js</exclude-pattern>
<exclude-pattern>*.jpg</exclude-pattern>
<exclude-pattern>*.jpeg</exclude-pattern>
<exclude-pattern>*.png</exclude-pattern>
<exclude-pattern>*.gif</exclude-pattern>
<!-- Include the whole PSR-2 standard -->
<rule ref="PSR2"/>
<rule ref="Generic.Files.LineLength">
<properties>
<property name="lineLimit" value="140"/>
<property name="absoluteLineLimit" value="0"/>
</properties>
</rule>
</ruleset>

View File

@ -0,0 +1,45 @@
<?xml version="1.0"?>
<ruleset name="My first PHPMD rule set"
xmlns="http://pmd.sf.net/ruleset/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0
http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:noNamespaceSchemaLocation="
http://pmd.sf.net/ruleset_xml_schema.xsd">
<description>My custom rule set that checks my code...</description>
<!-- Import the entire unused code rule set -->
<rule ref="rulesets/unusedcode.xml" />
<rule ref="rulesets/design.xml" />
<rule ref="rulesets/naming.xml">
<exclude name="ShortVariable"/>
<exclude name="LongVariable"/>
</rule>
<rule ref="rulesets/naming.xml/ShortVariable">
<properties>
<property name="minimum" value="2" />
</properties>
</rule>
<rule ref="rulesets/naming.xml/LongVariable">
<properties>
<property name="maximum" value="30" />
</properties>
</rule>
<rule ref="rulesets/codesize.xml">
<exclude name="TooManyMethods"/>
<exclude name="ExcessiveClassComplexity"/>
</rule>
<rule ref="rulesets/codesize.xml/TooManyMethods">
<properties>
<property name="maxmethods" value="20" />
</properties>
</rule>
<rule ref="rulesets/codesize.xml/ExcessiveClassComplexity">
<properties>
<property name="maximum" value="70" />
</properties>
</rule>
</ruleset>

View File

@ -2,6 +2,10 @@
//require_once('vendor/autoload.php');
require_once('SwaggerClient-php/SwaggerClient.php');
// show error reporting
//ini_set('display_errors', 1);
//error_reporting(~0);
// initialize the API client
//$api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2');
//$api_client->addDefaultHeader("test1", "value1");
@ -19,10 +23,8 @@ try {
$pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903");
// return Pet (model)
$response = $pet_api->getPetById($petId);
var_dump($response);
// test upload file (exception)
$upload_response = $pet_api->uploadFile($petId, "test meta", NULL);
// to test __toString()
print ($response);
// add pet (post json)
$new_pet_id = 10005;
@ -45,6 +47,9 @@ try {
// add a new pet (model)
$add_response = $pet_api->addPet($new_pet);
// test upload file (exception)
$upload_response = $pet_api->uploadFile($petId, "test meta", NULL);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
echo 'HTTP response headers: ', $e->getResponseHeaders(), "\n";

View File

@ -9,8 +9,8 @@ from .models.order import Order
# import apis into sdk package
from .apis.user_api import UserApi
from .apis.store_api import StoreApi
from .apis.pet_api import PetApi
from .apis.store_api import StoreApi
# import ApiClient
from .api_client import ApiClient

View File

@ -168,13 +168,20 @@ class ApiClient(object):
sub_class = match.group(1)
return [self.deserialize(sub_obj, sub_class) for sub_obj in obj]
if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']:
if 'dict(' in obj_class:
match = re.match('dict\((.*), (.*)\)', obj_class)
sub_class = match.group(2)
return {k: self.deserialize(v, sub_class) for k, v in iteritems(obj)}
if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime', "object"]:
obj_class = eval(obj_class)
else: # not a native type, must be model class
obj_class = eval('models.' + obj_class)
if obj_class in [int, float, dict, list, str, bool]:
return obj_class(obj)
elif obj_class == object:
return object()
elif obj_class == datetime:
return self.__parse_string_to_datetime(obj)

View File

@ -2,6 +2,6 @@ from __future__ import absolute_import
# import apis into api package
from .user_api import UserApi
from .store_api import StoreApi
from .pet_api import PetApi
from .store_api import StoreApi

View File

@ -298,7 +298,7 @@ class PetApi(object):
header_params['Content-Type'] = self.api_client.select_header_content_type([])
# Authentication setting
auth_settings = ['petstore_auth', 'api_key']
auth_settings = ['api_key', 'petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,

View File

@ -47,7 +47,7 @@ class StoreApi(object):
Returns a map of status codes to quantities
:return: map(String, int)
:return: dict(str, int)
"""
all_params = []
@ -86,7 +86,7 @@ class StoreApi(object):
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response='map(String, int)', auth_settings=auth_settings)
response='dict(str, int)', auth_settings=auth_settings)
return response

View File

@ -88,3 +88,46 @@ class ApiClientTests(unittest.TestCase):
content_types = []
content_type = self.api_client.select_header_content_type(content_types)
self.assertEqual(content_type, 'application/json')
def test_deserialize_to_dict(self):
# dict(str, Pet)
json = {
'pet': {
"id": 0,
"category": {
"id": 0,
"name": "string"
},
"name": "doggie",
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}
}
data = self.api_client.deserialize(json, 'dict(str, Pet)')
self.assertTrue(isinstance(data, dict))
self.assertTrue(isinstance(data['pet'], SwaggerPetstore.Pet))
# dict(str, int)
json = {
'integer': 1
}
data = self.api_client.deserialize(json, 'dict(str, int)')
self.assertTrue(isinstance(data, dict))
self.assertTrue(isinstance(data['integer'], int))
def test_deserialize_to_object(self):
data = self.api_client.deserialize("", "object")
self.assertTrue(type(data) == object)

View File

@ -0,0 +1,31 @@
# coding: utf-8
"""
Run the tests.
$ pip install nose (optional)
$ cd SwaggerPetstore-python
$ nosetests -v
"""
import os
import time
import unittest
import SwaggerPetstore
from SwaggerPetstore.rest import ApiException
class StoreApiTests(unittest.TestCase):
def setUp(self):
self.store_api = SwaggerPetstore.StoreApi()
def tearDown(self):
# sleep 1 sec between two every 2 tests
time.sleep(1)
def test_get_inventory(self):
data = self.store_api.get_inventory()
self.assertIsNotNone(data)
self.assertTrue(isinstance(data, dict))
self.assertItemsEqual(data.keys(), ['available', 'string', 'sold', 'pending', 'confused', 'active', 'na'])

View File

@ -0,0 +1,5 @@
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

View File

@ -0,0 +1,10 @@
# Swagger generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the
[swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a PHP server.
This example uses the [Silex](http://silex.sensiolabs.org/) micro-framework. To see how to make this your own, please take a look at the template here:
[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/silex/)

View File

@ -0,0 +1,5 @@
{
"require": {
"silex/silex": "~1.2"
}
}

View File

@ -0,0 +1,184 @@
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Silex\Application;
$app = new Silex\Application();
$app->POST('/user', function(Application $app, Request $request) {
return new Response('How about implementing createUser as a POST method ?');
});
$app->POST('/user/createWithArray', function(Application $app, Request $request) {
return new Response('How about implementing createUsersWithArrayInput as a POST method ?');
});
$app->POST('/user/createWithList', function(Application $app, Request $request) {
return new Response('How about implementing createUsersWithListInput as a POST method ?');
});
$app->GET('/user/login', function(Application $app, Request $request) {
$username = $request->get('username'); $password = $request->get('password');
return new Response('How about implementing loginUser as a GET method ?');
});
$app->GET('/user/logout', function(Application $app, Request $request) {
return new Response('How about implementing logoutUser as a GET method ?');
});
$app->GET('/user/{username}', function(Application $app, Request $request, $username) {
return new Response('How about implementing getUserByName as a GET method ?');
});
$app->PUT('/user/{username}', function(Application $app, Request $request, $username) {
return new Response('How about implementing updateUser as a PUT method ?');
});
$app->DELETE('/user/{username}', function(Application $app, Request $request, $username) {
return new Response('How about implementing deleteUser as a DELETE method ?');
});
$app->PUT('/pet', function(Application $app, Request $request) {
return new Response('How about implementing updatePet as a PUT method ?');
});
$app->POST('/pet', function(Application $app, Request $request) {
return new Response('How about implementing addPet as a POST method ?');
});
$app->GET('/pet/findByStatus', function(Application $app, Request $request) {
$status = $request->get('status');
return new Response('How about implementing findPetsByStatus as a GET method ?');
});
$app->GET('/pet/findByTags', function(Application $app, Request $request) {
$tags = $request->get('tags');
return new Response('How about implementing findPetsByTags as a GET method ?');
});
$app->GET('/pet/{petId}', function(Application $app, Request $request, $pet_id) {
return new Response('How about implementing getPetById as a GET method ?');
});
$app->POST('/pet/{petId}', function(Application $app, Request $request, $pet_id) {
$name = $request->get('name'); $status = $request->get('status');
return new Response('How about implementing updatePetWithForm as a POST method ?');
});
$app->DELETE('/pet/{petId}', function(Application $app, Request $request, $pet_id) {
return new Response('How about implementing deletePet as a DELETE method ?');
});
$app->POST('/pet/{petId}/uploadImage', function(Application $app, Request $request, $pet_id) {
$additional_metadata = $request->get('additional_metadata'); $file = $request->get('file');
return new Response('How about implementing uploadFile as a POST method ?');
});
$app->GET('/store/inventory', function(Application $app, Request $request) {
return new Response('How about implementing getInventory as a GET method ?');
});
$app->POST('/store/order', function(Application $app, Request $request) {
return new Response('How about implementing placeOrder as a POST method ?');
});
$app->GET('/store/order/{orderId}', function(Application $app, Request $request, $order_id) {
return new Response('How about implementing getOrderById as a GET method ?');
});
$app->DELETE('/store/order/{orderId}', function(Application $app, Request $request, $order_id) {
return new Response('How about implementing deleteOrder as a DELETE method ?');
});
$app->run();

View File

@ -0,0 +1,5 @@
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

View File

@ -0,0 +1,10 @@
# Swagger generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the
[swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
is an example of building a PHP server.
This example uses the [Silex](http://silex.sensiolabs.org/) micro-framework. To see how to make this your own, please take a look at the template here:
[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/silex/)

View File

@ -0,0 +1,5 @@
{
"require": {
"silex/silex": "~1.2"
}
}

View File

@ -0,0 +1,184 @@
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Silex\Application;
$app = new Silex\Application();
$app->POST('/user', function(Application $app, Request $request) {
return new Response('How about implementing createUser as a POST method ?');
});
$app->POST('/user/createWithArray', function(Application $app, Request $request) {
return new Response('How about implementing createUsersWithArrayInput as a POST method ?');
});
$app->POST('/user/createWithList', function(Application $app, Request $request) {
return new Response('How about implementing createUsersWithListInput as a POST method ?');
});
$app->GET('/user/login', function(Application $app, Request $request) {
$username = $request->get('username'); $password = $request->get('password');
return new Response('How about implementing loginUser as a GET method ?');
});
$app->GET('/user/logout', function(Application $app, Request $request) {
return new Response('How about implementing logoutUser as a GET method ?');
});
$app->GET('/user/{username}', function(Application $app, Request $request, $username) {
return new Response('How about implementing getUserByName as a GET method ?');
});
$app->PUT('/user/{username}', function(Application $app, Request $request, $username) {
return new Response('How about implementing updateUser as a PUT method ?');
});
$app->DELETE('/user/{username}', function(Application $app, Request $request, $username) {
return new Response('How about implementing deleteUser as a DELETE method ?');
});
$app->PUT('/pet', function(Application $app, Request $request) {
return new Response('How about implementing updatePet as a PUT method ?');
});
$app->POST('/pet', function(Application $app, Request $request) {
return new Response('How about implementing addPet as a POST method ?');
});
$app->GET('/pet/findByStatus', function(Application $app, Request $request) {
$status = $request->get('status');
return new Response('How about implementing findPetsByStatus as a GET method ?');
});
$app->GET('/pet/findByTags', function(Application $app, Request $request) {
$tags = $request->get('tags');
return new Response('How about implementing findPetsByTags as a GET method ?');
});
$app->GET('/pet/{petId}', function(Application $app, Request $request, $pet_id) {
return new Response('How about implementing getPetById as a GET method ?');
});
$app->POST('/pet/{petId}', function(Application $app, Request $request, $pet_id) {
$name = $request->get('name'); $status = $request->get('status');
return new Response('How about implementing updatePetWithForm as a POST method ?');
});
$app->DELETE('/pet/{petId}', function(Application $app, Request $request, $pet_id) {
return new Response('How about implementing deletePet as a DELETE method ?');
});
$app->POST('/pet/{petId}/uploadImage', function(Application $app, Request $request, $pet_id) {
$additional_metadata = $request->get('additional_metadata'); $file = $request->get('file');
return new Response('How about implementing uploadFile as a POST method ?');
});
$app->GET('/store/inventory', function(Application $app, Request $request) {
return new Response('How about implementing getInventory as a GET method ?');
});
$app->POST('/store/order', function(Application $app, Request $request) {
return new Response('How about implementing placeOrder as a POST method ?');
});
$app->GET('/store/order/{orderId}', function(Application $app, Request $request, $order_id) {
return new Response('How about implementing getOrderById as a GET method ?');
});
$app->DELETE('/store/order/{orderId}', function(Application $app, Request $request, $order_id) {
return new Response('How about implementing deleteOrder as a DELETE method ?');
});
$app->run();