<?php
/**
 * FileattachmentsAttachmentApi
 * PHP version 8.1
 *
 * @category Class
 * @package  Fortnox
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * Fortnox API
 *
 * # Documentation   The Fortnox API is organized around REST. This means that we’ve designed it to have resource-oriented URLs and be as predictable as possible for you as developer.  It also means that we use HTTP status codes when something goes wrong and HTTP verbs understod by many API clients around the web.  We use a modified version of OAuth2 for authentication to offer a secure way for both you and our users to interact.  The API is generally built to support both XML and JSON but in this documentation all the examples will be in JSON.  We encourage you to read all the articles in the [Guides & Good to Know section](https://www.fortnox.se/developer/guides-and-good-to-know/)</a> first, before going forward and learning about the different resources.  This to ensure you get an understanding of some of the shared components of the API such as parameters and error handling.  ## Rate limits  The limit per access-token is 25 requests per 5 seconds. This equals to 300 requests per minute.  [Read more about this here.](https://www.fortnox.se/developer/guides-and-good-to-know/rate-limits-for-fortnox-api/)  ## Query parameters  Use query parameters with the ?-character and separate parameters with the &-character.   **Example:**  GET - https://api.fortnox.se/3/invoices?accountnumberfrom=3000&accountnumberto=4000 Read more about our parameters [here](https://www.fortnox.se/developer/guides-and-good-to-know/parameters/)   Search the documentation using the search field in the top left corner.
 *
 * The version of the OpenAPI document: 
 * Generated by: https://openapi-generator.tech
 * Generator version: 7.19.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 Fortnox\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 Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Fortnox\ApiException;
use Fortnox\Configuration;
use Fortnox\FormDataProcessor;
use Fortnox\HeaderSelector;
use Fortnox\ObjectSerializer;

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

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

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

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

    /** @var string[] $contentTypes **/
    public const contentTypes = [
        'attach' => [
            'application/json',
        ],
        'detach' => [
            'application/json',
        ],
        'getAttachments' => [
            'application/json',
        ],
        'getNumberOfAttachmentsForEntity' => [
            'application/json',
        ],
        'updateAttachment' => [
            'application/json',
        ],
        'validateIncludedOnSend' => [
            'application/json',
        ],
    ];

    /**
     * @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,
        int $hostIndex = 0
    ) {
        $this->client = $client ?: new Client();
        $this->config = $config ?: Configuration::getDefaultConfiguration();
        $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 attach
     *
     * Attach files to one or more entities
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments A list of attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['attach'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Fortnox\Model\FileattachmentsAttachment|\Fortnox\Model\FileattachmentsWebException
     */
    public function attach($attachments = null, string $contentType = self::contentTypes['attach'][0])
    {
        list($response) = $this->attachWithHttpInfo($attachments, $contentType);
        return $response;
    }

    /**
     * Operation attachWithHttpInfo
     *
     * Attach files to one or more entities
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments A list of attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['attach'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Fortnox\Model\FileattachmentsAttachment|\Fortnox\Model\FileattachmentsWebException, HTTP status code, HTTP response headers (array of strings)
     */
    public function attachWithHttpInfo($attachments = null, string $contentType = self::contentTypes['attach'][0])
    {
        $request = $this->attachRequest($attachments, $contentType);

        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();


            switch($statusCode) {
                case 201:
                    return $this->handleResponseWithDataType(
                        '\Fortnox\Model\FileattachmentsAttachment',
                        $request,
                        $response,
                    );
                default:
                    return $this->handleResponseWithDataType(
                        '\Fortnox\Model\FileattachmentsWebException',
                        $request,
                        $response,
                    );
            }

            

            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 $this->handleResponseWithDataType(
                '\Fortnox\Model\FileattachmentsAttachment',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 201:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsAttachment',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                default:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsWebException',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation attachAsync
     *
     * Attach files to one or more entities
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments A list of attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['attach'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function attachAsync($attachments = null, string $contentType = self::contentTypes['attach'][0])
    {
        return $this->attachAsyncWithHttpInfo($attachments, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation attachAsyncWithHttpInfo
     *
     * Attach files to one or more entities
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments A list of attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['attach'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function attachAsyncWithHttpInfo($attachments = null, string $contentType = self::contentTypes['attach'][0])
    {
        $returnType = '\Fortnox\Model\FileattachmentsAttachment';
        $request = $this->attachRequest($attachments, $contentType);

        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 'attach'
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments A list of attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['attach'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function attachRequest($attachments = null, string $contentType = self::contentTypes['attach'][0])
    {



        $resourcePath = '/api/fileattachments/attachments-v1';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;





        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (isset($attachments)) {
            if (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the body
                $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($attachments));
            } else {
                $httpBody = $attachments;
            }
        } 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 (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($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
        );

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

    /**
     * Operation detach
     *
     * Detach file
     *
     * @param  string $attachment_id id of the attachment to be detached (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['detach'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return void
     */
    public function detach($attachment_id, string $contentType = self::contentTypes['detach'][0])
    {
        $this->detachWithHttpInfo($attachment_id, $contentType);
    }

    /**
     * Operation detachWithHttpInfo
     *
     * Detach file
     *
     * @param  string $attachment_id id of the attachment to be detached (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['detach'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of null, HTTP status code, HTTP response headers (array of strings)
     */
    public function detachWithHttpInfo($attachment_id, string $contentType = self::contentTypes['detach'][0])
    {
        $request = $this->detachRequest($attachment_id, $contentType);

        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();


            return [null, $statusCode, $response->getHeaders()];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                default:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsWebException',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation detachAsync
     *
     * Detach file
     *
     * @param  string $attachment_id id of the attachment to be detached (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['detach'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function detachAsync($attachment_id, string $contentType = self::contentTypes['detach'][0])
    {
        return $this->detachAsyncWithHttpInfo($attachment_id, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation detachAsyncWithHttpInfo
     *
     * Detach file
     *
     * @param  string $attachment_id id of the attachment to be detached (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['detach'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function detachAsyncWithHttpInfo($attachment_id, string $contentType = self::contentTypes['detach'][0])
    {
        $returnType = '';
        $request = $this->detachRequest($attachment_id, $contentType);

        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 'detach'
     *
     * @param  string $attachment_id id of the attachment to be detached (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['detach'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function detachRequest($attachment_id, string $contentType = self::contentTypes['detach'][0])
    {

        // verify the required parameter 'attachment_id' is set
        if ($attachment_id === null || (is_array($attachment_id) && count($attachment_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $attachment_id when calling detach'
            );
        }


        $resourcePath = '/api/fileattachments/attachments-v1/{attachmentId}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



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


        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // 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 (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($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
        );

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

    /**
     * Operation getAttachments
     *
     * Get attached files on an entity
     *
     * @param  int[] $entityid ids of the entities whose attachments should be fetched (required)
     * @param  string $entitytype type of the entities whose attachments should be fetched (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAttachments'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Fortnox\Model\FileattachmentsAttachment|\Fortnox\Model\FileattachmentsWebException
     */
    public function getAttachments($entityid, $entitytype, string $contentType = self::contentTypes['getAttachments'][0])
    {
        list($response) = $this->getAttachmentsWithHttpInfo($entityid, $entitytype, $contentType);
        return $response;
    }

    /**
     * Operation getAttachmentsWithHttpInfo
     *
     * Get attached files on an entity
     *
     * @param  int[] $entityid ids of the entities whose attachments should be fetched (required)
     * @param  string $entitytype type of the entities whose attachments should be fetched (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAttachments'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Fortnox\Model\FileattachmentsAttachment|\Fortnox\Model\FileattachmentsWebException, HTTP status code, HTTP response headers (array of strings)
     */
    public function getAttachmentsWithHttpInfo($entityid, $entitytype, string $contentType = self::contentTypes['getAttachments'][0])
    {
        $request = $this->getAttachmentsRequest($entityid, $entitytype, $contentType);

        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();


            switch($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Fortnox\Model\FileattachmentsAttachment',
                        $request,
                        $response,
                    );
                default:
                    return $this->handleResponseWithDataType(
                        '\Fortnox\Model\FileattachmentsWebException',
                        $request,
                        $response,
                    );
            }

            

            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 $this->handleResponseWithDataType(
                '\Fortnox\Model\FileattachmentsAttachment',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsAttachment',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                default:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsWebException',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation getAttachmentsAsync
     *
     * Get attached files on an entity
     *
     * @param  int[] $entityid ids of the entities whose attachments should be fetched (required)
     * @param  string $entitytype type of the entities whose attachments should be fetched (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAttachments'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getAttachmentsAsync($entityid, $entitytype, string $contentType = self::contentTypes['getAttachments'][0])
    {
        return $this->getAttachmentsAsyncWithHttpInfo($entityid, $entitytype, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getAttachmentsAsyncWithHttpInfo
     *
     * Get attached files on an entity
     *
     * @param  int[] $entityid ids of the entities whose attachments should be fetched (required)
     * @param  string $entitytype type of the entities whose attachments should be fetched (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAttachments'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getAttachmentsAsyncWithHttpInfo($entityid, $entitytype, string $contentType = self::contentTypes['getAttachments'][0])
    {
        $returnType = '\Fortnox\Model\FileattachmentsAttachment';
        $request = $this->getAttachmentsRequest($entityid, $entitytype, $contentType);

        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 'getAttachments'
     *
     * @param  int[] $entityid ids of the entities whose attachments should be fetched (required)
     * @param  string $entitytype type of the entities whose attachments should be fetched (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getAttachments'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getAttachmentsRequest($entityid, $entitytype, string $contentType = self::contentTypes['getAttachments'][0])
    {

        // verify the required parameter 'entityid' is set
        if ($entityid === null || (is_array($entityid) && count($entityid) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $entityid when calling getAttachments'
            );
        }

        // verify the required parameter 'entitytype' is set
        if ($entitytype === null || (is_array($entitytype) && count($entitytype) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $entitytype when calling getAttachments'
            );
        }


        $resourcePath = '/api/fileattachments/attachments-v1';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $entityid,
            'entityid', // param base name
            'array', // openApiType
            'form', // style
            true, // explode
            true // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $entitytype,
            'entitytype', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            true // required
        ) ?? []);




        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // 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 (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($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
        );

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

    /**
     * Operation getNumberOfAttachmentsForEntity
     *
     * List number of attachments
     *
     * @param  int[] $entityids ids of the entities to look for number of attachments on (required)
     * @param  string $entitytype type of the entities  to look for number of attachments on (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getNumberOfAttachmentsForEntity'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Fortnox\Model\FileattachmentsNumberOfAttachments|\Fortnox\Model\FileattachmentsWebException
     */
    public function getNumberOfAttachmentsForEntity($entityids, $entitytype, string $contentType = self::contentTypes['getNumberOfAttachmentsForEntity'][0])
    {
        list($response) = $this->getNumberOfAttachmentsForEntityWithHttpInfo($entityids, $entitytype, $contentType);
        return $response;
    }

    /**
     * Operation getNumberOfAttachmentsForEntityWithHttpInfo
     *
     * List number of attachments
     *
     * @param  int[] $entityids ids of the entities to look for number of attachments on (required)
     * @param  string $entitytype type of the entities  to look for number of attachments on (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getNumberOfAttachmentsForEntity'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Fortnox\Model\FileattachmentsNumberOfAttachments|\Fortnox\Model\FileattachmentsWebException, HTTP status code, HTTP response headers (array of strings)
     */
    public function getNumberOfAttachmentsForEntityWithHttpInfo($entityids, $entitytype, string $contentType = self::contentTypes['getNumberOfAttachmentsForEntity'][0])
    {
        $request = $this->getNumberOfAttachmentsForEntityRequest($entityids, $entitytype, $contentType);

        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();


            switch($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Fortnox\Model\FileattachmentsNumberOfAttachments',
                        $request,
                        $response,
                    );
                default:
                    return $this->handleResponseWithDataType(
                        '\Fortnox\Model\FileattachmentsWebException',
                        $request,
                        $response,
                    );
            }

            

            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 $this->handleResponseWithDataType(
                '\Fortnox\Model\FileattachmentsNumberOfAttachments',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsNumberOfAttachments',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                default:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsWebException',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation getNumberOfAttachmentsForEntityAsync
     *
     * List number of attachments
     *
     * @param  int[] $entityids ids of the entities to look for number of attachments on (required)
     * @param  string $entitytype type of the entities  to look for number of attachments on (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getNumberOfAttachmentsForEntity'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getNumberOfAttachmentsForEntityAsync($entityids, $entitytype, string $contentType = self::contentTypes['getNumberOfAttachmentsForEntity'][0])
    {
        return $this->getNumberOfAttachmentsForEntityAsyncWithHttpInfo($entityids, $entitytype, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getNumberOfAttachmentsForEntityAsyncWithHttpInfo
     *
     * List number of attachments
     *
     * @param  int[] $entityids ids of the entities to look for number of attachments on (required)
     * @param  string $entitytype type of the entities  to look for number of attachments on (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getNumberOfAttachmentsForEntity'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getNumberOfAttachmentsForEntityAsyncWithHttpInfo($entityids, $entitytype, string $contentType = self::contentTypes['getNumberOfAttachmentsForEntity'][0])
    {
        $returnType = '\Fortnox\Model\FileattachmentsNumberOfAttachments';
        $request = $this->getNumberOfAttachmentsForEntityRequest($entityids, $entitytype, $contentType);

        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 'getNumberOfAttachmentsForEntity'
     *
     * @param  int[] $entityids ids of the entities to look for number of attachments on (required)
     * @param  string $entitytype type of the entities  to look for number of attachments on (required)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getNumberOfAttachmentsForEntity'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getNumberOfAttachmentsForEntityRequest($entityids, $entitytype, string $contentType = self::contentTypes['getNumberOfAttachmentsForEntity'][0])
    {

        // verify the required parameter 'entityids' is set
        if ($entityids === null || (is_array($entityids) && count($entityids) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $entityids when calling getNumberOfAttachmentsForEntity'
            );
        }

        // verify the required parameter 'entitytype' is set
        if ($entitytype === null || (is_array($entitytype) && count($entitytype) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $entitytype when calling getNumberOfAttachmentsForEntity'
            );
        }


        $resourcePath = '/api/fileattachments/attachments-v1/numberofattachments';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $entityids,
            'entityids', // param base name
            'array', // openApiType
            'form', // style
            true, // explode
            true // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $entitytype,
            'entitytype', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            true // required
        ) ?? []);




        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // 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 (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($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
        );

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

    /**
     * Operation updateAttachment
     *
     * Update attachment
     *
     * @param  string $attachment_id id of the attachment to be updated (required)
     * @param  \Fortnox\Model\FileattachmentsAttachment|null $attachment an attachment (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['updateAttachment'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return \Fortnox\Model\FileattachmentsAttachment|\Fortnox\Model\FileattachmentsWebException
     */
    public function updateAttachment($attachment_id, $attachment = null, string $contentType = self::contentTypes['updateAttachment'][0])
    {
        list($response) = $this->updateAttachmentWithHttpInfo($attachment_id, $attachment, $contentType);
        return $response;
    }

    /**
     * Operation updateAttachmentWithHttpInfo
     *
     * Update attachment
     *
     * @param  string $attachment_id id of the attachment to be updated (required)
     * @param  \Fortnox\Model\FileattachmentsAttachment|null $attachment an attachment (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['updateAttachment'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of \Fortnox\Model\FileattachmentsAttachment|\Fortnox\Model\FileattachmentsWebException, HTTP status code, HTTP response headers (array of strings)
     */
    public function updateAttachmentWithHttpInfo($attachment_id, $attachment = null, string $contentType = self::contentTypes['updateAttachment'][0])
    {
        $request = $this->updateAttachmentRequest($attachment_id, $attachment, $contentType);

        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();


            switch($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Fortnox\Model\FileattachmentsAttachment',
                        $request,
                        $response,
                    );
                default:
                    return $this->handleResponseWithDataType(
                        '\Fortnox\Model\FileattachmentsWebException',
                        $request,
                        $response,
                    );
            }

            

            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 $this->handleResponseWithDataType(
                '\Fortnox\Model\FileattachmentsAttachment',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsAttachment',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                default:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsWebException',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation updateAttachmentAsync
     *
     * Update attachment
     *
     * @param  string $attachment_id id of the attachment to be updated (required)
     * @param  \Fortnox\Model\FileattachmentsAttachment|null $attachment an attachment (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['updateAttachment'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function updateAttachmentAsync($attachment_id, $attachment = null, string $contentType = self::contentTypes['updateAttachment'][0])
    {
        return $this->updateAttachmentAsyncWithHttpInfo($attachment_id, $attachment, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation updateAttachmentAsyncWithHttpInfo
     *
     * Update attachment
     *
     * @param  string $attachment_id id of the attachment to be updated (required)
     * @param  \Fortnox\Model\FileattachmentsAttachment|null $attachment an attachment (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['updateAttachment'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function updateAttachmentAsyncWithHttpInfo($attachment_id, $attachment = null, string $contentType = self::contentTypes['updateAttachment'][0])
    {
        $returnType = '\Fortnox\Model\FileattachmentsAttachment';
        $request = $this->updateAttachmentRequest($attachment_id, $attachment, $contentType);

        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 'updateAttachment'
     *
     * @param  string $attachment_id id of the attachment to be updated (required)
     * @param  \Fortnox\Model\FileattachmentsAttachment|null $attachment an attachment (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['updateAttachment'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function updateAttachmentRequest($attachment_id, $attachment = null, string $contentType = self::contentTypes['updateAttachment'][0])
    {

        // verify the required parameter 'attachment_id' is set
        if ($attachment_id === null || (is_array($attachment_id) && count($attachment_id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $attachment_id when calling updateAttachment'
            );
        }



        $resourcePath = '/api/fileattachments/attachments-v1/{attachmentId}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



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


        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (isset($attachment)) {
            if (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the body
                $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($attachment));
            } else {
                $httpBody = $attachment;
            }
        } 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 (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($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
        );

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

    /**
     * Operation validateIncludedOnSend
     *
     * Validates a list of attachments that will be included on send
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments a list of Attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['validateIncludedOnSend'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return void
     */
    public function validateIncludedOnSend($attachments = null, string $contentType = self::contentTypes['validateIncludedOnSend'][0])
    {
        $this->validateIncludedOnSendWithHttpInfo($attachments, $contentType);
    }

    /**
     * Operation validateIncludedOnSendWithHttpInfo
     *
     * Validates a list of attachments that will be included on send
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments a list of Attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['validateIncludedOnSend'] to see the possible values for this operation
     *
     * @throws \Fortnox\ApiException on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     * @return array of null, HTTP status code, HTTP response headers (array of strings)
     */
    public function validateIncludedOnSendWithHttpInfo($attachments = null, string $contentType = self::contentTypes['validateIncludedOnSend'][0])
    {
        $request = $this->validateIncludedOnSendRequest($attachments, $contentType);

        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();


            return [null, $statusCode, $response->getHeaders()];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                default:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Fortnox\Model\FileattachmentsWebException',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
            }
        

            throw $e;
        }
    }

    /**
     * Operation validateIncludedOnSendAsync
     *
     * Validates a list of attachments that will be included on send
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments a list of Attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['validateIncludedOnSend'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function validateIncludedOnSendAsync($attachments = null, string $contentType = self::contentTypes['validateIncludedOnSend'][0])
    {
        return $this->validateIncludedOnSendAsyncWithHttpInfo($attachments, $contentType)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation validateIncludedOnSendAsyncWithHttpInfo
     *
     * Validates a list of attachments that will be included on send
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments a list of Attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['validateIncludedOnSend'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function validateIncludedOnSendAsyncWithHttpInfo($attachments = null, string $contentType = self::contentTypes['validateIncludedOnSend'][0])
    {
        $returnType = '';
        $request = $this->validateIncludedOnSendRequest($attachments, $contentType);

        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 'validateIncludedOnSend'
     *
     * @param  \Fortnox\Model\FileattachmentsAttachment[]|null $attachments a list of Attachments (optional)
     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['validateIncludedOnSend'] to see the possible values for this operation
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function validateIncludedOnSendRequest($attachments = null, string $contentType = self::contentTypes['validateIncludedOnSend'][0])
    {



        $resourcePath = '/api/fileattachments/attachments-v1/validateincludedonsend';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;





        $headers = $this->headerSelector->selectHeaders(
            ['application/json', ],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (isset($attachments)) {
            if (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the body
                $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($attachments));
            } else {
                $httpBody = $attachments;
            }
        } 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 (stripos($headers['Content-Type'], 'application/json') !== false) {
                # if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = \GuzzleHttp\Utils::jsonEncode($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
        );

        $operationHost = $this->config->getHost();
        $query = ObjectSerializer::buildQuery($queryParams);
        return new Request(
            'POST',
            $operationHost . $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());
            }
        }

        if ($this->config->getCertFile()) {
            $options[RequestOptions::CERT] = $this->config->getCertFile();
        }

        if ($this->config->getKeyFile()) {
            $options[RequestOptions::SSL_KEY] = $this->config->getKeyFile();
        }

        return $options;
    }

    private function handleResponseWithDataType(
        string $dataType,
        RequestInterface $request,
        ResponseInterface $response
    ): array {
        if ($dataType === '\SplFileObject') {
            $content = $response->getBody(); //stream goes to serializer
        } else {
            $content = (string) $response->getBody();
            if ($dataType !== 'string') {
                try {
                    $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                } catch (\JsonException $exception) {
                    throw new ApiException(
                        sprintf(
                            'Error JSON decoding server response (%s)',
                            $request->getUri()
                        ),
                        $response->getStatusCode(),
                        $response->getHeaders(),
                        $content
                    );
                }
            }
        }

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

    private function responseWithinRangeCode(
        string $rangeCode,
        int $statusCode
    ): bool {
        $left = (int) ($rangeCode[0].'00');
        $right = (int) ($rangeCode[0].'99');

        return $statusCode >= $left && $statusCode <= $right;
    }
}
