Skip to content

[PHP] addd binary support to response and body parameter #1891

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 15, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ public CodegenParameter copy() {
output.allowableValues = new HashMap<String, Object>(this.allowableValues);
}
output.vendorExtensions = this.vendorExtensions;
output.isBinary = this.isBinary;

return output;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1329,6 +1329,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation
cookieParams.add(p.copy());
} else if (param instanceof BodyParameter) {
p.isBodyParam = new Boolean(true);
p.isBinary = p.dataType.toLowerCase().startsWith("byte");
bodyParam = p;
bodyParams.add(p.copy());
} else if (param instanceof FormParameter) {
Expand Down Expand Up @@ -1422,7 +1423,7 @@ public CodegenResponse fromResponse(String responseCode, Response response) {
}
}
r.dataType = cm.datatype;
r.isBinary = cm.datatype.equals("byte[]");
r.isBinary = cm.datatype.toLowerCase().startsWith("byte");
if (cm.isContainer != null) {
r.simpleType = false;
r.containerType = cm.containerType;
Expand Down Expand Up @@ -1567,12 +1568,7 @@ public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
CodegenProperty cp = fromProperty("property", prop);
if (cp != null) {
p.dataType = cp.datatype;
if (p.dataType.equals("byte[]")) {
p.isBinary = true;
}
else {
p.isBinary = false;
}
p.isBinary = cp.datatype.toLowerCase().startsWith("byte");
}
}
} else if (model instanceof ArrayModel) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ public PhpClientCodegen() {
typeMapping.put("array", "array");
typeMapping.put("list", "array");
typeMapping.put("object", "object");
typeMapping.put("binary", "ByteArray");

cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ class ApiClient
throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null);
} elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) {
// return raw body if response is a file
if ($responseType == '\SplFileObject') {
if ($responseType == '\SplFileObject' || $responseType == 'ByteArray') {
return array($http_body, $response_info['http_code'], $http_header);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,8 @@ class ObjectSerializer
$values[] = $this->deserialize($value, $subClass);
}
$deserialized = $values;
} elseif ($class === 'ByteArray') { // byte array
$deserialized = unpack('C*', (string)$data);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I realize the mapped type is a technically a byte array but this seems more natural to return as a string. Even printing this data is complicated as it's an array of integers and PHP's pack cannot be called with an Array.

$string = "";
foreach($deserialized as $int) {
  $string = $string . pack("C", $int);
}

Compare with string returned:

echo $deserialized;

File operations also don't support this unpacked format either.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

} elseif ($class === '\DateTime') {
$deserialized = new \DateTime($data);
} elseif (in_array($class, array({{&primitives}}))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ use \{{invokerPackage}}\ObjectSerializer;
{{#bodyParams}}// body params
$_tempBody = null;
if (isset(${{paramName}})) {
$_tempBody = ${{paramName}};
{{^isBinary}}$_tempBody = ${{paramName}};{{/isBinary}}{{#isBinary}}$_tempBody = call_user_func_array('pack', array_merge(array('C*'), ${{paramName}}));{{/isBinary}}
}{{/bodyParams}}

// for model (json/xml)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
<Properties StartupItem="SwaggerClientTest.csproj">
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug" />
<MonoDevelop.Ide.Workbench ActiveDocument="TestPet.cs">
<MonoDevelop.Ide.Workbench ActiveDocument="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs">
<Files>
<File FileName="TestPet.cs" Line="182" Column="4" />
<File FileName="TestConfiguration.cs" Line="17" Column="7" />
<File FileName="TestPet.cs" Line="288" Column="11" />
<File FileName="TestConfiguration.cs" Line="1" Column="1" />
<File FileName="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs" Line="1" Column="1" />
<File FileName="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs" Line="1" Column="1" />
<File FileName="TestApiClient.cs" Line="1" Column="1" />
<File FileName="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs" Line="1" Column="1" />
</Files>
<Pads>
<Pad Id="MonoDevelop.NUnit.TestPad">
<State name="__root__">
<Node name="SwaggerClientTest" expanded="True">
<Node name="SwaggerClientTest" selected="True" />
<Node name="SwaggerClientTest" expanded="True">
<Node name="SwaggerClientTest" expanded="True">
<Node name="TestApiClient" expanded="True">
<Node name="TestApiClient" expanded="True" />
</Node>
</Node>
</Node>
</Node>
</State>
</Pad>
Expand All @@ -22,4 +29,4 @@
<BreakpointStore />
</MonoDevelop.Ide.DebuggingService.Breakpoints>
<MonoDevelop.Ide.DebuggingService.PinnedWatches />
</Properties>
</Properties>
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb
Expand Down
186 changes: 186 additions & 0 deletions samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -873,4 +873,190 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi
}
}

/**
* getPetByIdWithByteArray
*
* Fake endpoint to test byte array return by 'Find pet by ID'
*
* @param int $pet_id ID of pet that needs to be fetched (required)
* @return ByteArray
* @throws \Swagger\Client\ApiException on non-2xx response
*/
public function getPetByIdWithByteArray($pet_id)
{
list($response, $statusCode, $httpHeader) = $this->getPetByIdWithByteArrayWithHttpInfo ($pet_id);
return $response;
}


/**
* getPetByIdWithByteArrayWithHttpInfo
*
* Fake endpoint to test byte array return by 'Find pet by ID'
*
* @param int $pet_id ID of pet that needs to be fetched (required)
* @return Array of ByteArray, HTTP status code, HTTP response headers (array of strings)
* @throws \Swagger\Client\ApiException on non-2xx response
*/
public function getPetByIdWithByteArrayWithHttpInfo($pet_id)
{

// verify the required parameter 'pet_id' is set
if ($pet_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetByIdWithByteArray');
}

// parse inputs
$resourcePath = "/pet/{petId}?testing_byte_array=true";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array());



// path params

if ($pet_id !== null) {
$resourcePath = str_replace(
"{" . "petId" . "}",
$this->apiClient->getSerializer()->toPathValue($pet_id),
$resourcePath
);
}
// default format to json
$resourcePath = str_replace("{format}", "json", $resourcePath);




// for model (json/xml)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} elseif (count($formParams) > 0) {
$httpBody = $formParams; // for HTTP post (form)
}

// this endpoint requires API key authentication
$apiKey = $this->apiClient->getApiKeyWithPrefix('api_key');
if (strlen($apiKey) !== 0) {
$headerParams['api_key'] = $apiKey;
}


// make the API Call
try {
list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
$resourcePath, 'GET',
$queryParams, $httpBody,
$headerParams, 'ByteArray'
);

if (!$response) {
return array(null, $statusCode, $httpHeader);
}

return array($this->apiClient->getSerializer()->deserialize($response, 'ByteArray', $httpHeader), $statusCode, $httpHeader);

} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'ByteArray', $e->getResponseHeaders());
$e->setResponseObject($data);
break;
}

