<?php
/**
 * ContactsApi
 * PHP version 7.4
 *
 * @category Class
 * @package  SageOne
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * Sage Business Cloud Accounting - Accounts
 *
 * Documentation of the Sage Business Cloud Accounting API.
 *
 * The version of the OpenAPI document: 3.1
 * Generated by: https://openapi-generator.tech
 * OpenAPI Generator version: 6.0.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 SageOne\Api;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use SageOne\ApiException;
use SageOne\Configuration;
use SageOne\HeaderSelector;
use SageOne\ObjectSerializer;

/**
 * ContactsApi Class Doc Comment
 *
 * @category Class
 * @package  SageOne
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */
class ContactsApi
{
    /**
     * @var ClientInterface
     */
    protected $client;

    /**
     * @var Configuration
     */
    protected $config;

    /**
     * @var HeaderSelector
     */
    protected $headerSelector;

    /**
     * @var int Host index
     */
    protected $hostIndex;

    /**
     * @param ClientInterface $client
     * @param Configuration   $config
     * @param HeaderSelector  $selector
     * @param int             $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
     */
    public function __construct(
        ClientInterface $client = null,
        Configuration $config = null,
        HeaderSelector $selector = null,
        $hostIndex = 0
    ) {
        $this->client = $client ?: new Client();
        $this->config = $config ?: new Configuration();
        $this->headerSelector = $selector ?: new HeaderSelector();
        $this->hostIndex = $hostIndex;
    }

    /**
     * Set the host index
     *
     * @param int $hostIndex Host index (required)
     */
    public function setHostIndex($hostIndex): void
    {
        $this->hostIndex = $hostIndex;
    }

    /**
     * Get the host index
     *
     * @return int Host index
     */
    public function getHostIndex()
    {
        return $this->hostIndex;
    }

    /**
     * @return Configuration
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * Operation deleteContactsKey
     *
     * Deletes a Contact
     *
     * @param  string $key The Contact Key. (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return void
     */
    public function deleteContactsKey($key)
    {
        $this->deleteContactsKeyWithHttpInfo($key);
    }

