Skip to content
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

refactor: introduce async method and wip inline types #100

Merged
merged 15 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
17 changes: 15 additions & 2 deletions run_checks.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,32 +43,45 @@

try {
list($result, $response) = $client->getVisits($visitor_id);
if($result->getVisitorId() !== $visitor_id) {
throw new Exception('Argument visitorId is not equal to deserialized getVisitorId');
}
fwrite(STDOUT, sprintf("Got visits: %s \n", $response->getBody()->getContents()));
} catch (Exception $e) {
fwrite(STDERR, sprintf("Exception when calling FingerprintApi->getVisits: %s\n", $e->getMessage()));
exit(1);
}

try {
/** @var $result \Fingerprint\ServerAPI\Model\EventResponse */
list($result, $response) = $client->getEvent($request_id);
if($result->getProducts()->getIdentification()->getData()->getRequestId() !== $request_id) {
throw new Exception('Argument requestId is not equal to deserialized getRequestId');
}
fwrite(STDOUT, sprintf("\n\nGot event: %s \n", $response->getBody()->getContents()));
} catch (Exception $e) {
fwrite(STDERR, sprintf("\n\nException when calling FingerprintApi->getVisits: %s\n", $e->getMessage()));
exit(1);
}

$eventPromise = $client->getEventAsync($request_id);
$eventPromise->then(function ($tuple) {
$eventPromise->then(function ($tuple) use($request_id) {
list($result, $response) = $tuple;
if($result->getProducts()->getIdentification()->getData()->getRequestId() !== $request_id) {
throw new Exception('Argument requestId is not equal to deserialized getRequestId');
}
fwrite(STDOUT, sprintf("\n\nGot async event: %s \n", $response->getBody()->getContents()));
}, function($exception) {
fwrite(STDERR, sprintf("\n\nException when calling FingerprintApi->getVisits: %s\n", $exception->getMessage()));
exit(1);
})->wait();

$visitsPromise = $client->getVisitsAsync($visitor_id);
$visitsPromise->then(function($tuple) {
$visitsPromise->then(function($tuple) use($visitor_id) {
list($result, $response) = $tuple;
if($result->getVisitorId() !== $visitor_id) {
throw new Exception('Argument visitorId is not equal to deserialized getVisitorId');
}
fwrite(STDOUT, sprintf("\n\nGot async visits: %s \n", $response->getBody()->getContents()));
}, function ($exception) {
fwrite(STDERR, sprintf("\n\nException when calling FingerprintApi->getVisits: %s\n", $exception->getMessage()));
Expand Down
392 changes: 154 additions & 238 deletions src/Api/FingerprintApi.php

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions src/ApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ public function __construct(?string $message = '', ?int $code = 0)
parent::__construct($message, $code);
}

/**
* Sets the deseralized response object (during deserialization).
*/
public function setResponseObject(ResponseInterface $obj): void
{
$this->responseObject = $obj;
Expand Down
2 changes: 1 addition & 1 deletion src/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public function setApiKey(string $apiKeyIdentifier, string $key): self
*
* @return null|string API key or token
*/
public function getApiKey($apiKeyIdentifier): ?string
public function getApiKey(string $apiKeyIdentifier): ?string
{
return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null;
}
Expand Down
61 changes: 38 additions & 23 deletions src/ObjectSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
namespace Fingerprint\ServerAPI;

use DateTime;
use Psr\Http\Message\ResponseInterface;

/**
* ObjectSerializer Class Doc Comment.
Expand Down Expand Up @@ -226,13 +227,41 @@ public static function serializeCollection(array $collection, string $collection
/**
* Deserialize a JSON string into an object.
*
* @param mixed $data object or primitive to be deserialized
* @param string $class class name is passed as a string
* @param string[] $httpHeaders HTTP headers
* @param string $class class name is passed as a string
*
* @throws \Exception
*/
public static function deserialize(mixed $data, string $class, ?array $httpHeaders = null): mixed
public static function deserialize(ResponseInterface $response, string $class): mixed
{
$data = $response->getBody()->getContents();
$response->getBody()->rewind();

return self::mapToClass($data, $class, $response);
}

protected static function mapToClass(mixed $data, string $class, ResponseInterface $response): mixed
{
if ('string' === gettype($data)) {
$data = json_decode($data, false);
}
$instance = new $class();
foreach ($instance::swaggerTypes() as $property => $type) {
$propertySetter = $instance::setters()[$property];

if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) {
continue;
}

$propertyValue = $data->{$instance::attributeMap()[$property]};
if (isset($propertyValue)) {
$instance->{$propertySetter}(self::castData($propertyValue, $type, $response));
}
}

return $instance;
}

protected static function castData(mixed $data, string $class, ResponseInterface $response): mixed
{
if (null === $data) {
return null;
Expand All @@ -244,7 +273,7 @@ public static function deserialize(mixed $data, string $class, ?array $httpHeade
$subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1];
foreach ($data as $key => $value) {
$deserialized[$key] = self::deserialize($value, $subClass, null);
$deserialized[$key] = self::castData($value, $subClass, $response);
}
}

Expand All @@ -254,7 +283,7 @@ public static function deserialize(mixed $data, string $class, ?array $httpHeade
$subClass = substr($class, 0, -2);
$values = [];
foreach ($data as $key => $value) {
$values[] = self::deserialize($value, $subClass, null);
$values[] = self::castData($value, $subClass, $response);
}

return $values;
Expand Down Expand Up @@ -296,15 +325,15 @@ public static function deserialize(mixed $data, string $class, ?array $httpHeade
return (float) $originalData;
}
if ('string' === $normalizedClass && is_object($data)) {
throw new SerializationException();
throw new SerializationException($response);
}

settype($data, $class);
if (gettype($data) === $normalizedClass) {
return $data;
}

throw new SerializationException();
throw new SerializationException($response);
} elseif (method_exists($class, 'getAllowableEnumValues')) {
if (!in_array($data, $class::getAllowableEnumValues())) {
$imploded = implode("', '", $class::getAllowableEnumValues());
Expand All @@ -315,20 +344,6 @@ public static function deserialize(mixed $data, string $class, ?array $httpHeade
return $data;
}

$instance = new $class();
foreach ($instance::swaggerTypes() as $property => $type) {
$propertySetter = $instance::setters()[$property];

if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) {
continue;
}

$propertyValue = $data->{$instance::attributeMap()[$property]};
if (isset($propertyValue)) {
$instance->{$propertySetter}(self::deserialize($propertyValue, $type, null));
}
}

return $instance;
return self::mapToClass($data, $class, $response);
}
}
3 changes: 3 additions & 0 deletions template/ApiException.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ class ApiException extends Exception
}


/**
* Sets the deseralized response object (during deserialization)
*/
public function setResponseObject(ResponseInterface $obj): void
{
$this->responseObject = $obj;
Expand Down
2 changes: 1 addition & 1 deletion template/Configuration.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ class Configuration
*
* @return string|null API key or token
*/
public function getApiKey($apiKeyIdentifier): ?string
public function getApiKey(string $apiKeyIdentifier): ?string
{
return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null;
}
Expand Down
96 changes: 37 additions & 59 deletions template/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ use \GuzzleHttp\Exception\GuzzleException;
* {{.}}
*
{{/description}}
{{#parameters}}
* @param {{dataType}} ${{paramName}}{{#description}} {{{description}}}{{/description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/parameters}}
* @throws \InvalidArgumentException
* @throws SerializationException
* @throws GuzzleException
Expand Down Expand Up @@ -111,15 +114,8 @@ use \GuzzleHttp\Exception\GuzzleException;
}

{{#returnType}}
$responseBody = $response->getBody()->getContents();
$response->getBody()->rewind();

try {
$serialized = ObjectSerializer::deserialize($responseBody, $returnType, []);
} catch (SerializationException $e) {
$e->setResponse($response);
throw $e;
}
$serialized = ObjectSerializer::deserialize($response, $returnType);

return [$serialized, $response];
{{/returnType}}
Expand All @@ -128,30 +124,22 @@ use \GuzzleHttp\Exception\GuzzleException;
{{/returnType}}

} catch (ApiException $e) {
try {
switch ($e->getCode()) {
/** @var ResponseInterface $response */
$response = $e->getResponseObject();
switch ($e->getCode()) {
{{#responses}}
{{#dataType}}
{{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}}
/** @var ResponseInterface $response */
$response = $e->getResponseObject();
$responseBody = $response->getBody()->getContents();
$response->getBody()->rewind();
$data = ObjectSerializer::deserialize(
$responseBody,
'{{dataType}}',
$response->getHeaders()
);
$e->setResponseObject($data);
break;
{{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}}
$data = ObjectSerializer::deserialize(
$response,
'{{dataType}}'
);
$e->setResponseObject($data);
break;
{{/dataType}}
{{/responses}}
}
throw $e;
} catch(SerializationException $exception) {
$exception->setResponse($e->getResponseObject());
throw $exception;
}
throw $e;
}
}

Expand All @@ -163,8 +151,12 @@ use \GuzzleHttp\Exception\GuzzleException;
* {{.}}
*
{{/description}}
{{#parameters}}
* @param {{dataType}} ${{paramName}}{{#description}} {{{description}}}{{/description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/parameters}}
*
* @throws \InvalidArgumentException
* @throws SerializationException
*/
public function {{operationId}}Async({{#parameters}}{{dataType}} ${{paramName}}{{^required}} = {{#defaultValue}}'{{{.}}}'{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/parameters}}): \GuzzleHttp\Promise\PromiseInterface
{
Expand All @@ -190,15 +182,8 @@ use \GuzzleHttp\Exception\GuzzleException;
throw $apiException;
}
{{#returnType}}
$responseBody = $response->getBody()->getContents();
$response->getBody()->rewind();

try {
$serialized = ObjectSerializer::deserialize($responseBody, $returnType, []);
} catch (SerializationException $e) {
$e->setResponse($response);
throw $e;
}

$serialized = ObjectSerializer::deserialize($response, $returnType);

return [$serialized, $response];
{{/returnType}}
Expand All @@ -207,30 +192,22 @@ use \GuzzleHttp\Exception\GuzzleException;
{{/returnType}}
},
function ($e) {
try {
switch ($e->getCode()) {
{{#responses}}
{{#dataType}}
{{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}}
/** @var ResponseInterface $response */
$response = $e->getResponseObject();
$responseBody = $response->getBody()->getContents();
$response->getBody()->rewind();
$data = ObjectSerializer::deserialize(
$responseBody,
'{{dataType}}',
$response->getHeaders()
);
$e->setResponseObject($data);
break;
{{/dataType}}
{{/responses}}
}
throw $e;
} catch(SerializationException $exception) {
$exception->setResponse($e->getResponseObject());
throw $e;
/** @var ResponseInterface $response */
$response = $e->getResponseObject();
switch ($e->getCode()) {
{{#responses}}
{{#dataType}}
{{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}}
$data = ObjectSerializer::deserialize(
$response,
'{{dataType}}'
);
$e->setResponseObject($data);
break;
{{/dataType}}
{{/responses}}
}
throw $e;
}
);
}
Expand All @@ -240,6 +217,7 @@ use \GuzzleHttp\Exception\GuzzleException;
*
*
* @throws \InvalidArgumentException
* @throws SerializationException
*/
protected function {{operationId}}Request({{#parameters}}{{dataType}}{{^required}}|null{{/required}} ${{paramName}}{{^required}} = {{#defaultValue}}'{{{.}}}'{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/parameters}}): \GuzzleHttp\Psr7\Request
{
Expand Down
7 changes: 3 additions & 4 deletions test/FingerprintApiTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,10 @@ public function getEventWithHttpInfoMock($request_id): array
}

$file = file_get_contents(__DIR__ . "/mocks/$mock_name");
$events_mock_data = \GuzzleHttp\json_decode($file);
$response = new \GuzzleHttp\Psr7\Response(200, [], $file);

try {
$serialized = ObjectSerializer::deserialize($events_mock_data, EventResponse::class);
$serialized = ObjectSerializer::deserialize($response, EventResponse::class);
} catch (Exception $exception) {
throw new SerializationException($response, $exception);
}
Expand All @@ -113,9 +112,9 @@ public function getVisitsWithHttpInfoMock($visitor_id, $request_id = null, $link
$visits_mock_data->visits = array_slice($visits_mock_data->visits, 0, $limit);
}

$response = new \GuzzleHttp\Psr7\Response(200, [], $file);
$response = new \GuzzleHttp\Psr7\Response(200, [], json_encode($visits_mock_data));
try {
$serialized = ObjectSerializer::deserialize($visits_mock_data, Response::class);
$serialized = ObjectSerializer::deserialize($response, Response::class);
} catch (Exception $exception) {
throw new SerializationException($response, $exception);
}
Expand Down
Loading