throw $e;
}
}

/**
* addPetUsingByteArray
*
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param ByteArray $body Pet object in the form of byte array (optional)
* @return void
* @throws \Swagger\Client\ApiException on non-2xx response
*/
public function addPetUsingByteArray($body = null)
{
list($response, $statusCode, $httpHeader) = $this->addPetUsingByteArrayWithHttpInfo ($body);
return $response;
}


/**
* addPetUsingByteArrayWithHttpInfo
*
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param ByteArray $body Pet object in the form of byte array (optional)
* @return Array of null, HTTP status code, HTTP response headers (array of strings)
* @throws \Swagger\Client\ApiException on non-2xx response
*/
public function addPetUsingByteArrayWithHttpInfo($body = null)
{


// parse inputs
$resourcePath = "/pet?testing_byte_array=true";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml'));




// default format to json
$resourcePath = str_replace("{format}", "json", $resourcePath);


// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = call_user_func_array('pack', array_merge(array('C*'), $body));
}

// for model (json/xml)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} elseif (count($formParams) > 0) {
$httpBody = $formParams; // for HTTP post (form)
}

// this endpoint requires OAuth (access token)
if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) {
$headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken();
}

// make the API Call
try {
list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
$resourcePath, 'POST',
$queryParams, $httpBody,
$headerParams
);

return array(null, $statusCode, $httpHeader);

} catch (ApiException $e) {
switch ($e->getCode()) {
}

throw $e;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header
throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null);
} elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) {
// return raw body if response is a file
if ($responseType == '\SplFileObject') {
if ($responseType == '\SplFileObject' || $responseType == 'ByteArray') {
return array($http_body, $response_info['http_code'], $http_header);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,8 @@ public function deserialize($data, $class, $httpHeaders=null)
$values[] = $this->deserialize($value, $subClass);
}
$deserialized = $values;
} elseif ($class === 'ByteArray') { // byte array
$deserialized = unpack('C*', (string)$data);
} elseif ($class === '\DateTime') {
$deserialized = new \DateTime($data);
} elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) {
Expand Down
Loading