src/Developer/ClientRegistration/V1/ObjectSerializer.php
<?php
/**
* This file is part of the trollandtoad/ebay-sdk-php package.
*
* MIT License
*
* Copyright (c) 2022 Brandon Clothier
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
declare(strict_types=1);
/**
* ObjectSerializer.
*
* PHP version ^7.2 || ^8.0
*
* @category Class
*
* @author OpenAPI Generator team
*
* @see https://openapi-generator.tech
*/
/**
* Developer Registration API.
*
* <span class=\"tablenote\"><b>Note:</b> The Client Registration API is not intended for use by developers who have previously registered for a Developer Account on the eBay platform.</span><br/>The Client Registration API provides Dynamic Client Registration for regulated Third Party Providers (TPPs) who are, or will be, engaged in financial transactions on behalf of individuals domiciled in the EU/UK. This is required by the EU's Second Payment Services Directive (PSD2) which requires all regulated Account Servicing Payment Service Providers (ASPSPs) to provide secure APIs to access account and payment services on behalf of account holders.<br/><br/>A successful registration response returns a <b>HTTP 201 Created</b> status code with a JSON payload [RFC7519] that includes registration information.
*
* The version of the OpenAPI document: v1.0.0
* Generated by: https://openapi-generator.tech
* OpenAPI Generator version: 5.4.0
*/
/**
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace TNT\Ebay\Developer\ClientRegistration\V1;
use GuzzleHttp\Psr7\Utils;
use TNT\Ebay\Developer\ClientRegistration\V1\Model\ModelInterface;
/**
* ObjectSerializer Class Doc Comment.
*
* @category Class
*
* @author OpenAPI Generator team
*
* @see https://openapi-generator.tech
*/
class ObjectSerializer
{
/** @var string */
private static $dateTimeFormat = \DateTime::ATOM;
/**
* Change the date format.
*
* @param string $format the new date format to use
*/
public static function setDateTimeFormat($format)
{
self::$dateTimeFormat = $format;
}
/**
* Serialize data.
*
* @param mixed $data the data to serialize
* @param string $type the OpenAPIToolsType of the data
* @param string $format the format of the OpenAPITools type of the data
*
* @return scalar|object|array|null serialized form of $data
*/
public static function sanitizeForSerialization($data, $type = null, $format = null)
{
if (\is_scalar($data) || $data === null) {
return $data;
}
if ($data instanceof \DateTime) {
return ($format === 'date') ? $data->format('Y-m-d') : $data->format(self::$dateTimeFormat);
}
if (\is_array($data)) {
foreach ($data as $property => $value) {
$data[$property] = self::sanitizeForSerialization($value);
}
return $data;
}
if (\is_object($data)) {
$values = [];
if ($data instanceof ModelInterface) {
$formats = $data::openAPIFormats();
foreach ($data::openAPITypes() as $property => $openAPIType) {
$getter = $data::getters()[$property];
$value = $data->$getter();
if ($value !== null && ! \in_array($openAPIType, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) {
$callable = [$openAPIType, 'getAllowableEnumValues'];
if (\is_callable($callable)) {
/** array $callable */
$allowedEnumTypes = $callable();
if (! \in_array($value, $allowedEnumTypes, true)) {
$imploded = implode("', '", $allowedEnumTypes);
throw new \InvalidArgumentException("Invalid value for enum '$openAPIType', must be one of: '$imploded'");
}
}
}
if ($value !== null) {
$values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $openAPIType, $formats[$property]);
}
}
} else {
foreach ($data as $property => $value) {
$values[$property] = self::sanitizeForSerialization($value);
}
}
return (object) $values;
}
return (string) $data;
}
/**
* Sanitize filename by removing path.
* e.g. ../../sun.gif becomes sun.gif.
*
* @param string $filename filename to be sanitized
*
* @return string the sanitized filename
*/
public static function sanitizeFilename($filename)
{
if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) {
return $match[1];
}
return $filename;
}
/**
* Shorter timestamp microseconds to 6 digits length.
*
* @param string $timestamp Original timestamp
*
* @return string the shorten timestamp
*/
public static function sanitizeTimestamp($timestamp)
{
if (! \is_string($timestamp)) {
return $timestamp;
}
return preg_replace('/(:\d{2}.\d{6})\d*/', '$1', $timestamp);
}
/**
* Take value and turn it into a string suitable for inclusion in
* the path, by url-encoding.
*
* @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));
}
/**
* Take query parameter properties and turn it into an array suitable for
* native http_build_query or GuzzleHttp\Psr7\Query::build.
*
* @param mixed $value Parameter value
* @param string $paramName Parameter name
* @param string $openApiType OpenAPIType eg. array or object
* @param string $style Parameter serialization style
* @param bool $explode Parameter explode option
*/
public static function toQueryValue(
$value,
string $paramName,
string $openApiType = 'string',
string $style = 'form',
bool $explode = true
): array {
// return empty string
if (empty($value)) {
return ["{$paramName}" => ''];
}
$query = [];
$value = (\in_array($openApiType, ['object', 'array'], true)) ? (array) $value : $value;
// since \GuzzleHttp\Psr7\Query::build fails with nested arrays
// need to flatten array first
$flattenArray = function ($arr, $name, &$result = []) use (&$flattenArray, $style, $explode) {
if (! \is_array($arr)) {
return $arr;
}
foreach ($arr as $k => $v) {
$prop = ($style === 'deepObject') ? $prop = "{$name}[{$k}]" : $k;
if (\is_array($v)) {
$flattenArray($v, $prop, $result);
} else {
if ($style !== 'deepObject' && ! $explode) {
// push key itself
$result[] = $prop;
}
$result[$prop] = $v;
}
}
return $result;
};
$value = $flattenArray($value, $paramName);
if ($openApiType === 'object' && ($style === 'deepObject' || $explode)) {
return $value;
}
// handle style in serializeCollection
$query[$paramName] = ($explode) ? $value : self::serializeCollection((array) $value, $style);
return $query;
}
/**
* Take value and turn it into a string suitable for inclusion in
* the header. If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601.
*
* @param string $value a string which will be part of the header
*
* @return string the header string
*/
public static function toHeaderValue($value)
{
$callable = [$value, 'toHeaderValue'];
if (\is_callable($callable)) {
return $callable();
}
return self::toString($value);
}
/**
* Take value and turn it into a string suitable for inclusion in
* the http body (form parameter). If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601.
*
* @param string|\SplFileObject $value the value of the form parameter
*
* @return string the form string
*/
public static function toFormValue($value)
{
if ($value instanceof \SplFileObject) {
return $value->getRealPath();
}
return self::toString($value);
}
/**
* Take value and turn it into a string suitable for inclusion in
* the parameter. If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601
* If it's a boolean, convert it to "true" or "false".
*
* @param string|bool|\DateTime $value the value of the parameter
*
* @return string the header string
*/
public static function toString($value)
{
if ($value instanceof \DateTime) { // datetime in ISO8601 format
return $value->format(self::$dateTimeFormat);
}
if (\is_bool($value)) {
return $value ? 'true' : 'false';
}
return $value;
}
/**
* Serialize an array to a string.
*
* @param array $collection collection to serialize to a string
* @param string $style the format use for serialization (csv,
* ssv, tsv, pipes, multi)
* @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array
*
* @return string
*/
public static function serializeCollection(array $collection, $style, $allowCollectionFormatMulti = false)
{
if ($allowCollectionFormatMulti && ('multi' === $style)) {
// http_build_query() almost does the job for us. We just
// need to fix the result of multidimensional arrays.
return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&'));
}
switch ($style) {
case 'pipeDelimited':
case 'pipes':
return implode('|', $collection);
case 'tsv':
return implode("\t", $collection);
case 'spaceDelimited':
case 'ssv':
return implode(' ', $collection);
case 'simple':
case 'csv':
// Deliberate fall through. CSV is default format.
default:
return implode(',', $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
*
* @return object|array|null a single or an array of $class instances
*/
public static function deserialize($data, $class, $httpHeaders = null)
{
if ($data === null) {
return null;
}
if (strcasecmp(mb_substr($class, -2), '[]') === 0) {
$data = \is_string($data) ? json_decode($data) : $data;
if (! \is_array($data)) {
throw new \InvalidArgumentException("Invalid array '$class'");
}
$subClass = mb_substr($class, 0, -2);
$values = [];
foreach ($data as $key => $value) {
$values[] = self::deserialize($value, $subClass, null);
}
return $values;
}
// For associative array e.g. array<string,int>
if (preg_match('/^(array<|map\[)/', $class)) {
$data = \is_string($data) ? json_decode($data) : $data;
$data = (array) $data;
$inner = mb_substr($class, 4, -1);
$deserialized = [];
if (mb_strrpos($inner, ',') !== false) {
$subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1];
foreach ($data as $key => $value) {
$deserialized[$key] = self::deserialize($value, $subClass, null);
}
}
return $deserialized;
}
if ($class === 'object') {
return (array) $data;
}
if ($class === 'mixed') {
settype($data, gettype($data));
return $data;
}
if ($class === '\DateTime') {
// Some API's return an invalid, empty string as a
// date-time property. DateTime::__construct() will return
// the current time for empty input which is probably not
// what is meant. The invalid empty string is probably to
// be interpreted as a missing field/value. Let's handle
// this graceful.
if (! empty($data)) {
try {
return new \DateTime($data);
} catch (\Exception $exception) {
// Some API's return a date-time with too high nanosecond
// precision for php's DateTime to handle.
// With provided regexp 6 digits of microseconds saved
return new \DateTime(self::sanitizeTimestamp($data));
}
} else {
return null;
}
}
if ($class === '\SplFileObject') {
/** @var \Psr\Http\Message\StreamInterface $data */
$data = Utils::streamFor($data);
// Determine file name
if (
\is_array($httpHeaders)
&& \array_key_exists('Content-Disposition', $httpHeaders)
&& preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)
) {
$filename = Configuration::getDefaultConfiguration()->getTempFolderPath().DIRECTORY_SEPARATOR.self::sanitizeFilename($match[1]);
} else {
$filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), '');
}
$file = fopen($filename, 'wb');
while ($chunk = $data->read(200)) {
fwrite($file, $chunk);
}
fclose($file);
return new \SplFileObject($filename, 'r');
}
/** @psalm-suppress ParadoxicalCondition */
if (\in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) {
settype($data, $class);
return $data;
}
if (method_exists($class, 'getAllowableEnumValues')) {
if (! \in_array($data, $class::getAllowableEnumValues(), true)) {
$imploded = implode("', '", $class::getAllowableEnumValues());
throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'");
}
return $data;
}
$data = \is_string($data) ? json_decode($data) : $data;
// If a discriminator is defined and points to a valid subclass, use it.
$discriminator = $class::DISCRIMINATOR;
if (! empty($discriminator) && isset($data->{$discriminator}) && \is_string($data->{$discriminator})) {
$subclass = '\TNT\Ebay\Developer\ClientRegistration\V1\Model\\'.$data->{$discriminator};
if (is_subclass_of($subclass, $class)) {
$class = $subclass;
}
}
/** @var ModelInterface $instance */
$instance = new $class();
foreach ($instance::openAPITypes() as $property => $type) {
$propertySetter = $instance::setters()[$property];
if (! isset($propertySetter, $data->{$instance::attributeMap()[$property]})) {
continue;
}
if (isset($data->{$instance::attributeMap()[$property]})) {
$propertyValue = $data->{$instance::attributeMap()[$property]};
$instance->$propertySetter(self::deserialize($propertyValue, $type, null));
}
}
return $instance;
}
/**
* Native `http_build_query` wrapper.
*
* @see https://www.php.net/manual/en/function.http-build-query
*
* @param array|object $data may be an array or object containing properties
* @param string $numeric_prefix if numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only
* @param string|null $arg_separator arg_separator.output is used to separate arguments but may be overridden by specifying this parameter.
* @param int $encoding_type Encoding type. By default, PHP_QUERY_RFC1738.
*/
public static function buildQuery(
$data,
string $numeric_prefix = '',
string $arg_separator = null,
int $encoding_type = \PHP_QUERY_RFC3986
): string {
return \GuzzleHttp\Psr7\Query::build($data, $encoding_type);
}
}