    /**
     * Operation deleteContactsKeyWithHttpInfo
     *
     * Deletes a Contact
     *
     * @param  string $key The Contact Key. (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of null, HTTP status code, HTTP response headers (array of strings)
     */
    public function deleteContactsKeyWithHttpInfo($key)
    {
        $request = $this->deleteContactsKeyRequest($key);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return [null, $statusCode, $response->getHeaders()];

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

    /**
     * Operation deleteContactsKeyAsync
     *
     * Deletes a Contact
     *
     * @param  string $key The Contact Key. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function deleteContactsKeyAsync($key)
    {
        return $this->deleteContactsKeyAsyncWithHttpInfo($key)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation deleteContactsKeyAsyncWithHttpInfo
     *
     * Deletes a Contact
     *
     * @param  string $key The Contact Key. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function deleteContactsKeyAsyncWithHttpInfo($key)
    {
        $returnType = '';
        $request = $this->deleteContactsKeyRequest($key);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    return [null, $response->getStatusCode(), $response->getHeaders()];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'deleteContactsKey'
     *
     * @param  string $key The Contact Key. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function deleteContactsKeyRequest($key)
    {
        // verify the required parameter 'key' is set
        if ($key === null || (is_array($key) && count($key) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $key when calling deleteContactsKey'
            );
        }

        $resourcePath = '/contacts/{key}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($key !== null) {
            $resourcePath = str_replace(
                '{' . 'key' . '}',
                ObjectSerializer::toPathValue($key),
                $resourcePath
            );
        }


        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                []
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                [],
                []
            );
        }

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }


        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'DELETE',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation getContacts
     *
     * Returns all Contacts
     *
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Contacts changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Contacts deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  string $contact_type_id Use this to filter by contact type id (optional)
     * @param  bool $exclude_system Use this to filter out system entities, not applicable for transaction creation (optional)
     * @param  string $search Use this to filter by the contact name, company name or reference. (optional)
     * @param  string $email Use this to filter by the contact person email address. (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contacts (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contacts. (optional)
     * @param  int $items_per_page Returns the given number of Contacts per request. (optional, default to 20)
     * @param  int $page Go to specific page of Contacts (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Contacts (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\PagingContact
     */
    public function getContacts($updated_or_created_since = null, $deleted_since = null, $contact_type_id = null, $exclude_system = null, $search = null, $email = null, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        list($response) = $this->getContactsWithHttpInfo($updated_or_created_since, $deleted_since, $contact_type_id, $exclude_system, $search, $email, $nested_attributes, $show_balance, $show_legacy_id, $items_per_page, $page, $attributes);
        return $response;
    }

    /**
     * Operation getContactsWithHttpInfo
     *
     * Returns all Contacts
     *
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Contacts changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Contacts deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  string $contact_type_id Use this to filter by contact type id (optional)
     * @param  bool $exclude_system Use this to filter out system entities, not applicable for transaction creation (optional)
     * @param  string $search Use this to filter by the contact name, company name or reference. (optional)
     * @param  string $email Use this to filter by the contact person email address. (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contacts (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contacts. (optional)
     * @param  int $items_per_page Returns the given number of Contacts per request. (optional, default to 20)
     * @param  int $page Go to specific page of Contacts (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Contacts (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\PagingContact, HTTP status code, HTTP response headers (array of strings)
     */
    public function getContactsWithHttpInfo($updated_or_created_since = null, $deleted_since = null, $contact_type_id = null, $exclude_system = null, $search = null, $email = null, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        $request = $this->getContactsRequest($updated_or_created_since, $deleted_since, $contact_type_id, $exclude_system, $search, $email, $nested_attributes, $show_balance, $show_legacy_id, $items_per_page, $page, $attributes);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\SageOne\Model\PagingContact' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\PagingContact' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\SageOne\Model\PagingContact', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\SageOne\Model\PagingContact';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\SageOne\Model\PagingContact',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation getContactsAsync
     *
     * Returns all Contacts
     *
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Contacts changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Contacts deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  string $contact_type_id Use this to filter by contact type id (optional)
     * @param  bool $exclude_system Use this to filter out system entities, not applicable for transaction creation (optional)
     * @param  string $search Use this to filter by the contact name, company name or reference. (optional)
     * @param  string $email Use this to filter by the contact person email address. (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contacts (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contacts. (optional)
     * @param  int $items_per_page Returns the given number of Contacts per request. (optional, default to 20)
     * @param  int $page Go to specific page of Contacts (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Contacts (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getContactsAsync($updated_or_created_since = null, $deleted_since = null, $contact_type_id = null, $exclude_system = null, $search = null, $email = null, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        return $this->getContactsAsyncWithHttpInfo($updated_or_created_since, $deleted_since, $contact_type_id, $exclude_system, $search, $email, $nested_attributes, $show_balance, $show_legacy_id, $items_per_page, $page, $attributes)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getContactsAsyncWithHttpInfo
     *
     * Returns all Contacts
     *
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Contacts changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Contacts deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  string $contact_type_id Use this to filter by contact type id (optional)
     * @param  bool $exclude_system Use this to filter out system entities, not applicable for transaction creation (optional)
     * @param  string $search Use this to filter by the contact name, company name or reference. (optional)
     * @param  string $email Use this to filter by the contact person email address. (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contacts (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contacts. (optional)
     * @param  int $items_per_page Returns the given number of Contacts per request. (optional, default to 20)
     * @param  int $page Go to specific page of Contacts (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Contacts (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getContactsAsyncWithHttpInfo($updated_or_created_since = null, $deleted_since = null, $contact_type_id = null, $exclude_system = null, $search = null, $email = null, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        $returnType = '\SageOne\Model\PagingContact';
        $request = $this->getContactsRequest($updated_or_created_since, $deleted_since, $contact_type_id, $exclude_system, $search, $email, $nested_attributes, $show_balance, $show_legacy_id, $items_per_page, $page, $attributes);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'getContacts'
     *
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Contacts changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Contacts deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  string $contact_type_id Use this to filter by contact type id (optional)
     * @param  bool $exclude_system Use this to filter out system entities, not applicable for transaction creation (optional)
     * @param  string $search Use this to filter by the contact name, company name or reference. (optional)
     * @param  string $email Use this to filter by the contact person email address. (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contacts (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contacts. (optional)
     * @param  int $items_per_page Returns the given number of Contacts per request. (optional, default to 20)
     * @param  int $page Go to specific page of Contacts (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Contacts (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getContactsRequest($updated_or_created_since = null, $deleted_since = null, $contact_type_id = null, $exclude_system = null, $search = null, $email = null, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        if ($items_per_page !== null && $items_per_page > 200) {
            throw new \InvalidArgumentException('invalid value for "$items_per_page" when calling ContactsApi.getContacts, must be smaller than or equal to 200.');
        }
        if ($items_per_page !== null && $items_per_page < 1) {
            throw new \InvalidArgumentException('invalid value for "$items_per_page" when calling ContactsApi.getContacts, must be bigger than or equal to 1.');
        }


        $resourcePath = '/contacts';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $updated_or_created_since,
            'updated_or_created_since', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $deleted_since,
            'deleted_since', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $contact_type_id,
            'contact_type_id', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $exclude_system,
            'exclude_system', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $search,
            'search', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $email,
            'email', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $nested_attributes,
            'nested_attributes', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $show_balance,
            'show_balance', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $show_legacy_id,
            'show_legacy_id', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $items_per_page,
            'items_per_page', // param base name
            'integer', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $page,
            'page', // param base name
            'integer', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $attributes,
            'attributes', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);




        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                []
            );
        }

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }


        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'GET',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation getContactsKey
     *
     * Returns a Contact
     *
     * @param  string $key The Contact Key. (required)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contact (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contact. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Contact (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\Contact
     */
    public function getContactsKey($key, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $attributes = null)
    {
        list($response) = $this->getContactsKeyWithHttpInfo($key, $nested_attributes, $show_balance, $show_legacy_id, $attributes);
        return $response;
    }

    /**
     * Operation getContactsKeyWithHttpInfo
     *
     * Returns a Contact
     *
     * @param  string $key The Contact Key. (required)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contact (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contact. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Contact (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\Contact, HTTP status code, HTTP response headers (array of strings)
     */
    public function getContactsKeyWithHttpInfo($key, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $attributes = null)
    {
        $request = $this->getContactsKeyRequest($key, $nested_attributes, $show_balance, $show_legacy_id, $attributes);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\SageOne\Model\Contact' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\Contact' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\SageOne\Model\Contact', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\SageOne\Model\Contact';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\SageOne\Model\Contact',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation getContactsKeyAsync
     *
     * Returns a Contact
     *
     * @param  string $key The Contact Key. (required)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contact (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contact. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Contact (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getContactsKeyAsync($key, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $attributes = null)
    {
        return $this->getContactsKeyAsyncWithHttpInfo($key, $nested_attributes, $show_balance, $show_legacy_id, $attributes)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getContactsKeyAsyncWithHttpInfo
     *
     * Returns a Contact
     *
     * @param  string $key The Contact Key. (required)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contact (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contact. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Contact (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getContactsKeyAsyncWithHttpInfo($key, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $attributes = null)
    {
        $returnType = '\SageOne\Model\Contact';
        $request = $this->getContactsKeyRequest($key, $nested_attributes, $show_balance, $show_legacy_id, $attributes);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'getContactsKey'
     *
     * @param  string $key The Contact Key. (required)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Contact (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $show_balance Use this to display the balance for a contact. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Contact. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Contact (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getContactsKeyRequest($key, $nested_attributes = null, $show_balance = null, $show_legacy_id = null, $attributes = null)
    {
        // verify the required parameter 'key' is set
        if ($key === null || (is_array($key) && count($key) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $key when calling getContactsKey'
            );
        }

        $resourcePath = '/contacts/{key}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $nested_attributes,
            'nested_attributes', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $show_balance,
            'show_balance', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $show_legacy_id,
            'show_legacy_id', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $attributes,
            'attributes', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);


        // path params
        if ($key !== null) {
            $resourcePath = str_replace(
                '{' . 'key' . '}',
                ObjectSerializer::toPathValue($key),
                $resourcePath
            );
        }


        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                []
            );
        }

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }


        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'GET',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation postContacts
     *
     * Creates a Contact
     *
     * @param  \SageOne\Model\PostContacts $contacts contacts (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\Contact
     */
    public function postContacts($contacts)
    {
        list($response) = $this->postContactsWithHttpInfo($contacts);
        return $response;
    }

    /**
     * Operation postContactsWithHttpInfo
     *
     * Creates a Contact
     *
     * @param  \SageOne\Model\PostContacts $contacts (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\Contact, HTTP status code, HTTP response headers (array of strings)
     */
    public function postContactsWithHttpInfo($contacts)
    {
        $request = $this->postContactsRequest($contacts);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            switch($statusCode) {
                case 201:
                    if ('\SageOne\Model\Contact' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\Contact' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\SageOne\Model\Contact', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\SageOne\Model\Contact';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 201:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\SageOne\Model\Contact',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation postContactsAsync
     *
     * Creates a Contact
     *
     * @param  \SageOne\Model\PostContacts $contacts (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function postContactsAsync($contacts)
    {
        return $this->postContactsAsyncWithHttpInfo($contacts)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation postContactsAsyncWithHttpInfo
     *
     * Creates a Contact
     *
     * @param  \SageOne\Model\PostContacts $contacts (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function postContactsAsyncWithHttpInfo($contacts)
    {
        $returnType = '\SageOne\Model\Contact';
        $request = $this->postContactsRequest($contacts);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'postContacts'
     *
     * @param  \SageOne\Model\PostContacts $contacts (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function postContactsRequest($contacts)
    {
        // verify the required parameter 'contacts' is set
        if ($contacts === null || (is_array($contacts) && count($contacts) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $contacts when calling postContacts'
            );
        }

        $resourcePath = '/contacts';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;





        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                ['application/json']
            );
        }

        // for model (json/xml)
        if (isset($contacts)) {
            if ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($contacts));
            } else {
                $httpBody = $contacts;
            }
        } elseif (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }


        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'POST',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation putContactsKey
     *
     * Updates a Contact
     *
     * @param  string $key The Contact Key. (required)
     * @param  \SageOne\Model\PutContacts $contacts contacts (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\Contact
     */
    public function putContactsKey($key, $contacts)
    {
        list($response) = $this->putContactsKeyWithHttpInfo($key, $contacts);
        return $response;
    }

    /**
     * Operation putContactsKeyWithHttpInfo
     *
     * Updates a Contact
     *
     * @param  string $key The Contact Key. (required)
     * @param  \SageOne\Model\PutContacts $contacts (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\Contact, HTTP status code, HTTP response headers (array of strings)
     */
    public function putContactsKeyWithHttpInfo($key, $contacts)
    {
        $request = $this->putContactsKeyRequest($key, $contacts);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\SageOne\Model\Contact' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\Contact' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\SageOne\Model\Contact', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            $returnType = '\SageOne\Model\Contact';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\SageOne\Model\Contact',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation putContactsKeyAsync
     *
     * Updates a Contact
     *
     * @param  string $key The Contact Key. (required)
     * @param  \SageOne\Model\PutContacts $contacts (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function putContactsKeyAsync($key, $contacts)
    {
        return $this->putContactsKeyAsyncWithHttpInfo($key, $contacts)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation putContactsKeyAsyncWithHttpInfo
     *
     * Updates a Contact
     *
     * @param  string $key The Contact Key. (required)
     * @param  \SageOne\Model\PutContacts $contacts (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function putContactsKeyAsyncWithHttpInfo($key, $contacts)
    {
        $returnType = '\SageOne\Model\Contact';
        $request = $this->putContactsKeyRequest($key, $contacts);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ($returnType !== 'string') {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'putContactsKey'
     *
     * @param  string $key The Contact Key. (required)
     * @param  \SageOne\Model\PutContacts $contacts (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function putContactsKeyRequest($key, $contacts)
    {
        // verify the required parameter 'key' is set
        if ($key === null || (is_array($key) && count($key) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $key when calling putContactsKey'
            );
        }
        // verify the required parameter 'contacts' is set
        if ($contacts === null || (is_array($contacts) && count($contacts) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $contacts when calling putContactsKey'
            );
        }

        $resourcePath = '/contacts/{key}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($key !== null) {
            $resourcePath = str_replace(
                '{' . 'key' . '}',
                ObjectSerializer::toPathValue($key),
                $resourcePath
            );
        }


        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                ['application/json']
            );
        }

        // for model (json/xml)
        if (isset($contacts)) {
            if ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($contacts));
            } else {
                $httpBody = $contacts;
            }
        } elseif (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        }


        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'PUT',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Create http client option
     *
     * @throws \RuntimeException on file opening failure
     * @return array of http client options
     */
    protected function createHttpClientOption()
    {
        $options = [];
        if ($this->config->getDebug()) {
            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
            if (!$options[RequestOptions::DEBUG]) {
                throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
            }
        }

        return $options;
    }
}
