From 1840ba64888b20a203f2cf824f565dcc11ce33f1 Mon Sep 17 00:00:00 2001 From: Orkun Date: Fri, 9 Aug 2024 11:56:06 +0300 Subject: [PATCH] refactor: new logic for serializer --- run_checks.php | 17 +- src/Api/FingerprintApi.php | 374 +++++++++++++----------------------- src/ObjectSerializer.php | 61 +++--- template/api.mustache | 90 +++------ test/FingerprintApiTest.php | 7 +- 5 files changed, 223 insertions(+), 326 deletions(-) diff --git a/run_checks.php b/run_checks.php index c676c1fb..689abfbe 100644 --- a/run_checks.php +++ b/run_checks.php @@ -43,6 +43,9 @@ 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())); @@ -50,7 +53,11 @@ } 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())); @@ -58,8 +65,11 @@ } $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())); @@ -67,8 +77,11 @@ })->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())); diff --git a/src/Api/FingerprintApi.php b/src/Api/FingerprintApi.php index fd799616..d0597565 100644 --- a/src/Api/FingerprintApi.php +++ b/src/Api/FingerprintApi.php @@ -117,70 +117,43 @@ public function getEvent(string $request_id): array throw $apiException; } - $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]; } catch (ApiException $e) { - try { - switch ($e->getCode()) { - case 200: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\EventResponse', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - - case 403: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\ErrorEvent403Response', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - - case 404: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\ErrorEvent404Response', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - } - - throw $e; - } catch (SerializationException $exception) { - $exception->setResponse($e->getResponseObject()); - - throw $exception; + /** @var ResponseInterface $response */ + $response = $e->getResponseObject(); + + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\EventResponse' + ); + $e->setResponseObject($data); + + break; + + case 403: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\ErrorEvent403Response' + ); + $e->setResponseObject($data); + + break; + + case 404: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\ErrorEvent404Response' + ); + $e->setResponseObject($data); + + break; } + + throw $e; } } @@ -190,6 +163,7 @@ public function getEvent(string $request_id): array * Get event by requestId * * @throws \InvalidArgumentException + * @throws SerializationException */ public function getEventAsync(string $request_id): PromiseInterface { @@ -215,71 +189,45 @@ function ($response) use ($returnType, $request) { throw $apiException; } - $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]; }, function ($e) { - try { - switch ($e->getCode()) { - case 200: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\EventResponse', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - - case 403: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\ErrorEvent403Response', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - - case 404: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\ErrorEvent404Response', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - } - - throw $e; - } catch (SerializationException $exception) { - $exception->setResponse($e->getResponseObject()); - - throw $e; + /** @var ResponseInterface $response */ + $response = $e->getResponseObject(); + + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\EventResponse' + ); + $e->setResponseObject($data); + + break; + + case 403: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\ErrorEvent403Response' + ); + $e->setResponseObject($data); + + break; + + case 404: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\ErrorEvent404Response' + ); + $e->setResponseObject($data); + + break; } + + throw $e; } ); } @@ -331,70 +279,43 @@ public function getVisits(string $visitor_id, ?string $request_id = null, ?strin throw $apiException; } - $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]; } catch (ApiException $e) { - try { - switch ($e->getCode()) { - case 200: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\Response', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - - case 403: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\ErrorVisits403', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - - case 429: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\ManyRequestsResponse', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - } - - throw $e; - } catch (SerializationException $exception) { - $exception->setResponse($e->getResponseObject()); - - throw $exception; + /** @var ResponseInterface $response */ + $response = $e->getResponseObject(); + + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\Response' + ); + $e->setResponseObject($data); + + break; + + case 403: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\ErrorVisits403' + ); + $e->setResponseObject($data); + + break; + + case 429: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\ManyRequestsResponse' + ); + $e->setResponseObject($data); + + break; } + + throw $e; } } @@ -404,6 +325,7 @@ public function getVisits(string $visitor_id, ?string $request_id = null, ?strin * Get visits by visitorId * * @throws \InvalidArgumentException + * @throws SerializationException */ public function getVisitsAsync(string $visitor_id, ?string $request_id = null, ?string $linked_id = null, ?int $limit = null, ?string $pagination_key = null, ?int $before = null): PromiseInterface { @@ -429,71 +351,45 @@ function ($response) use ($returnType, $request) { throw $apiException; } - $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]; }, function ($e) { - try { - switch ($e->getCode()) { - case 200: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\Response', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - - case 403: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\ErrorVisits403', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - - case 429: - /** @var ResponseInterface $response */ - $response = $e->getResponseObject(); - $responseBody = $response->getBody()->getContents(); - $response->getBody()->rewind(); - $data = ObjectSerializer::deserialize( - $responseBody, - '\Fingerprint\ServerAPI\Model\ManyRequestsResponse', - $response->getHeaders() - ); - $e->setResponseObject($data); - - break; - } - - throw $e; - } catch (SerializationException $exception) { - $exception->setResponse($e->getResponseObject()); - - throw $e; + /** @var ResponseInterface $response */ + $response = $e->getResponseObject(); + + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\Response' + ); + $e->setResponseObject($data); + + break; + + case 403: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\ErrorVisits403' + ); + $e->setResponseObject($data); + + break; + + case 429: + $data = ObjectSerializer::deserialize( + $response, + '\Fingerprint\ServerAPI\Model\ManyRequestsResponse' + ); + $e->setResponseObject($data); + + break; } + + throw $e; } ); } @@ -502,6 +398,7 @@ function ($e) { * Create request for operation 'getEvent'. * * @throws \InvalidArgumentException + * @throws SerializationException */ protected function getEventRequest(string $request_id): Request { @@ -566,6 +463,7 @@ protected function getEventRequest(string $request_id): Request * Create request for operation 'getVisits'. * * @throws \InvalidArgumentException + * @throws SerializationException */ protected function getVisitsRequest(string $visitor_id, ?string $request_id = null, ?string $linked_id = null, ?int $limit = null, ?string $pagination_key = null, ?int $before = null): Request { diff --git a/src/ObjectSerializer.php b/src/ObjectSerializer.php index adcb378a..1bed1992 100644 --- a/src/ObjectSerializer.php +++ b/src/ObjectSerializer.php @@ -30,6 +30,7 @@ namespace Fingerprint\ServerAPI; use DateTime; +use Psr\Http\Message\ResponseInterface; /** * ObjectSerializer Class Doc Comment. @@ -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; @@ -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); } } @@ -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; @@ -296,7 +325,7 @@ 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); @@ -304,7 +333,7 @@ public static function deserialize(mixed $data, string $class, ?array $httpHeade return $data; } - throw new SerializationException(); + throw new SerializationException($response); } elseif (method_exists($class, 'getAllowableEnumValues')) { if (!in_array($data, $class::getAllowableEnumValues())) { $imploded = implode("', '", $class::getAllowableEnumValues()); @@ -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); } } diff --git a/template/api.mustache b/template/api.mustache index 2b9556f2..3238a89d 100644 --- a/template/api.mustache +++ b/template/api.mustache @@ -111,15 +111,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}} @@ -128,30 +121,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; } } @@ -165,6 +150,7 @@ use \GuzzleHttp\Exception\GuzzleException; {{/description}} * * @throws \InvalidArgumentException + * @throws SerializationException */ public function {{operationId}}Async({{#parameters}}{{dataType}} ${{paramName}}{{^required}} = {{#defaultValue}}'{{{.}}}'{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/parameters}}): \GuzzleHttp\Promise\PromiseInterface { @@ -190,15 +176,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}} @@ -207,30 +186,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; } ); } @@ -240,6 +211,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 { diff --git a/test/FingerprintApiTest.php b/test/FingerprintApiTest.php index 3ee91f78..e498b7d7 100644 --- a/test/FingerprintApiTest.php +++ b/test/FingerprintApiTest.php @@ -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); } @@ -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); }