From ad6c8297a986cb6e7dc1c83e84b90b92b8a96b3f Mon Sep 17 00:00:00 2001 From: Gosling-dude <153452401+Gosling-dude@users.noreply.github.com> Date: Wed, 30 Apr 2025 09:04:17 +0530 Subject: [PATCH] Update PHP samples to include declare(strict_types=1) --- samples/client/petstore/php/.gitignore | 15 + .../petstore/php/.openapi-generator-ignore | 23 + .../petstore/php/.openapi-generator/FILES | 41 + .../petstore/php/.openapi-generator/VERSION | 2 +- .../petstore/php/.php-cs-fixer.dist.php | 29 + samples/client/petstore/php/.travis.yml | 8 + samples/client/petstore/php/README.md | 145 ++ samples/client/petstore/php/composer.json | 38 + .../client/petstore/php/docs/Api/PetApi.md | 493 ++++ .../client/petstore/php/docs/Api/StoreApi.md | 235 ++ .../client/petstore/php/docs/Api/UserApi.md | 448 ++++ .../petstore/php/docs/Model/ApiResponse.md | 11 + .../petstore/php/docs/Model/Category.md | 10 + .../client/petstore/php/docs/Model/Order.md | 14 + samples/client/petstore/php/docs/Model/Pet.md | 14 + samples/client/petstore/php/docs/Model/Tag.md | 10 + .../client/petstore/php/docs/Model/User.md | 16 + samples/client/petstore/php/git_push.sh | 57 + .../client/petstore/php/lib/Api/PetApi.php | 2249 +++++++++++++++++ .../client/petstore/php/lib/Api/StoreApi.php | 1210 +++++++++ .../client/petstore/php/lib/Api/UserApi.php | 2072 +++++++++++++++ .../client/petstore/php/lib/ApiException.php | 119 + .../client/petstore/php/lib/Configuration.php | 531 ++++ .../petstore/php/lib/FormDataProcessor.php | 242 ++ .../petstore/php/lib/HeaderSelector.php | 273 ++ .../petstore/php/lib/Model/ApiResponse.php | 478 ++++ .../petstore/php/lib/Model/Category.php | 444 ++++ .../petstore/php/lib/Model/ModelInterface.php | 111 + .../client/petstore/php/lib/Model/Order.php | 616 +++++ samples/client/petstore/php/lib/Model/Pet.php | 622 +++++ samples/client/petstore/php/lib/Model/Tag.php | 444 ++++ .../client/petstore/php/lib/Model/User.php | 648 +++++ .../petstore/php/lib/ObjectSerializer.php | 599 +++++ samples/client/petstore/php/phpunit.xml.dist | 18 + .../petstore/php/test/Api/PetApiTest.php | 169 ++ .../petstore/php/test/Api/StoreApiTest.php | 121 + .../petstore/php/test/Api/UserApiTest.php | 169 ++ .../php/test/Model/ApiResponseTest.php | 108 + .../petstore/php/test/Model/CategoryTest.php | 99 + .../petstore/php/test/Model/OrderTest.php | 135 + .../petstore/php/test/Model/PetTest.php | 135 + .../petstore/php/test/Model/TagTest.php | 99 + .../petstore/php/test/Model/UserTest.php | 153 ++ 43 files changed, 13472 insertions(+), 1 deletion(-) create mode 100644 samples/client/petstore/php/.gitignore create mode 100644 samples/client/petstore/php/.openapi-generator-ignore create mode 100644 samples/client/petstore/php/.openapi-generator/FILES create mode 100644 samples/client/petstore/php/.php-cs-fixer.dist.php create mode 100644 samples/client/petstore/php/.travis.yml create mode 100644 samples/client/petstore/php/README.md create mode 100644 samples/client/petstore/php/composer.json create mode 100644 samples/client/petstore/php/docs/Api/PetApi.md create mode 100644 samples/client/petstore/php/docs/Api/StoreApi.md create mode 100644 samples/client/petstore/php/docs/Api/UserApi.md create mode 100644 samples/client/petstore/php/docs/Model/ApiResponse.md create mode 100644 samples/client/petstore/php/docs/Model/Category.md create mode 100644 samples/client/petstore/php/docs/Model/Order.md create mode 100644 samples/client/petstore/php/docs/Model/Pet.md create mode 100644 samples/client/petstore/php/docs/Model/Tag.md create mode 100644 samples/client/petstore/php/docs/Model/User.md create mode 100644 samples/client/petstore/php/git_push.sh create mode 100644 samples/client/petstore/php/lib/Api/PetApi.php create mode 100644 samples/client/petstore/php/lib/Api/StoreApi.php create mode 100644 samples/client/petstore/php/lib/Api/UserApi.php create mode 100644 samples/client/petstore/php/lib/ApiException.php create mode 100644 samples/client/petstore/php/lib/Configuration.php create mode 100644 samples/client/petstore/php/lib/FormDataProcessor.php create mode 100644 samples/client/petstore/php/lib/HeaderSelector.php create mode 100644 samples/client/petstore/php/lib/Model/ApiResponse.php create mode 100644 samples/client/petstore/php/lib/Model/Category.php create mode 100644 samples/client/petstore/php/lib/Model/ModelInterface.php create mode 100644 samples/client/petstore/php/lib/Model/Order.php create mode 100644 samples/client/petstore/php/lib/Model/Pet.php create mode 100644 samples/client/petstore/php/lib/Model/Tag.php create mode 100644 samples/client/petstore/php/lib/Model/User.php create mode 100644 samples/client/petstore/php/lib/ObjectSerializer.php create mode 100644 samples/client/petstore/php/phpunit.xml.dist create mode 100644 samples/client/petstore/php/test/Api/PetApiTest.php create mode 100644 samples/client/petstore/php/test/Api/StoreApiTest.php create mode 100644 samples/client/petstore/php/test/Api/UserApiTest.php create mode 100644 samples/client/petstore/php/test/Model/ApiResponseTest.php create mode 100644 samples/client/petstore/php/test/Model/CategoryTest.php create mode 100644 samples/client/petstore/php/test/Model/OrderTest.php create mode 100644 samples/client/petstore/php/test/Model/PetTest.php create mode 100644 samples/client/petstore/php/test/Model/TagTest.php create mode 100644 samples/client/petstore/php/test/Model/UserTest.php diff --git a/samples/client/petstore/php/.gitignore b/samples/client/petstore/php/.gitignore new file mode 100644 index 000000000000..9f1681c2be8d --- /dev/null +++ b/samples/client/petstore/php/.gitignore @@ -0,0 +1,15 @@ +# ref: https://github.com/github/gitignore/blob/master/Composer.gitignore + +composer.phar +/vendor/ + +# Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control +# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file +# composer.lock + +# php-cs-fixer cache +.php_cs.cache +.php-cs-fixer.cache + +# PHPUnit cache +.phpunit.result.cache diff --git a/samples/client/petstore/php/.openapi-generator-ignore b/samples/client/petstore/php/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/php/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/php/.openapi-generator/FILES b/samples/client/petstore/php/.openapi-generator/FILES new file mode 100644 index 000000000000..94685da65746 --- /dev/null +++ b/samples/client/petstore/php/.openapi-generator/FILES @@ -0,0 +1,41 @@ +.gitignore +.openapi-generator-ignore +.php-cs-fixer.dist.php +.travis.yml +README.md +composer.json +docs/Api/PetApi.md +docs/Api/StoreApi.md +docs/Api/UserApi.md +docs/Model/ApiResponse.md +docs/Model/Category.md +docs/Model/Order.md +docs/Model/Pet.md +docs/Model/Tag.md +docs/Model/User.md +git_push.sh +lib/Api/PetApi.php +lib/Api/StoreApi.php +lib/Api/UserApi.php +lib/ApiException.php +lib/Configuration.php +lib/FormDataProcessor.php +lib/HeaderSelector.php +lib/Model/ApiResponse.php +lib/Model/Category.php +lib/Model/ModelInterface.php +lib/Model/Order.php +lib/Model/Pet.php +lib/Model/Tag.php +lib/Model/User.php +lib/ObjectSerializer.php +phpunit.xml.dist +test/Api/PetApiTest.php +test/Api/StoreApiTest.php +test/Api/UserApiTest.php +test/Model/ApiResponseTest.php +test/Model/CategoryTest.php +test/Model/OrderTest.php +test/Model/PetTest.php +test/Model/TagTest.php +test/Model/UserTest.php diff --git a/samples/client/petstore/php/.openapi-generator/VERSION b/samples/client/petstore/php/.openapi-generator/VERSION index afa636560641..4c631cf217a2 100644 --- a/samples/client/petstore/php/.openapi-generator/VERSION +++ b/samples/client/petstore/php/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +7.14.0-SNAPSHOT diff --git a/samples/client/petstore/php/.php-cs-fixer.dist.php b/samples/client/petstore/php/.php-cs-fixer.dist.php new file mode 100644 index 000000000000..af9cf39fddb0 --- /dev/null +++ b/samples/client/petstore/php/.php-cs-fixer.dist.php @@ -0,0 +1,29 @@ +in(__DIR__) + ->exclude('vendor') + ->exclude('test') + ->exclude('tests') +; + +$config = new PhpCsFixer\Config(); +return $config->setRules([ + '@PSR12' => true, + 'phpdoc_order' => true, + 'array_syntax' => [ 'syntax' => 'short' ], + 'strict_comparison' => true, + 'strict_param' => true, + 'no_trailing_whitespace' => false, + 'no_trailing_whitespace_in_comment' => false, + 'braces' => false, + 'single_blank_line_at_eof' => false, + 'blank_line_after_namespace' => false, + 'no_leading_import_slash' => false, + ]) + ->setFinder($finder) +; diff --git a/samples/client/petstore/php/.travis.yml b/samples/client/petstore/php/.travis.yml new file mode 100644 index 000000000000..667b81565308 --- /dev/null +++ b/samples/client/petstore/php/.travis.yml @@ -0,0 +1,8 @@ +language: php +# Bionic environment has preinstalled PHP from 7.1 to 7.4 +# https://docs.travis-ci.com/user/reference/bionic/#php-support +dist: bionic +php: + - 7.4 +before_install: "composer install" +script: "vendor/bin/phpunit" diff --git a/samples/client/petstore/php/README.md b/samples/client/petstore/php/README.md new file mode 100644 index 000000000000..f614e42565ee --- /dev/null +++ b/samples/client/petstore/php/README.md @@ -0,0 +1,145 @@ +# OpenAPIClient-php + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + + +## Installation & Usage + +### Requirements + +PHP 8.1 and later. + +### Composer + +To install the bindings via [Composer](https://getcomposer.org/), add the following to `composer.json`: + +```json +{ + "repositories": [ + { + "type": "vcs", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + } + ], + "require": { + "GIT_USER_ID/GIT_REPO_ID": "*@dev" + } +} +``` + +Then run `composer install` + +### Manual Installation + +Download the files and include `autoload.php`: + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + + +$apiInstance = new OpenAPI\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$body = new \OpenAPI\Client\Model\Pet(); // \OpenAPI\Client\Model\Pet | Pet object that needs to be added to the store + +try { + $apiInstance->addPet($body); +} catch (Exception $e) { + echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), PHP_EOL; +} + +``` + +## API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/Api/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/Api/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/Api/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/Api/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/Api/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/Api/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/Api/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/Api/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/Api/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/Api/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/Api/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/Api/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/Api/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/Api/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/Api/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/Api/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/Api/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/Api/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/Api/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/Api/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + +## Models + +- [ApiResponse](docs/Model/ApiResponse.md) +- [Category](docs/Model/Category.md) +- [Order](docs/Model/Order.md) +- [Pet](docs/Model/Pet.md) +- [Tag](docs/Model/Tag.md) +- [User](docs/Model/User.md) + +## Authorization + +Authentication schemes defined for the API: +### petstore_auth + +- **Type**: `OAuth` +- **Flow**: `implicit` +- **Authorization URL**: `http://petstore.swagger.io/api/oauth/dialog` +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +## Tests + +To run the tests, use: + +```bash +composer install +vendor/bin/phpunit +``` + +## Author + + + +## About this package + +This PHP package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: `1.0.0` + - Generator version: `7.14.0-SNAPSHOT` +- Build package: `org.openapitools.codegen.languages.PhpClientCodegen` diff --git a/samples/client/petstore/php/composer.json b/samples/client/petstore/php/composer.json new file mode 100644 index 000000000000..59dc2d7f82a0 --- /dev/null +++ b/samples/client/petstore/php/composer.json @@ -0,0 +1,38 @@ +{ + "description": "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", + "keywords": [ + "openapitools", + "openapi-generator", + "openapi", + "php", + "sdk", + "rest", + "api" + ], + "homepage": "https://openapi-generator.tech", + "license": "unlicense", + "authors": [ + { + "name": "OpenAPI", + "homepage": "https://openapi-generator.tech" + } + ], + "require": { + "php": "^8.1", + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "guzzlehttp/guzzle": "^7.3", + "guzzlehttp/psr7": "^1.7 || ^2.0" + }, + "require-dev": { + "phpunit/phpunit": "^8.0 || ^9.0", + "friendsofphp/php-cs-fixer": "^3.5" + }, + "autoload": { + "psr-4": { "OpenAPI\\Client\\" : "lib/" } + }, + "autoload-dev": { + "psr-4": { "OpenAPI\\Client\\Test\\" : "test/" } + } +} diff --git a/samples/client/petstore/php/docs/Api/PetApi.md b/samples/client/petstore/php/docs/Api/PetApi.md new file mode 100644 index 000000000000..4d4631c202f6 --- /dev/null +++ b/samples/client/petstore/php/docs/Api/PetApi.md @@ -0,0 +1,493 @@ +# OpenAPI\Client\PetApi + +All URIs are relative to http://petstore.swagger.io/v2, except if the operation defines another base path. + +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**addPet()**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store | +| [**deletePet()**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**findPetsByStatus()**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status | +| [**findPetsByTags()**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**getPetById()**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID | +| [**updatePet()**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet | +| [**updatePetWithForm()**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**uploadFile()**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image | + + +## `addPet()` + +```php +addPet($body) +``` + +Add a new pet to the store + +### Example + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + + +$apiInstance = new OpenAPI\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$body = new \OpenAPI\Client\Model\Pet(); // \OpenAPI\Client\Model\Pet | Pet object that needs to be added to the store + +try { + $apiInstance->addPet($body); +} catch (Exception $e) { + echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | [**\OpenAPI\Client\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: `application/json`, `application/xml` +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `deletePet()` + +```php +deletePet($pet_id, $api_key) +``` + +Deletes a pet + +### Example + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + + +$apiInstance = new OpenAPI\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet_id = 56; // int | Pet id to delete +$api_key = 'api_key_example'; // string + +try { + $apiInstance->deletePet($pet_id, $api_key); +} catch (Exception $e) { + echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet_id** | **int**| Pet id to delete | | +| **api_key** | **string**| | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `findPetsByStatus()` + +```php +findPetsByStatus($status): \OpenAPI\Client\Model\Pet[] +``` + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + + +$apiInstance = new OpenAPI\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$status = array('status_example'); // string[] | Status values that need to be considered for filter + +try { + $result = $apiInstance->findPetsByStatus($status); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->findPetsByStatus: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **status** | [**string[]**](../Model/string.md)| Status values that need to be considered for filter | | + +### Return type + +[**\OpenAPI\Client\Model\Pet[]**](../Model/Pet.md) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/xml`, `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `findPetsByTags()` + +```php +findPetsByTags($tags): \OpenAPI\Client\Model\Pet[] +``` + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + + +$apiInstance = new OpenAPI\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$tags = array('tags_example'); // string[] | Tags to filter by + +try { + $result = $apiInstance->findPetsByTags($tags); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->findPetsByTags: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **tags** | [**string[]**](../Model/string.md)| Tags to filter by | | + +### Return type + +[**\OpenAPI\Client\Model\Pet[]**](../Model/Pet.md) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/xml`, `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getPetById()` + +```php +getPetById($pet_id): \OpenAPI\Client\Model\Pet +``` + +Find pet by ID + +Returns a single pet + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet_id = 56; // int | ID of pet to return + +try { + $result = $apiInstance->getPetById($pet_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->getPetById: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet_id** | **int**| ID of pet to return | | + +### Return type + +[**\OpenAPI\Client\Model\Pet**](../Model/Pet.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/xml`, `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `updatePet()` + +```php +updatePet($body) +``` + +Update an existing pet + +### Example + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + + +$apiInstance = new OpenAPI\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$body = new \OpenAPI\Client\Model\Pet(); // \OpenAPI\Client\Model\Pet | Pet object that needs to be added to the store + +try { + $apiInstance->updatePet($body); +} catch (Exception $e) { + echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | [**\OpenAPI\Client\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: `application/json`, `application/xml` +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `updatePetWithForm()` + +```php +updatePetWithForm($pet_id, $name, $status) +``` + +Updates a pet in the store with form data + +### Example + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + + +$apiInstance = new OpenAPI\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet_id = 56; // int | ID of pet that needs to be updated +$name = 'name_example'; // string | Updated name of the pet +$status = 'status_example'; // string | Updated status of the pet + +try { + $apiInstance->updatePetWithForm($pet_id, $name, $status); +} catch (Exception $e) { + echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet_id** | **int**| ID of pet that needs to be updated | | +| **name** | **string**| Updated name of the pet | [optional] | +| **status** | **string**| Updated status of the pet | [optional] | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: `application/x-www-form-urlencoded` +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `uploadFile()` + +```php +uploadFile($pet_id, $additional_metadata, $file): \OpenAPI\Client\Model\ApiResponse +``` + +uploads an image + +### Example + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + + +$apiInstance = new OpenAPI\Client\Api\PetApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$pet_id = 56; // int | ID of pet to update +$additional_metadata = 'additional_metadata_example'; // string | Additional data to pass to server +$file = '/path/to/file.txt'; // \SplFileObject | file to upload + +try { + $result = $apiInstance->uploadFile($pet_id, $additional_metadata, $file); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PetApi->uploadFile: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet_id** | **int**| ID of pet to update | | +| **additional_metadata** | **string**| Additional data to pass to server | [optional] | +| **file** | **\SplFileObject****\SplFileObject**| file to upload | [optional] | + +### Return type + +[**\OpenAPI\Client\Model\ApiResponse**](../Model/ApiResponse.md) + +### Authorization + +[petstore_auth](../../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: `multipart/form-data` +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/docs/Api/StoreApi.md b/samples/client/petstore/php/docs/Api/StoreApi.md new file mode 100644 index 000000000000..bb15aad43f4d --- /dev/null +++ b/samples/client/petstore/php/docs/Api/StoreApi.md @@ -0,0 +1,235 @@ +# OpenAPI\Client\StoreApi + +All URIs are relative to http://petstore.swagger.io/v2, except if the operation defines another base path. + +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**deleteOrder()**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID | +| [**getInventory()**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status | +| [**getOrderById()**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID | +| [**placeOrder()**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet | + + +## `deleteOrder()` + +```php +deleteOrder($order_id) +``` + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example + +```php +deleteOrder($order_id); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **order_id** | **string**| ID of the order that needs to be deleted | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getInventory()` + +```php +getInventory(): array +``` + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\StoreApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); + +try { + $result = $apiInstance->getInventory(); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->getInventory: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**array** + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getOrderById()` + +```php +getOrderById($order_id): \OpenAPI\Client\Model\Order +``` + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + +### Example + +```php +getOrderById($order_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->getOrderById: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **order_id** | **int**| ID of pet that needs to be fetched | | + +### Return type + +[**\OpenAPI\Client\Model\Order**](../Model/Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/xml`, `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `placeOrder()` + +```php +placeOrder($body): \OpenAPI\Client\Model\Order +``` + +Place an order for a pet + +### Example + +```php +placeOrder($body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling StoreApi->placeOrder: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | [**\OpenAPI\Client\Model\Order**](../Model/Order.md)| order placed for purchasing the pet | | + +### Return type + +[**\OpenAPI\Client\Model\Order**](../Model/Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/xml`, `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/docs/Api/UserApi.md b/samples/client/petstore/php/docs/Api/UserApi.md new file mode 100644 index 000000000000..1d6f200da5b9 --- /dev/null +++ b/samples/client/petstore/php/docs/Api/UserApi.md @@ -0,0 +1,448 @@ +# OpenAPI\Client\UserApi + +All URIs are relative to http://petstore.swagger.io/v2, except if the operation defines another base path. + +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**createUser()**](UserApi.md#createUser) | **POST** /user | Create user | +| [**createUsersWithArrayInput()**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array | +| [**createUsersWithListInput()**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array | +| [**deleteUser()**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user | +| [**getUserByName()**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name | +| [**loginUser()**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system | +| [**logoutUser()**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session | +| [**updateUser()**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user | + + +## `createUser()` + +```php +createUser($body) +``` + +Create user + +This can only be done by the logged in user. + +### Example + +```php +createUser($body); +} catch (Exception $e) { + echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | [**\OpenAPI\Client\Model\User**](../Model/User.md)| Created user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `createUsersWithArrayInput()` + +```php +createUsersWithArrayInput($body) +``` + +Creates list of users with given input array + +### Example + +```php +createUsersWithArrayInput($body); +} catch (Exception $e) { + echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | [**\OpenAPI\Client\Model\User[]**](../Model/User.md)| List of user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `createUsersWithListInput()` + +```php +createUsersWithListInput($body) +``` + +Creates list of users with given input array + +### Example + +```php +createUsersWithListInput($body); +} catch (Exception $e) { + echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **body** | [**\OpenAPI\Client\Model\User[]**](../Model/User.md)| List of user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `deleteUser()` + +```php +deleteUser($username) +``` + +Delete user + +This can only be done by the logged in user. + +### Example + +```php +deleteUser($username); +} catch (Exception $e) { + echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **username** | **string**| The name that needs to be deleted | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getUserByName()` + +```php +getUserByName($username): \OpenAPI\Client\Model\User +``` + +Get user by user name + +### Example + +```php +getUserByName($username); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApi->getUserByName: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **username** | **string**| The name that needs to be fetched. Use user1 for testing. | | + +### Return type + +[**\OpenAPI\Client\Model\User**](../Model/User.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/xml`, `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `loginUser()` + +```php +loginUser($username, $password): string +``` + +Logs user into the system + +### Example + +```php +loginUser($username, $password); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApi->loginUser: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **username** | **string**| The user name for login | | +| **password** | **string**| The password for login in clear text | | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/xml`, `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `logoutUser()` + +```php +logoutUser() +``` + +Logs out current logged in user session + +### Example + +```php +logoutUser(); +} catch (Exception $e) { + echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `updateUser()` + +```php +updateUser($username, $body) +``` + +Updated user + +This can only be done by the logged in user. + +### Example + +```php +updateUser($username, $body); +} catch (Exception $e) { + echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **username** | **string**| name that need to be deleted | | +| **body** | [**\OpenAPI\Client\Model\User**](../Model/User.md)| Updated user object | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/docs/Model/ApiResponse.md b/samples/client/petstore/php/docs/Model/ApiResponse.md new file mode 100644 index 000000000000..bd084f0b741e --- /dev/null +++ b/samples/client/petstore/php/docs/Model/ApiResponse.md @@ -0,0 +1,11 @@ +# # ApiResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | [optional] +**type** | **string** | | [optional] +**message** | **string** | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/docs/Model/Category.md b/samples/client/petstore/php/docs/Model/Category.md new file mode 100644 index 000000000000..7302be9d97dd --- /dev/null +++ b/samples/client/petstore/php/docs/Model/Category.md @@ -0,0 +1,10 @@ +# # Category + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/docs/Model/Order.md b/samples/client/petstore/php/docs/Model/Order.md new file mode 100644 index 000000000000..c6ec90a33c1d --- /dev/null +++ b/samples/client/petstore/php/docs/Model/Order.md @@ -0,0 +1,14 @@ +# # Order + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**pet_id** | **int** | | [optional] +**quantity** | **int** | | [optional] +**ship_date** | **\DateTime** | | [optional] +**status** | **string** | Order Status | [optional] +**complete** | **bool** | | [optional] [default to false] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/docs/Model/Pet.md b/samples/client/petstore/php/docs/Model/Pet.md new file mode 100644 index 000000000000..c9edeaf65b64 --- /dev/null +++ b/samples/client/petstore/php/docs/Model/Pet.md @@ -0,0 +1,14 @@ +# # Pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**category** | [**\OpenAPI\Client\Model\Category**](Category.md) | | [optional] +**name** | **string** | | +**photo_urls** | **string[]** | | +**tags** | [**\OpenAPI\Client\Model\Tag[]**](Tag.md) | | [optional] +**status** | **string** | pet status in the store | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/docs/Model/Tag.md b/samples/client/petstore/php/docs/Model/Tag.md new file mode 100644 index 000000000000..4cf7084738b0 --- /dev/null +++ b/samples/client/petstore/php/docs/Model/Tag.md @@ -0,0 +1,10 @@ +# # Tag + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/docs/Model/User.md b/samples/client/petstore/php/docs/Model/User.md new file mode 100644 index 000000000000..dde68f38fc0b --- /dev/null +++ b/samples/client/petstore/php/docs/Model/User.md @@ -0,0 +1,16 @@ +# # User + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**username** | **string** | | [optional] +**first_name** | **string** | | [optional] +**last_name** | **string** | | [optional] +**email** | **string** | | [optional] +**password** | **string** | | [optional] +**phone** | **string** | | [optional] +**user_status** | **int** | User Status | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/git_push.sh b/samples/client/petstore/php/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/petstore/php/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/php/lib/Api/PetApi.php b/samples/client/petstore/php/lib/Api/PetApi.php new file mode 100644 index 000000000000..5e158b335f19 --- /dev/null +++ b/samples/client/petstore/php/lib/Api/PetApi.php @@ -0,0 +1,2249 @@ + [ + 'application/json', + 'application/xml', + ], + 'deletePet' => [ + 'application/json', + ], + 'findPetsByStatus' => [ + 'application/json', + ], + 'findPetsByTags' => [ + 'application/json', + ], + 'getPetById' => [ + 'application/json', + ], + 'updatePet' => [ + 'application/json', + 'application/xml', + ], + 'updatePetWithForm' => [ + 'application/x-www-form-urlencoded', + ], + 'uploadFile' => [ + 'multipart/form-data', + ], + ]; + + /** + * @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 addPet + * + * Add a new pet to the store + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function addPet($body, string $contentType = self::contentTypes['addPet'][0]) + { + $this->addPetWithHttpInfo($body, $contentType); + } + + /** + * Operation addPetWithHttpInfo + * + * Add a new pet to the store + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 addPetWithHttpInfo($body, string $contentType = self::contentTypes['addPet'][0]) + { + $request = $this->addPetRequest($body, $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()) { + } + + + throw $e; + } + } + + /** + * Operation addPetAsync + * + * Add a new pet to the store + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function addPetAsync($body, string $contentType = self::contentTypes['addPet'][0]) + { + return $this->addPetAsyncWithHttpInfo($body, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation addPetAsyncWithHttpInfo + * + * Add a new pet to the store + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function addPetAsyncWithHttpInfo($body, string $contentType = self::contentTypes['addPet'][0]) + { + $returnType = ''; + $request = $this->addPetRequest($body, $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 'addPet' + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function addPetRequest($body, string $contentType = self::contentTypes['addPet'][0]) + { + + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling addPet' + ); + } + + + $resourcePath = '/pet'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + [], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($body)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); + } else { + $httpBody = $body; + } + } 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); + } + } + + // this endpoint requires OAuth (access token) + if (!empty($this->config->getAccessToken())) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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 deletePet + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string|null $api_key api_key (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function deletePet($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) + { + $this->deletePetWithHttpInfo($pet_id, $api_key, $contentType); + } + + /** + * Operation deletePetWithHttpInfo + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string|null $api_key (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 deletePetWithHttpInfo($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) + { + $request = $this->deletePetRequest($pet_id, $api_key, $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()) { + } + + + throw $e; + } + } + + /** + * Operation deletePetAsync + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string|null $api_key (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deletePetAsync($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) + { + return $this->deletePetAsyncWithHttpInfo($pet_id, $api_key, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation deletePetAsyncWithHttpInfo + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string|null $api_key (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deletePetAsyncWithHttpInfo($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) + { + $returnType = ''; + $request = $this->deletePetRequest($pet_id, $api_key, $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 'deletePet' + * + * @param int $pet_id Pet id to delete (required) + * @param string|null $api_key (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function deletePetRequest($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) + { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet_id when calling deletePet' + ); + } + + + + $resourcePath = '/pet/{petId}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // header params + if ($api_key !== null) { + $headerParams['api_key'] = ObjectSerializer::toHeaderValue($api_key); + } + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + '{' . 'petId' . '}', + ObjectSerializer::toPathValue($pet_id), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + [], + $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); + } + } + + // this endpoint requires OAuth (access token) + if (!empty($this->config->getAccessToken())) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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 findPetsByStatus + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\Pet[] + */ + public function findPetsByStatus($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) + { + list($response) = $this->findPetsByStatusWithHttpInfo($status, $contentType); + return $response; + } + + /** + * Operation findPetsByStatusWithHttpInfo + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + */ + public function findPetsByStatusWithHttpInfo($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) + { + $request = $this->findPetsByStatusRequest($status, $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( + '\OpenAPI\Client\Model\Pet[]', + $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( + '\OpenAPI\Client\Model\Pet[]', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\Pet[]', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation findPetsByStatusAsync + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function findPetsByStatusAsync($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) + { + return $this->findPetsByStatusAsyncWithHttpInfo($status, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation findPetsByStatusAsyncWithHttpInfo + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function findPetsByStatusAsyncWithHttpInfo($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) + { + $returnType = '\OpenAPI\Client\Model\Pet[]'; + $request = $this->findPetsByStatusRequest($status, $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 'findPetsByStatus' + * + * @param string[] $status Status values that need to be considered for filter (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function findPetsByStatusRequest($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) + { + + // verify the required parameter 'status' is set + if ($status === null || (is_array($status) && count($status) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $status when calling findPetsByStatus' + ); + } + + + $resourcePath = '/pet/findByStatus'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $status, + 'status', // param base name + 'array', // openApiType + 'form', // style + false, // explode + true // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', '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); + } + } + + // this endpoint requires OAuth (access token) + if (!empty($this->config->getAccessToken())) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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 findPetsByTags + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\Pet[] + * @deprecated + */ + public function findPetsByTags($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) + { + list($response) = $this->findPetsByTagsWithHttpInfo($tags, $contentType); + return $response; + } + + /** + * Operation findPetsByTagsWithHttpInfo + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + * @deprecated + */ + public function findPetsByTagsWithHttpInfo($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) + { + $request = $this->findPetsByTagsRequest($tags, $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( + '\OpenAPI\Client\Model\Pet[]', + $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( + '\OpenAPI\Client\Model\Pet[]', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\Pet[]', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation findPetsByTagsAsync + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + * @deprecated + */ + public function findPetsByTagsAsync($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) + { + return $this->findPetsByTagsAsyncWithHttpInfo($tags, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation findPetsByTagsAsyncWithHttpInfo + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + * @deprecated + */ + public function findPetsByTagsAsyncWithHttpInfo($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) + { + $returnType = '\OpenAPI\Client\Model\Pet[]'; + $request = $this->findPetsByTagsRequest($tags, $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 'findPetsByTags' + * + * @param string[] $tags Tags to filter by (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + * @deprecated + */ + public function findPetsByTagsRequest($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) + { + + // verify the required parameter 'tags' is set + if ($tags === null || (is_array($tags) && count($tags) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $tags when calling findPetsByTags' + ); + } + + + $resourcePath = '/pet/findByTags'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $tags, + 'tags', // param base name + 'array', // openApiType + 'form', // style + false, // explode + true // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', '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); + } + } + + // this endpoint requires OAuth (access token) + if (!empty($this->config->getAccessToken())) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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 getPetById + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\Pet + */ + public function getPetById($pet_id, string $contentType = self::contentTypes['getPetById'][0]) + { + list($response) = $this->getPetByIdWithHttpInfo($pet_id, $contentType); + return $response; + } + + /** + * Operation getPetByIdWithHttpInfo + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) + */ + public function getPetByIdWithHttpInfo($pet_id, string $contentType = self::contentTypes['getPetById'][0]) + { + $request = $this->getPetByIdRequest($pet_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(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\Pet', + $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( + '\OpenAPI\Client\Model\Pet', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\Pet', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getPetByIdAsync + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPetByIdAsync($pet_id, string $contentType = self::contentTypes['getPetById'][0]) + { + return $this->getPetByIdAsyncWithHttpInfo($pet_id, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getPetByIdAsyncWithHttpInfo + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPetByIdAsyncWithHttpInfo($pet_id, string $contentType = self::contentTypes['getPetById'][0]) + { + $returnType = '\OpenAPI\Client\Model\Pet'; + $request = $this->getPetByIdRequest($pet_id, $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 'getPetById' + * + * @param int $pet_id ID of pet to return (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getPetByIdRequest($pet_id, string $contentType = self::contentTypes['getPetById'][0]) + { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet_id when calling getPetById' + ); + } + + + $resourcePath = '/pet/{petId}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + '{' . 'petId' . '}', + ObjectSerializer::toPathValue($pet_id), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', '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); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $headers['api_key'] = $apiKey; + } + + $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 updatePet + * + * Update an existing pet + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function updatePet($body, string $contentType = self::contentTypes['updatePet'][0]) + { + $this->updatePetWithHttpInfo($body, $contentType); + } + + /** + * Operation updatePetWithHttpInfo + * + * Update an existing pet + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 updatePetWithHttpInfo($body, string $contentType = self::contentTypes['updatePet'][0]) + { + $request = $this->updatePetRequest($body, $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()) { + } + + + throw $e; + } + } + + /** + * Operation updatePetAsync + * + * Update an existing pet + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updatePetAsync($body, string $contentType = self::contentTypes['updatePet'][0]) + { + return $this->updatePetAsyncWithHttpInfo($body, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation updatePetAsyncWithHttpInfo + * + * Update an existing pet + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updatePetAsyncWithHttpInfo($body, string $contentType = self::contentTypes['updatePet'][0]) + { + $returnType = ''; + $request = $this->updatePetRequest($body, $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 'updatePet' + * + * @param \OpenAPI\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function updatePetRequest($body, string $contentType = self::contentTypes['updatePet'][0]) + { + + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling updatePet' + ); + } + + + $resourcePath = '/pet'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + [], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($body)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); + } else { + $httpBody = $body; + } + } 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); + } + } + + // this endpoint requires OAuth (access token) + if (!empty($this->config->getAccessToken())) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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 updatePetWithForm + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string|null $name Updated name of the pet (optional) + * @param string|null $status Updated status of the pet (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function updatePetWithForm($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) + { + $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status, $contentType); + } + + /** + * Operation updatePetWithFormWithHttpInfo + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string|null $name Updated name of the pet (optional) + * @param string|null $status Updated status of the pet (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) + { + $request = $this->updatePetWithFormRequest($pet_id, $name, $status, $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()) { + } + + + throw $e; + } + } + + /** + * Operation updatePetWithFormAsync + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string|null $name Updated name of the pet (optional) + * @param string|null $status Updated status of the pet (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updatePetWithFormAsync($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) + { + return $this->updatePetWithFormAsyncWithHttpInfo($pet_id, $name, $status, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation updatePetWithFormAsyncWithHttpInfo + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string|null $name Updated name of the pet (optional) + * @param string|null $status Updated status of the pet (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updatePetWithFormAsyncWithHttpInfo($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) + { + $returnType = ''; + $request = $this->updatePetWithFormRequest($pet_id, $name, $status, $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 'updatePetWithForm' + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string|null $name Updated name of the pet (optional) + * @param string|null $status Updated status of the pet (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function updatePetWithFormRequest($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) + { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet_id when calling updatePetWithForm' + ); + } + + + + + $resourcePath = '/pet/{petId}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + '{' . 'petId' . '}', + ObjectSerializer::toPathValue($pet_id), + $resourcePath + ); + } + + // form params + $formDataProcessor = new FormDataProcessor(); + + $formData = $formDataProcessor->prepare([ + 'name' => $name, + 'status' => $status, + ]); + + $formParams = $formDataProcessor->flatten($formData); + $multipart = $formDataProcessor->has_file; + + $headers = $this->headerSelector->selectHeaders( + [], + $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); + } + } + + // this endpoint requires OAuth (access token) + if (!empty($this->config->getAccessToken())) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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 uploadFile + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string|null $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject|null $file file to upload (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\ApiResponse + */ + public function uploadFile($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) + { + list($response) = $this->uploadFileWithHttpInfo($pet_id, $additional_metadata, $file, $contentType); + return $response; + } + + /** + * Operation uploadFileWithHttpInfo + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string|null $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject|null $file file to upload (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) + */ + public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) + { + $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file, $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( + '\OpenAPI\Client\Model\ApiResponse', + $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( + '\OpenAPI\Client\Model\ApiResponse', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\ApiResponse', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation uploadFileAsync + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string|null $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject|null $file file to upload (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function uploadFileAsync($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) + { + return $this->uploadFileAsyncWithHttpInfo($pet_id, $additional_metadata, $file, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation uploadFileAsyncWithHttpInfo + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string|null $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject|null $file file to upload (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function uploadFileAsyncWithHttpInfo($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) + { + $returnType = '\OpenAPI\Client\Model\ApiResponse'; + $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file, $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 'uploadFile' + * + * @param int $pet_id ID of pet to update (required) + * @param string|null $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject|null $file file to upload (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function uploadFileRequest($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) + { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $pet_id when calling uploadFile' + ); + } + + + + + $resourcePath = '/pet/{petId}/uploadImage'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + '{' . 'petId' . '}', + ObjectSerializer::toPathValue($pet_id), + $resourcePath + ); + } + + // form params + $formDataProcessor = new FormDataProcessor(); + + $formData = $formDataProcessor->prepare([ + 'additional_metadata' => $additional_metadata, + 'file' => $file, + ]); + + $formParams = $formDataProcessor->flatten($formData); + $multipart = $formDataProcessor->has_file; + + $multipart = true; + $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); + } + } + + // this endpoint requires OAuth (access token) + if (!empty($this->config->getAccessToken())) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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()); + } + } + + 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; + } +} diff --git a/samples/client/petstore/php/lib/Api/StoreApi.php b/samples/client/petstore/php/lib/Api/StoreApi.php new file mode 100644 index 000000000000..b0ff8ba18e62 --- /dev/null +++ b/samples/client/petstore/php/lib/Api/StoreApi.php @@ -0,0 +1,1210 @@ + [ + 'application/json', + ], + 'getInventory' => [ + 'application/json', + ], + 'getOrderById' => [ + 'application/json', + ], + 'placeOrder' => [ + '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 deleteOrder + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function deleteOrder($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) + { + $this->deleteOrderWithHttpInfo($order_id, $contentType); + } + + /** + * Operation deleteOrderWithHttpInfo + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 deleteOrderWithHttpInfo($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) + { + $request = $this->deleteOrderRequest($order_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()) { + } + + + throw $e; + } + } + + /** + * Operation deleteOrderAsync + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deleteOrderAsync($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) + { + return $this->deleteOrderAsyncWithHttpInfo($order_id, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation deleteOrderAsyncWithHttpInfo + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deleteOrderAsyncWithHttpInfo($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) + { + $returnType = ''; + $request = $this->deleteOrderRequest($order_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 'deleteOrder' + * + * @param string $order_id ID of the order that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function deleteOrderRequest($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) + { + + // verify the required parameter 'order_id' is set + if ($order_id === null || (is_array($order_id) && count($order_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $order_id when calling deleteOrder' + ); + } + + + $resourcePath = '/store/order/{orderId}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($order_id !== null) { + $resourcePath = str_replace( + '{' . 'orderId' . '}', + ObjectSerializer::toPathValue($order_id), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + [], + $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 getInventory + * + * Returns pet inventories by status + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array + */ + public function getInventory(string $contentType = self::contentTypes['getInventory'][0]) + { + list($response) = $this->getInventoryWithHttpInfo($contentType); + return $response; + } + + /** + * Operation getInventoryWithHttpInfo + * + * Returns pet inventories by status + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of array, HTTP status code, HTTP response headers (array of strings) + */ + public function getInventoryWithHttpInfo(string $contentType = self::contentTypes['getInventory'][0]) + { + $request = $this->getInventoryRequest($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( + 'array', + $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( + 'array', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'array', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getInventoryAsync + * + * Returns pet inventories by status + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getInventoryAsync(string $contentType = self::contentTypes['getInventory'][0]) + { + return $this->getInventoryAsyncWithHttpInfo($contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getInventoryAsyncWithHttpInfo + * + * Returns pet inventories by status + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getInventoryAsyncWithHttpInfo(string $contentType = self::contentTypes['getInventory'][0]) + { + $returnType = 'array'; + $request = $this->getInventoryRequest($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 'getInventory' + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getInventoryRequest(string $contentType = self::contentTypes['getInventory'][0]) + { + + + $resourcePath = '/store/inventory'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $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); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $headers['api_key'] = $apiKey; + } + + $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 getOrderById + * + * Find purchase order by ID + * + * @param int $order_id ID of pet that needs to be fetched (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\Order + */ + public function getOrderById($order_id, string $contentType = self::contentTypes['getOrderById'][0]) + { + list($response) = $this->getOrderByIdWithHttpInfo($order_id, $contentType); + return $response; + } + + /** + * Operation getOrderByIdWithHttpInfo + * + * Find purchase order by ID + * + * @param int $order_id ID of pet that needs to be fetched (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) + */ + public function getOrderByIdWithHttpInfo($order_id, string $contentType = self::contentTypes['getOrderById'][0]) + { + $request = $this->getOrderByIdRequest($order_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(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\Order', + $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( + '\OpenAPI\Client\Model\Order', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\Order', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getOrderByIdAsync + * + * Find purchase order by ID + * + * @param int $order_id ID of pet that needs to be fetched (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getOrderByIdAsync($order_id, string $contentType = self::contentTypes['getOrderById'][0]) + { + return $this->getOrderByIdAsyncWithHttpInfo($order_id, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getOrderByIdAsyncWithHttpInfo + * + * Find purchase order by ID + * + * @param int $order_id ID of pet that needs to be fetched (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getOrderByIdAsyncWithHttpInfo($order_id, string $contentType = self::contentTypes['getOrderById'][0]) + { + $returnType = '\OpenAPI\Client\Model\Order'; + $request = $this->getOrderByIdRequest($order_id, $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 'getOrderById' + * + * @param int $order_id ID of pet that needs to be fetched (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getOrderByIdRequest($order_id, string $contentType = self::contentTypes['getOrderById'][0]) + { + + // verify the required parameter 'order_id' is set + if ($order_id === null || (is_array($order_id) && count($order_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $order_id when calling getOrderById' + ); + } + if ($order_id > 5) { + throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be smaller than or equal to 5.'); + } + if ($order_id < 1) { + throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.'); + } + + + $resourcePath = '/store/order/{orderId}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($order_id !== null) { + $resourcePath = str_replace( + '{' . 'orderId' . '}', + ObjectSerializer::toPathValue($order_id), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', '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 placeOrder + * + * Place an order for a pet + * + * @param \OpenAPI\Client\Model\Order $body order placed for purchasing the pet (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\Order + */ + public function placeOrder($body, string $contentType = self::contentTypes['placeOrder'][0]) + { + list($response) = $this->placeOrderWithHttpInfo($body, $contentType); + return $response; + } + + /** + * Operation placeOrderWithHttpInfo + * + * Place an order for a pet + * + * @param \OpenAPI\Client\Model\Order $body order placed for purchasing the pet (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) + */ + public function placeOrderWithHttpInfo($body, string $contentType = self::contentTypes['placeOrder'][0]) + { + $request = $this->placeOrderRequest($body, $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( + '\OpenAPI\Client\Model\Order', + $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( + '\OpenAPI\Client\Model\Order', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\Order', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation placeOrderAsync + * + * Place an order for a pet + * + * @param \OpenAPI\Client\Model\Order $body order placed for purchasing the pet (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function placeOrderAsync($body, string $contentType = self::contentTypes['placeOrder'][0]) + { + return $this->placeOrderAsyncWithHttpInfo($body, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation placeOrderAsyncWithHttpInfo + * + * Place an order for a pet + * + * @param \OpenAPI\Client\Model\Order $body order placed for purchasing the pet (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function placeOrderAsyncWithHttpInfo($body, string $contentType = self::contentTypes['placeOrder'][0]) + { + $returnType = '\OpenAPI\Client\Model\Order'; + $request = $this->placeOrderRequest($body, $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 'placeOrder' + * + * @param \OpenAPI\Client\Model\Order $body order placed for purchasing the pet (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function placeOrderRequest($body, string $contentType = self::contentTypes['placeOrder'][0]) + { + + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling placeOrder' + ); + } + + + $resourcePath = '/store/order'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($body)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); + } else { + $httpBody = $body; + } + } 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()); + } + } + + 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; + } +} diff --git a/samples/client/petstore/php/lib/Api/UserApi.php b/samples/client/petstore/php/lib/Api/UserApi.php new file mode 100644 index 000000000000..198f53730bdf --- /dev/null +++ b/samples/client/petstore/php/lib/Api/UserApi.php @@ -0,0 +1,2072 @@ + [ + 'application/json', + ], + 'createUsersWithArrayInput' => [ + 'application/json', + ], + 'createUsersWithListInput' => [ + 'application/json', + ], + 'deleteUser' => [ + 'application/json', + ], + 'getUserByName' => [ + 'application/json', + ], + 'loginUser' => [ + 'application/json', + ], + 'logoutUser' => [ + 'application/json', + ], + 'updateUser' => [ + '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 createUser + * + * Create user + * + * @param \OpenAPI\Client\Model\User $body Created user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function createUser($body, string $contentType = self::contentTypes['createUser'][0]) + { + $this->createUserWithHttpInfo($body, $contentType); + } + + /** + * Operation createUserWithHttpInfo + * + * Create user + * + * @param \OpenAPI\Client\Model\User $body Created user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 createUserWithHttpInfo($body, string $contentType = self::contentTypes['createUser'][0]) + { + $request = $this->createUserRequest($body, $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()) { + } + + + throw $e; + } + } + + /** + * Operation createUserAsync + * + * Create user + * + * @param \OpenAPI\Client\Model\User $body Created user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUserAsync($body, string $contentType = self::contentTypes['createUser'][0]) + { + return $this->createUserAsyncWithHttpInfo($body, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation createUserAsyncWithHttpInfo + * + * Create user + * + * @param \OpenAPI\Client\Model\User $body Created user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUserAsyncWithHttpInfo($body, string $contentType = self::contentTypes['createUser'][0]) + { + $returnType = ''; + $request = $this->createUserRequest($body, $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 'createUser' + * + * @param \OpenAPI\Client\Model\User $body Created user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function createUserRequest($body, string $contentType = self::contentTypes['createUser'][0]) + { + + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling createUser' + ); + } + + + $resourcePath = '/user'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + [], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($body)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); + } else { + $httpBody = $body; + } + } 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 createUsersWithArrayInput + * + * Creates list of users with given input array + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function createUsersWithArrayInput($body, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) + { + $this->createUsersWithArrayInputWithHttpInfo($body, $contentType); + } + + /** + * Operation createUsersWithArrayInputWithHttpInfo + * + * Creates list of users with given input array + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 createUsersWithArrayInputWithHttpInfo($body, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) + { + $request = $this->createUsersWithArrayInputRequest($body, $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()) { + } + + + throw $e; + } + } + + /** + * Operation createUsersWithArrayInputAsync + * + * Creates list of users with given input array + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUsersWithArrayInputAsync($body, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) + { + return $this->createUsersWithArrayInputAsyncWithHttpInfo($body, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation createUsersWithArrayInputAsyncWithHttpInfo + * + * Creates list of users with given input array + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUsersWithArrayInputAsyncWithHttpInfo($body, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) + { + $returnType = ''; + $request = $this->createUsersWithArrayInputRequest($body, $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 'createUsersWithArrayInput' + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function createUsersWithArrayInputRequest($body, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) + { + + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling createUsersWithArrayInput' + ); + } + + + $resourcePath = '/user/createWithArray'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + [], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($body)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); + } else { + $httpBody = $body; + } + } 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 createUsersWithListInput + * + * Creates list of users with given input array + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function createUsersWithListInput($body, string $contentType = self::contentTypes['createUsersWithListInput'][0]) + { + $this->createUsersWithListInputWithHttpInfo($body, $contentType); + } + + /** + * Operation createUsersWithListInputWithHttpInfo + * + * Creates list of users with given input array + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 createUsersWithListInputWithHttpInfo($body, string $contentType = self::contentTypes['createUsersWithListInput'][0]) + { + $request = $this->createUsersWithListInputRequest($body, $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()) { + } + + + throw $e; + } + } + + /** + * Operation createUsersWithListInputAsync + * + * Creates list of users with given input array + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUsersWithListInputAsync($body, string $contentType = self::contentTypes['createUsersWithListInput'][0]) + { + return $this->createUsersWithListInputAsyncWithHttpInfo($body, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation createUsersWithListInputAsyncWithHttpInfo + * + * Creates list of users with given input array + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function createUsersWithListInputAsyncWithHttpInfo($body, string $contentType = self::contentTypes['createUsersWithListInput'][0]) + { + $returnType = ''; + $request = $this->createUsersWithListInputRequest($body, $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 'createUsersWithListInput' + * + * @param \OpenAPI\Client\Model\User[] $body List of user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function createUsersWithListInputRequest($body, string $contentType = self::contentTypes['createUsersWithListInput'][0]) + { + + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling createUsersWithListInput' + ); + } + + + $resourcePath = '/user/createWithList'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + [], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($body)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); + } else { + $httpBody = $body; + } + } 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 deleteUser + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function deleteUser($username, string $contentType = self::contentTypes['deleteUser'][0]) + { + $this->deleteUserWithHttpInfo($username, $contentType); + } + + /** + * Operation deleteUserWithHttpInfo + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 deleteUserWithHttpInfo($username, string $contentType = self::contentTypes['deleteUser'][0]) + { + $request = $this->deleteUserRequest($username, $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()) { + } + + + throw $e; + } + } + + /** + * Operation deleteUserAsync + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deleteUserAsync($username, string $contentType = self::contentTypes['deleteUser'][0]) + { + return $this->deleteUserAsyncWithHttpInfo($username, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation deleteUserAsyncWithHttpInfo + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function deleteUserAsyncWithHttpInfo($username, string $contentType = self::contentTypes['deleteUser'][0]) + { + $returnType = ''; + $request = $this->deleteUserRequest($username, $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 'deleteUser' + * + * @param string $username The name that needs to be deleted (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function deleteUserRequest($username, string $contentType = self::contentTypes['deleteUser'][0]) + { + + // verify the required parameter 'username' is set + if ($username === null || (is_array($username) && count($username) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $username when calling deleteUser' + ); + } + + + $resourcePath = '/user/{username}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($username !== null) { + $resourcePath = str_replace( + '{' . 'username' . '}', + ObjectSerializer::toPathValue($username), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + [], + $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 getUserByName + * + * Get user by user name + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\User + */ + public function getUserByName($username, string $contentType = self::contentTypes['getUserByName'][0]) + { + list($response) = $this->getUserByNameWithHttpInfo($username, $contentType); + return $response; + } + + /** + * Operation getUserByNameWithHttpInfo + * + * Get user by user name + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\User, HTTP status code, HTTP response headers (array of strings) + */ + public function getUserByNameWithHttpInfo($username, string $contentType = self::contentTypes['getUserByName'][0]) + { + $request = $this->getUserByNameRequest($username, $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( + '\OpenAPI\Client\Model\User', + $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( + '\OpenAPI\Client\Model\User', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\User', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getUserByNameAsync + * + * Get user by user name + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getUserByNameAsync($username, string $contentType = self::contentTypes['getUserByName'][0]) + { + return $this->getUserByNameAsyncWithHttpInfo($username, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getUserByNameAsyncWithHttpInfo + * + * Get user by user name + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getUserByNameAsyncWithHttpInfo($username, string $contentType = self::contentTypes['getUserByName'][0]) + { + $returnType = '\OpenAPI\Client\Model\User'; + $request = $this->getUserByNameRequest($username, $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 'getUserByName' + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getUserByNameRequest($username, string $contentType = self::contentTypes['getUserByName'][0]) + { + + // verify the required parameter 'username' is set + if ($username === null || (is_array($username) && count($username) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $username when calling getUserByName' + ); + } + + + $resourcePath = '/user/{username}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($username !== null) { + $resourcePath = str_replace( + '{' . 'username' . '}', + ObjectSerializer::toPathValue($username), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', '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 loginUser + * + * Logs user into the system + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return string + */ + public function loginUser($username, $password, string $contentType = self::contentTypes['loginUser'][0]) + { + list($response) = $this->loginUserWithHttpInfo($username, $password, $contentType); + return $response; + } + + /** + * Operation loginUserWithHttpInfo + * + * Logs user into the system + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of string, HTTP status code, HTTP response headers (array of strings) + */ + public function loginUserWithHttpInfo($username, $password, string $contentType = self::contentTypes['loginUser'][0]) + { + $request = $this->loginUserRequest($username, $password, $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( + 'string', + $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( + 'string', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'string', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation loginUserAsync + * + * Logs user into the system + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function loginUserAsync($username, $password, string $contentType = self::contentTypes['loginUser'][0]) + { + return $this->loginUserAsyncWithHttpInfo($username, $password, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation loginUserAsyncWithHttpInfo + * + * Logs user into the system + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function loginUserAsyncWithHttpInfo($username, $password, string $contentType = self::contentTypes['loginUser'][0]) + { + $returnType = 'string'; + $request = $this->loginUserRequest($username, $password, $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 'loginUser' + * + * @param string $username The user name for login (required) + * @param string $password The password for login in clear text (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function loginUserRequest($username, $password, string $contentType = self::contentTypes['loginUser'][0]) + { + + // verify the required parameter 'username' is set + if ($username === null || (is_array($username) && count($username) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $username when calling loginUser' + ); + } + + // verify the required parameter 'password' is set + if ($password === null || (is_array($password) && count($password) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $password when calling loginUser' + ); + } + + + $resourcePath = '/user/login'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $username, + 'username', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $password, + 'password', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', '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 logoutUser + * + * Logs out current logged in user session + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function logoutUser(string $contentType = self::contentTypes['logoutUser'][0]) + { + $this->logoutUserWithHttpInfo($contentType); + } + + /** + * Operation logoutUserWithHttpInfo + * + * Logs out current logged in user session + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 logoutUserWithHttpInfo(string $contentType = self::contentTypes['logoutUser'][0]) + { + $request = $this->logoutUserRequest($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()) { + } + + + throw $e; + } + } + + /** + * Operation logoutUserAsync + * + * Logs out current logged in user session + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function logoutUserAsync(string $contentType = self::contentTypes['logoutUser'][0]) + { + return $this->logoutUserAsyncWithHttpInfo($contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation logoutUserAsyncWithHttpInfo + * + * Logs out current logged in user session + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function logoutUserAsyncWithHttpInfo(string $contentType = self::contentTypes['logoutUser'][0]) + { + $returnType = ''; + $request = $this->logoutUserRequest($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 'logoutUser' + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function logoutUserRequest(string $contentType = self::contentTypes['logoutUser'][0]) + { + + + $resourcePath = '/user/logout'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + [], + $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 updateUser + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param \OpenAPI\Client\Model\User $body Updated user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function updateUser($username, $body, string $contentType = self::contentTypes['updateUser'][0]) + { + $this->updateUserWithHttpInfo($username, $body, $contentType); + } + + /** + * Operation updateUserWithHttpInfo + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param \OpenAPI\Client\Model\User $body Updated user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\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 updateUserWithHttpInfo($username, $body, string $contentType = self::contentTypes['updateUser'][0]) + { + $request = $this->updateUserRequest($username, $body, $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()) { + } + + + throw $e; + } + } + + /** + * Operation updateUserAsync + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param \OpenAPI\Client\Model\User $body Updated user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updateUserAsync($username, $body, string $contentType = self::contentTypes['updateUser'][0]) + { + return $this->updateUserAsyncWithHttpInfo($username, $body, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation updateUserAsyncWithHttpInfo + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param \OpenAPI\Client\Model\User $body Updated user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function updateUserAsyncWithHttpInfo($username, $body, string $contentType = self::contentTypes['updateUser'][0]) + { + $returnType = ''; + $request = $this->updateUserRequest($username, $body, $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 'updateUser' + * + * @param string $username name that need to be deleted (required) + * @param \OpenAPI\Client\Model\User $body Updated user object (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function updateUserRequest($username, $body, string $contentType = self::contentTypes['updateUser'][0]) + { + + // verify the required parameter 'username' is set + if ($username === null || (is_array($username) && count($username) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $username when calling updateUser' + ); + } + + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling updateUser' + ); + } + + + $resourcePath = '/user/{username}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($username !== null) { + $resourcePath = str_replace( + '{' . 'username' . '}', + ObjectSerializer::toPathValue($username), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + [], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($body)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); + } else { + $httpBody = $body; + } + } 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 + ); + } + + /** + * 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; + } + + 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; + } +} diff --git a/samples/client/petstore/php/lib/ApiException.php b/samples/client/petstore/php/lib/ApiException.php new file mode 100644 index 000000000000..01118b816726 --- /dev/null +++ b/samples/client/petstore/php/lib/ApiException.php @@ -0,0 +1,119 @@ +responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; + } + + /** + * Gets the HTTP response header + * + * @return string[][]|null HTTP response header + */ + public function getResponseHeaders() + { + return $this->responseHeaders; + } + + /** + * Gets the HTTP body of the server response either as Json or string + * + * @return \stdClass|string|null HTTP body of the server response either as \stdClass or string + */ + public function getResponseBody() + { + return $this->responseBody; + } + + /** + * Sets the deserialized response object (during deserialization) + * + * @param mixed $obj Deserialized response object + * + * @return void + */ + public function setResponseObject($obj) + { + $this->responseObject = $obj; + } + + /** + * Gets the deserialized response object (during deserialization) + * + * @return mixed the deserialized response object + */ + public function getResponseObject() + { + return $this->responseObject; + } +} diff --git a/samples/client/petstore/php/lib/Configuration.php b/samples/client/petstore/php/lib/Configuration.php new file mode 100644 index 000000000000..bbdce3e73ba2 --- /dev/null +++ b/samples/client/petstore/php/lib/Configuration.php @@ -0,0 +1,531 @@ +tempFolderPath = sys_get_temp_dir(); + } + + /** + * Sets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $key API key or token + * + * @return $this + */ + public function setApiKey($apiKeyIdentifier, $key) + { + $this->apiKeys[$apiKeyIdentifier] = $key; + return $this; + } + + /** + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return null|string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return $this + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return null|string + */ + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; + } + + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return $this + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Sets boolean format for query string. + * + * @param string $booleanFormat Boolean format for query string + * + * @return $this + */ + public function setBooleanFormatForQueryString(string $booleanFormat) + { + $this->booleanFormatForQueryString = $booleanFormat; + + return $this; + } + + /** + * Gets boolean format for query string. + * + * @return string Boolean format for query string + */ + public function getBooleanFormatForQueryString(): string + { + return $this->booleanFormatForQueryString; + } + + /** + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * + * @return $this + */ + public function setUsername($username) + { + $this->username = $username; + return $this; + } + + /** + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * + * @return $this + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + /** + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication + */ + public function getPassword() + { + return $this->password; + } + + /** + * Sets the host + * + * @param string $host Host + * + * @return $this + */ + public function setHost($host) + { + $this->host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setUserAgent($userAgent) + { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * Gets the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Sets debug flag + * + * @param bool $debug Debug flag + * + * @return $this + */ + public function setDebug($debug) + { + $this->debug = $debug; + return $this; + } + + /** + * Gets the debug flag + * + * @return bool + */ + public function getDebug() + { + return $this->debug; + } + + /** + * Sets the debug file + * + * @param string $debugFile Debug file + * + * @return $this + */ + public function setDebugFile($debugFile) + { + $this->debugFile = $debugFile; + return $this; + } + + /** + * Gets the debug file + * + * @return string + */ + public function getDebugFile() + { + return $this->debugFile; + } + + /** + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * + * @return $this + */ + public function setTempFolderPath($tempFolderPath) + { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * Gets the temp folder path + * + * @return string Temp folder path + */ + public function getTempFolderPath() + { + return $this->tempFolderPath; + } + + /** + * Gets the default configuration instance + * + * @return Configuration + */ + public static function getDefaultConfiguration() + { + if (self::$defaultConfiguration === null) { + self::$defaultConfiguration = new Configuration(); + } + + return self::$defaultConfiguration; + } + + /** + * Sets the default configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void + */ + public static function setDefaultConfiguration(Configuration $config) + { + self::$defaultConfiguration = $config; + } + + /** + * Gets the essential information for debugging + * + * @return string The report for debugging + */ + public static function toDebugReport() + { + $report = 'PHP SDK (OpenAPI\Client) Debug Report:' . PHP_EOL; + $report .= ' OS: ' . php_uname() . PHP_EOL; + $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; + $report .= ' The version of the OpenAPI document: 1.0.0' . PHP_EOL; + $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; + + return $report; + } + + /** + * Get API key (with prefix if set) + * + * @param string $apiKeyIdentifier name of apikey + * + * @return null|string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) + { + $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->getApiKey($apiKeyIdentifier); + + if ($apiKey === null) { + return null; + } + + if ($prefix === null) { + $keyWithPrefix = $apiKey; + } else { + $keyWithPrefix = $prefix . ' ' . $apiKey; + } + + return $keyWithPrefix; + } + + /** + * Returns an array of host settings + * + * @return array an array of host settings + */ + public function getHostSettings() + { + return [ + [ + "url" => "http://petstore.swagger.io/v2", + "description" => "No description provided", + ] + ]; + } + + /** + * Returns URL based on host settings, index and variables + * + * @param array $hostSettings array of host settings, generated from getHostSettings() or equivalent from the API clients + * @param int $hostIndex index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public static function getHostString(array $hostSettings, $hostIndex, ?array $variables = null) + { + if (null === $variables) { + $variables = []; + } + + // check array index out of bound + if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { + throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostSettings)); + } + + $host = $hostSettings[$hostIndex]; + $url = $host["url"]; + + // go through variable and assign a value + foreach ($host["variables"] ?? [] as $name => $variable) { + if (array_key_exists($name, $variables)) { // check to see if it's in the variables provided by the user + if (!isset($variable['enum_values']) || in_array($variables[$name], $variable["enum_values"], true)) { // check to see if the value is in the enum + $url = str_replace("{".$name."}", $variables[$name], $url); + } else { + throw new \InvalidArgumentException("The variable `$name` in the host URL has invalid value ".$variables[$name].". Must be ".join(',', $variable["enum_values"])."."); + } + } else { + // use default value + $url = str_replace("{".$name."}", $variable["default_value"], $url); + } + } + + return $url; + } + + /** + * Returns URL based on the index and variables + * + * @param int $index index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public function getHostFromSettings($index, $variables = null) + { + return self::getHostString($this->getHostSettings(), $index, $variables); + } +} diff --git a/samples/client/petstore/php/lib/FormDataProcessor.php b/samples/client/petstore/php/lib/FormDataProcessor.php new file mode 100644 index 000000000000..7d87e519b51d --- /dev/null +++ b/samples/client/petstore/php/lib/FormDataProcessor.php @@ -0,0 +1,242 @@ + $values the value of the form parameter + * + * @return array [key => value] of formdata + */ + public function prepare(array $values): array + { + $this->has_file = false; + $result = []; + + foreach ($values as $k => $v) { + if ($v === null) { + continue; + } + + $result[$k] = $this->makeFormSafe($v); + } + + return $result; + } + + /** + * Flattens a multi-level array of data and generates a single-level array + * compatible with formdata - a single-level array where the keys use bracket + * notation to signify nested data. + * + * credit: https://github.com/FranBar1966/FlatPHP + */ + public static function flatten(array $source, string $start = ''): array + { + $opt = [ + 'prefix' => '[', + 'suffix' => ']', + 'suffix-end' => true, + 'prefix-list' => '[', + 'suffix-list' => ']', + 'suffix-list-end' => true, + ]; + + if ($start === '') { + $currentPrefix = ''; + $currentSuffix = ''; + $currentSuffixEnd = false; + } elseif (array_is_list($source)) { + $currentPrefix = $opt['prefix-list']; + $currentSuffix = $opt['suffix-list']; + $currentSuffixEnd = $opt['suffix-list-end']; + } else { + $currentPrefix = $opt['prefix']; + $currentSuffix = $opt['suffix']; + $currentSuffixEnd = $opt['suffix-end']; + } + + $currentName = $start; + $result = []; + + foreach ($source as $key => $val) { + $currentName .= $currentPrefix.$key; + + if (is_array($val) && !empty($val)) { + $currentName .= $currentSuffix; + $result += self::flatten($val, $currentName); + } else { + if ($currentSuffixEnd) { + $currentName .= $currentSuffix; + } + + $result[$currentName] = ObjectSerializer::toString($val); + } + + $currentName = $start; + } + + return $result; + } + + /** + * formdata must be limited to scalars or arrays of scalar values, + * or a resource for a file upload. Here we iterate through all available + * data and identify how to handle each scenario + */ + protected function makeFormSafe($value) + { + if ($value instanceof SplFileObject) { + return $this->processFiles([$value])[0]; + } + + if (is_resource($value)) { + $this->has_file = true; + + return $value; + } + + if ($value instanceof ModelInterface) { + return $this->processModel($value); + } + + if (is_array($value) || (is_object($value) && !$value instanceof \DateTimeInterface)) { + $data = []; + + foreach ($value as $k => $v) { + $data[$k] = $this->makeFormSafe($v); + } + + return $data; + } + + return ObjectSerializer::toString($value); + } + + /** + * We are able to handle nested ModelInterface. We do not simply call + * json_decode(json_encode()) because any given model may have binary data + * or other data that cannot be serialized to a JSON string + */ + protected function processModel(ModelInterface $model): array + { + $result = []; + + foreach ($model::openAPITypes() as $name => $type) { + $value = $model->offsetGet($name); + + if ($value === null) { + continue; + } + + if (strpos($type, '\SplFileObject') !== false) { + $file = is_array($value) ? $value : [$value]; + $result[$name] = $this->processFiles($file); + + continue; + } + + if ($value instanceof ModelInterface) { + $result[$name] = $this->processModel($value); + + continue; + } + + if (is_array($value) || is_object($value)) { + $result[$name] = $this->makeFormSafe($value); + + continue; + } + + $result[$name] = ObjectSerializer::toString($value); + } + + return $result; + } + + /** + * Handle file data + */ + protected function processFiles(array $files): array + { + $this->has_file = true; + + $result = []; + + foreach ($files as $i => $file) { + if (is_array($file)) { + $result[$i] = $this->processFiles($file); + + continue; + } + + if ($file instanceof StreamInterface) { + $result[$i] = $file; + + continue; + } + + if ($file instanceof SplFileObject) { + $result[$i] = $this->tryFopen($file); + } + } + + return $result; + } + + private function tryFopen(SplFileObject $file) + { + return Utils::tryFopen($file->getRealPath(), 'rb'); + } +} diff --git a/samples/client/petstore/php/lib/HeaderSelector.php b/samples/client/petstore/php/lib/HeaderSelector.php new file mode 100644 index 000000000000..49d0b27d4353 --- /dev/null +++ b/samples/client/petstore/php/lib/HeaderSelector.php @@ -0,0 +1,273 @@ +selectAcceptHeader($accept); + if ($accept !== null) { + $headers['Accept'] = $accept; + } + + if (!$isMultipart) { + if($contentType === '') { + $contentType = 'application/json'; + } + + $headers['Content-Type'] = $contentType; + } + + return $headers; + } + + /** + * Return the header 'Accept' based on an array of Accept provided. + * + * @param string[] $accept Array of header + * + * @return null|string Accept (e.g. application/json) + */ + private function selectAcceptHeader(array $accept): ?string + { + # filter out empty entries + $accept = array_filter($accept); + + if (count($accept) === 0) { + return null; + } + + # If there's only one Accept header, just use it + if (count($accept) === 1) { + return reset($accept); + } + + # If none of the available Accept headers is of type "json", then just use all them + $headersWithJson = $this->selectJsonMimeList($accept); + if (count($headersWithJson) === 0) { + return implode(',', $accept); + } + + # If we got here, then we need add quality values (weight), as described in IETF RFC 9110, Items 12.4.2/12.5.1, + # to give the highest priority to json-like headers - recalculating the existing ones, if needed + return $this->getAcceptHeaderWithAdjustedWeight($accept, $headersWithJson); + } + + /** + * Detects whether a string contains a valid JSON mime type + * + * @param string $searchString + * @return bool + */ + public function isJsonMime(string $searchString): bool + { + return preg_match('~^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)~', $searchString) === 1; + } + + /** + * Select all items from a list containing a JSON mime type + * + * @param array $mimeList + * @return array + */ + private function selectJsonMimeList(array $mimeList): array { + $jsonMimeList = []; + foreach ($mimeList as $mime) { + if($this->isJsonMime($mime)) { + $jsonMimeList[] = $mime; + } + } + return $jsonMimeList; + } + + + /** + * Create an Accept header string from the given "Accept" headers array, recalculating all weights + * + * @param string[] $accept Array of Accept Headers + * @param string[] $headersWithJson Array of Accept Headers of type "json" + * + * @return string "Accept" Header (e.g. "application/json, text/html; q=0.9") + */ + private function getAcceptHeaderWithAdjustedWeight(array $accept, array $headersWithJson): string + { + $processedHeaders = [ + 'withApplicationJson' => [], + 'withJson' => [], + 'withoutJson' => [], + ]; + + foreach ($accept as $header) { + + $headerData = $this->getHeaderAndWeight($header); + + if (stripos($headerData['header'], 'application/json') === 0) { + $processedHeaders['withApplicationJson'][] = $headerData; + } elseif (in_array($header, $headersWithJson, true)) { + $processedHeaders['withJson'][] = $headerData; + } else { + $processedHeaders['withoutJson'][] = $headerData; + } + } + + $acceptHeaders = []; + $currentWeight = 1000; + + $hasMoreThan28Headers = count($accept) > 28; + + foreach($processedHeaders as $headers) { + if (count($headers) > 0) { + $acceptHeaders[] = $this->adjustWeight($headers, $currentWeight, $hasMoreThan28Headers); + } + } + + $acceptHeaders = array_merge(...$acceptHeaders); + + return implode(',', $acceptHeaders); + } + + /** + * Given an Accept header, returns an associative array splitting the header and its weight + * + * @param string $header "Accept" Header + * + * @return array with the header and its weight + */ + private function getHeaderAndWeight(string $header): array + { + # matches headers with weight, splitting the header and the weight in $outputArray + if (preg_match('/(.*);\s*q=(1(?:\.0+)?|0\.\d+)$/', $header, $outputArray) === 1) { + $headerData = [ + 'header' => $outputArray[1], + 'weight' => (int)($outputArray[2] * 1000), + ]; + } else { + $headerData = [ + 'header' => trim($header), + 'weight' => 1000, + ]; + } + + return $headerData; + } + + /** + * @param array[] $headers + * @param float $currentWeight + * @param bool $hasMoreThan28Headers + * @return string[] array of adjusted "Accept" headers + */ + private function adjustWeight(array $headers, float &$currentWeight, bool $hasMoreThan28Headers): array + { + usort($headers, function (array $a, array $b) { + return $b['weight'] - $a['weight']; + }); + + $acceptHeaders = []; + foreach ($headers as $index => $header) { + if($index > 0 && $headers[$index - 1]['weight'] > $header['weight']) + { + $currentWeight = $this->getNextWeight($currentWeight, $hasMoreThan28Headers); + } + + $weight = $currentWeight; + + $acceptHeaders[] = $this->buildAcceptHeader($header['header'], $weight); + } + + $currentWeight = $this->getNextWeight($currentWeight, $hasMoreThan28Headers); + + return $acceptHeaders; + } + + /** + * @param string $header + * @param int $weight + * @return string + */ + private function buildAcceptHeader(string $header, int $weight): string + { + if($weight === 1000) { + return $header; + } + + return trim($header, '; ') . ';q=' . rtrim(sprintf('%0.3f', $weight / 1000), '0'); + } + + /** + * Calculate the next weight, based on the current one. + * + * If there are less than 28 "Accept" headers, the weights will be decreased by 1 on its highest significant digit, using the + * following formula: + * + * next weight = current weight - 10 ^ (floor(log(current weight - 1))) + * + * ( current weight minus ( 10 raised to the power of ( floor of (log to the base 10 of ( current weight minus 1 ) ) ) ) ) + * + * Starting from 1000, this generates the following series: + * + * 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 + * + * The resulting quality codes are closer to the average "normal" usage of them (like "q=0.9", "q=0.8" and so on), but it only works + * if there is a maximum of 28 "Accept" headers. If we have more than that (which is extremely unlikely), then we fall back to a 1-by-1 + * decrement rule, which will result in quality codes like "q=0.999", "q=0.998" etc. + * + * @param int $currentWeight varying from 1 to 1000 (will be divided by 1000 to build the quality value) + * @param bool $hasMoreThan28Headers + * @return int + */ + public function getNextWeight(int $currentWeight, bool $hasMoreThan28Headers): int + { + if ($currentWeight <= 1) { + return 1; + } + + if ($hasMoreThan28Headers) { + return $currentWeight - 1; + } + + return $currentWeight - 10 ** floor( log10($currentWeight - 1) ); + } +} diff --git a/samples/client/petstore/php/lib/Model/ApiResponse.php b/samples/client/petstore/php/lib/Model/ApiResponse.php new file mode 100644 index 000000000000..dbd286dd210f --- /dev/null +++ b/samples/client/petstore/php/lib/Model/ApiResponse.php @@ -0,0 +1,478 @@ + + */ +class ApiResponse implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'ApiResponse'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'code' => 'int', + 'type' => 'string', + 'message' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'code' => 'int32', + 'type' => null, + 'message' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'code' => false, + 'type' => false, + 'message' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'code' => 'code', + 'type' => 'type', + 'message' => 'message' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'code' => 'setCode', + 'type' => 'setType', + 'message' => 'setMessage' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'code' => 'getCode', + 'type' => 'getType', + 'message' => 'getMessage' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('code', $data ?? [], null); + $this->setIfExists('type', $data ?? [], null); + $this->setIfExists('message', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets code + * + * @return int|null + */ + public function getCode() + { + return $this->container['code']; + } + + /** + * Sets code + * + * @param int|null $code code + * + * @return self + */ + public function setCode($code) + { + if (is_null($code)) { + throw new \InvalidArgumentException('non-nullable code cannot be null'); + } + $this->container['code'] = $code; + + return $this; + } + + /** + * Gets type + * + * @return string|null + */ + public function getType() + { + return $this->container['type']; + } + + /** + * Sets type + * + * @param string|null $type type + * + * @return self + */ + public function setType($type) + { + if (is_null($type)) { + throw new \InvalidArgumentException('non-nullable type cannot be null'); + } + $this->container['type'] = $type; + + return $this; + } + + /** + * Gets message + * + * @return string|null + */ + public function getMessage() + { + return $this->container['message']; + } + + /** + * Sets message + * + * @param string|null $message message + * + * @return self + */ + public function setMessage($message) + { + if (is_null($message)) { + throw new \InvalidArgumentException('non-nullable message cannot be null'); + } + $this->container['message'] = $message; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/lib/Model/Category.php b/samples/client/petstore/php/lib/Model/Category.php new file mode 100644 index 000000000000..1c5923c900d1 --- /dev/null +++ b/samples/client/petstore/php/lib/Model/Category.php @@ -0,0 +1,444 @@ + + */ +class Category implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Category'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'id' => 'int', + 'name' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'id' => 'int64', + 'name' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'id' => false, + 'name' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'name' => 'name' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'name' => 'setName' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'name' => 'getName' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('id', $data ?? [], null); + $this->setIfExists('name', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets id + * + * @return int|null + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int|null $id id + * + * @return self + */ + public function setId($id) + { + if (is_null($id)) { + throw new \InvalidArgumentException('non-nullable id cannot be null'); + } + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets name + * + * @return string|null + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string|null $name name + * + * @return self + */ + public function setName($name) + { + if (is_null($name)) { + throw new \InvalidArgumentException('non-nullable name cannot be null'); + } + $this->container['name'] = $name; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/lib/Model/ModelInterface.php b/samples/client/petstore/php/lib/Model/ModelInterface.php new file mode 100644 index 000000000000..c5edbba99307 --- /dev/null +++ b/samples/client/petstore/php/lib/Model/ModelInterface.php @@ -0,0 +1,111 @@ + + */ +class Order implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Order'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'id' => 'int', + 'pet_id' => 'int', + 'quantity' => 'int', + 'ship_date' => '\DateTime', + 'status' => 'string', + 'complete' => 'bool' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'id' => 'int64', + 'pet_id' => 'int64', + 'quantity' => 'int32', + 'ship_date' => 'date-time', + 'status' => null, + 'complete' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'id' => false, + 'pet_id' => false, + 'quantity' => false, + 'ship_date' => false, + 'status' => false, + 'complete' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'pet_id' => 'petId', + 'quantity' => 'quantity', + 'ship_date' => 'shipDate', + 'status' => 'status', + 'complete' => 'complete' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'pet_id' => 'setPetId', + 'quantity' => 'setQuantity', + 'ship_date' => 'setShipDate', + 'status' => 'setStatus', + 'complete' => 'setComplete' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'pet_id' => 'getPetId', + 'quantity' => 'getQuantity', + 'ship_date' => 'getShipDate', + 'status' => 'getStatus', + 'complete' => 'getComplete' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + public const STATUS_PLACED = 'placed'; + public const STATUS_APPROVED = 'approved'; + public const STATUS_DELIVERED = 'delivered'; + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getStatusAllowableValues() + { + return [ + self::STATUS_PLACED, + self::STATUS_APPROVED, + self::STATUS_DELIVERED, + ]; + } + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('id', $data ?? [], null); + $this->setIfExists('pet_id', $data ?? [], null); + $this->setIfExists('quantity', $data ?? [], null); + $this->setIfExists('ship_date', $data ?? [], null); + $this->setIfExists('status', $data ?? [], null); + $this->setIfExists('complete', $data ?? [], false); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + $allowedValues = $this->getStatusAllowableValues(); + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value '%s' for 'status', must be one of '%s'", + $this->container['status'], + implode("', '", $allowedValues) + ); + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets id + * + * @return int|null + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int|null $id id + * + * @return self + */ + public function setId($id) + { + if (is_null($id)) { + throw new \InvalidArgumentException('non-nullable id cannot be null'); + } + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets pet_id + * + * @return int|null + */ + public function getPetId() + { + return $this->container['pet_id']; + } + + /** + * Sets pet_id + * + * @param int|null $pet_id pet_id + * + * @return self + */ + public function setPetId($pet_id) + { + if (is_null($pet_id)) { + throw new \InvalidArgumentException('non-nullable pet_id cannot be null'); + } + $this->container['pet_id'] = $pet_id; + + return $this; + } + + /** + * Gets quantity + * + * @return int|null + */ + public function getQuantity() + { + return $this->container['quantity']; + } + + /** + * Sets quantity + * + * @param int|null $quantity quantity + * + * @return self + */ + public function setQuantity($quantity) + { + if (is_null($quantity)) { + throw new \InvalidArgumentException('non-nullable quantity cannot be null'); + } + $this->container['quantity'] = $quantity; + + return $this; + } + + /** + * Gets ship_date + * + * @return \DateTime|null + */ + public function getShipDate() + { + return $this->container['ship_date']; + } + + /** + * Sets ship_date + * + * @param \DateTime|null $ship_date ship_date + * + * @return self + */ + public function setShipDate($ship_date) + { + if (is_null($ship_date)) { + throw new \InvalidArgumentException('non-nullable ship_date cannot be null'); + } + $this->container['ship_date'] = $ship_date; + + return $this; + } + + /** + * Gets status + * + * @return string|null + */ + public function getStatus() + { + return $this->container['status']; + } + + /** + * Sets status + * + * @param string|null $status Order Status + * + * @return self + */ + public function setStatus($status) + { + if (is_null($status)) { + throw new \InvalidArgumentException('non-nullable status cannot be null'); + } + $allowedValues = $this->getStatusAllowableValues(); + if (!in_array($status, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value '%s' for 'status', must be one of '%s'", + $status, + implode("', '", $allowedValues) + ) + ); + } + $this->container['status'] = $status; + + return $this; + } + + /** + * Gets complete + * + * @return bool|null + */ + public function getComplete() + { + return $this->container['complete']; + } + + /** + * Sets complete + * + * @param bool|null $complete complete + * + * @return self + */ + public function setComplete($complete) + { + if (is_null($complete)) { + throw new \InvalidArgumentException('non-nullable complete cannot be null'); + } + $this->container['complete'] = $complete; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/lib/Model/Pet.php b/samples/client/petstore/php/lib/Model/Pet.php new file mode 100644 index 000000000000..71f6376bb07d --- /dev/null +++ b/samples/client/petstore/php/lib/Model/Pet.php @@ -0,0 +1,622 @@ + + */ +class Pet implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Pet'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'id' => 'int', + 'category' => '\OpenAPI\Client\Model\Category', + 'name' => 'string', + 'photo_urls' => 'string[]', + 'tags' => '\OpenAPI\Client\Model\Tag[]', + 'status' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'id' => 'int64', + 'category' => null, + 'name' => null, + 'photo_urls' => null, + 'tags' => null, + 'status' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'id' => false, + 'category' => false, + 'name' => false, + 'photo_urls' => false, + 'tags' => false, + 'status' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'category' => 'category', + 'name' => 'name', + 'photo_urls' => 'photoUrls', + 'tags' => 'tags', + 'status' => 'status' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'category' => 'setCategory', + 'name' => 'setName', + 'photo_urls' => 'setPhotoUrls', + 'tags' => 'setTags', + 'status' => 'setStatus' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'category' => 'getCategory', + 'name' => 'getName', + 'photo_urls' => 'getPhotoUrls', + 'tags' => 'getTags', + 'status' => 'getStatus' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + public const STATUS_AVAILABLE = 'available'; + public const STATUS_PENDING = 'pending'; + public const STATUS_SOLD = 'sold'; + + /** + * Gets allowable values of the enum + * + * @return string[] + */ + public function getStatusAllowableValues() + { + return [ + self::STATUS_AVAILABLE, + self::STATUS_PENDING, + self::STATUS_SOLD, + ]; + } + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('id', $data ?? [], null); + $this->setIfExists('category', $data ?? [], null); + $this->setIfExists('name', $data ?? [], null); + $this->setIfExists('photo_urls', $data ?? [], null); + $this->setIfExists('tags', $data ?? [], null); + $this->setIfExists('status', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + if ($this->container['name'] === null) { + $invalidProperties[] = "'name' can't be null"; + } + if ($this->container['photo_urls'] === null) { + $invalidProperties[] = "'photo_urls' can't be null"; + } + $allowedValues = $this->getStatusAllowableValues(); + if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { + $invalidProperties[] = sprintf( + "invalid value '%s' for 'status', must be one of '%s'", + $this->container['status'], + implode("', '", $allowedValues) + ); + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets id + * + * @return int|null + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int|null $id id + * + * @return self + */ + public function setId($id) + { + if (is_null($id)) { + throw new \InvalidArgumentException('non-nullable id cannot be null'); + } + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets category + * + * @return \OpenAPI\Client\Model\Category|null + */ + public function getCategory() + { + return $this->container['category']; + } + + /** + * Sets category + * + * @param \OpenAPI\Client\Model\Category|null $category category + * + * @return self + */ + public function setCategory($category) + { + if (is_null($category)) { + throw new \InvalidArgumentException('non-nullable category cannot be null'); + } + $this->container['category'] = $category; + + return $this; + } + + /** + * Gets name + * + * @return string + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string $name name + * + * @return self + */ + public function setName($name) + { + if (is_null($name)) { + throw new \InvalidArgumentException('non-nullable name cannot be null'); + } + $this->container['name'] = $name; + + return $this; + } + + /** + * Gets photo_urls + * + * @return string[] + */ + public function getPhotoUrls() + { + return $this->container['photo_urls']; + } + + /** + * Sets photo_urls + * + * @param string[] $photo_urls photo_urls + * + * @return self + */ + public function setPhotoUrls($photo_urls) + { + if (is_null($photo_urls)) { + throw new \InvalidArgumentException('non-nullable photo_urls cannot be null'); + } + $this->container['photo_urls'] = $photo_urls; + + return $this; + } + + /** + * Gets tags + * + * @return \OpenAPI\Client\Model\Tag[]|null + */ + public function getTags() + { + return $this->container['tags']; + } + + /** + * Sets tags + * + * @param \OpenAPI\Client\Model\Tag[]|null $tags tags + * + * @return self + */ + public function setTags($tags) + { + if (is_null($tags)) { + throw new \InvalidArgumentException('non-nullable tags cannot be null'); + } + $this->container['tags'] = $tags; + + return $this; + } + + /** + * Gets status + * + * @return string|null + */ + public function getStatus() + { + return $this->container['status']; + } + + /** + * Sets status + * + * @param string|null $status pet status in the store + * + * @return self + */ + public function setStatus($status) + { + if (is_null($status)) { + throw new \InvalidArgumentException('non-nullable status cannot be null'); + } + $allowedValues = $this->getStatusAllowableValues(); + if (!in_array($status, $allowedValues, true)) { + throw new \InvalidArgumentException( + sprintf( + "Invalid value '%s' for 'status', must be one of '%s'", + $status, + implode("', '", $allowedValues) + ) + ); + } + $this->container['status'] = $status; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/lib/Model/Tag.php b/samples/client/petstore/php/lib/Model/Tag.php new file mode 100644 index 000000000000..36550a62a986 --- /dev/null +++ b/samples/client/petstore/php/lib/Model/Tag.php @@ -0,0 +1,444 @@ + + */ +class Tag implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Tag'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'id' => 'int', + 'name' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'id' => 'int64', + 'name' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'id' => false, + 'name' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'name' => 'name' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'name' => 'setName' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'name' => 'getName' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('id', $data ?? [], null); + $this->setIfExists('name', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets id + * + * @return int|null + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int|null $id id + * + * @return self + */ + public function setId($id) + { + if (is_null($id)) { + throw new \InvalidArgumentException('non-nullable id cannot be null'); + } + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets name + * + * @return string|null + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string|null $name name + * + * @return self + */ + public function setName($name) + { + if (is_null($name)) { + throw new \InvalidArgumentException('non-nullable name cannot be null'); + } + $this->container['name'] = $name; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/lib/Model/User.php b/samples/client/petstore/php/lib/Model/User.php new file mode 100644 index 000000000000..f872fa6a3b06 --- /dev/null +++ b/samples/client/petstore/php/lib/Model/User.php @@ -0,0 +1,648 @@ + + */ +class User implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'User'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'id' => 'int', + 'username' => 'string', + 'first_name' => 'string', + 'last_name' => 'string', + 'email' => 'string', + 'password' => 'string', + 'phone' => 'string', + 'user_status' => 'int' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'id' => 'int64', + 'username' => null, + 'first_name' => null, + 'last_name' => null, + 'email' => null, + 'password' => null, + 'phone' => null, + 'user_status' => 'int32' + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'id' => false, + 'username' => false, + 'first_name' => false, + 'last_name' => false, + 'email' => false, + 'password' => false, + 'phone' => false, + 'user_status' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id', + 'username' => 'username', + 'first_name' => 'firstName', + 'last_name' => 'lastName', + 'email' => 'email', + 'password' => 'password', + 'phone' => 'phone', + 'user_status' => 'userStatus' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId', + 'username' => 'setUsername', + 'first_name' => 'setFirstName', + 'last_name' => 'setLastName', + 'email' => 'setEmail', + 'password' => 'setPassword', + 'phone' => 'setPhone', + 'user_status' => 'setUserStatus' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId', + 'username' => 'getUsername', + 'first_name' => 'getFirstName', + 'last_name' => 'getLastName', + 'email' => 'getEmail', + 'password' => 'getPassword', + 'phone' => 'getPhone', + 'user_status' => 'getUserStatus' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('id', $data ?? [], null); + $this->setIfExists('username', $data ?? [], null); + $this->setIfExists('first_name', $data ?? [], null); + $this->setIfExists('last_name', $data ?? [], null); + $this->setIfExists('email', $data ?? [], null); + $this->setIfExists('password', $data ?? [], null); + $this->setIfExists('phone', $data ?? [], null); + $this->setIfExists('user_status', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets id + * + * @return int|null + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param int|null $id id + * + * @return self + */ + public function setId($id) + { + if (is_null($id)) { + throw new \InvalidArgumentException('non-nullable id cannot be null'); + } + $this->container['id'] = $id; + + return $this; + } + + /** + * Gets username + * + * @return string|null + */ + public function getUsername() + { + return $this->container['username']; + } + + /** + * Sets username + * + * @param string|null $username username + * + * @return self + */ + public function setUsername($username) + { + if (is_null($username)) { + throw new \InvalidArgumentException('non-nullable username cannot be null'); + } + $this->container['username'] = $username; + + return $this; + } + + /** + * Gets first_name + * + * @return string|null + */ + public function getFirstName() + { + return $this->container['first_name']; + } + + /** + * Sets first_name + * + * @param string|null $first_name first_name + * + * @return self + */ + public function setFirstName($first_name) + { + if (is_null($first_name)) { + throw new \InvalidArgumentException('non-nullable first_name cannot be null'); + } + $this->container['first_name'] = $first_name; + + return $this; + } + + /** + * Gets last_name + * + * @return string|null + */ + public function getLastName() + { + return $this->container['last_name']; + } + + /** + * Sets last_name + * + * @param string|null $last_name last_name + * + * @return self + */ + public function setLastName($last_name) + { + if (is_null($last_name)) { + throw new \InvalidArgumentException('non-nullable last_name cannot be null'); + } + $this->container['last_name'] = $last_name; + + return $this; + } + + /** + * Gets email + * + * @return string|null + */ + public function getEmail() + { + return $this->container['email']; + } + + /** + * Sets email + * + * @param string|null $email email + * + * @return self + */ + public function setEmail($email) + { + if (is_null($email)) { + throw new \InvalidArgumentException('non-nullable email cannot be null'); + } + $this->container['email'] = $email; + + return $this; + } + + /** + * Gets password + * + * @return string|null + */ + public function getPassword() + { + return $this->container['password']; + } + + /** + * Sets password + * + * @param string|null $password password + * + * @return self + */ + public function setPassword($password) + { + if (is_null($password)) { + throw new \InvalidArgumentException('non-nullable password cannot be null'); + } + $this->container['password'] = $password; + + return $this; + } + + /** + * Gets phone + * + * @return string|null + */ + public function getPhone() + { + return $this->container['phone']; + } + + /** + * Sets phone + * + * @param string|null $phone phone + * + * @return self + */ + public function setPhone($phone) + { + if (is_null($phone)) { + throw new \InvalidArgumentException('non-nullable phone cannot be null'); + } + $this->container['phone'] = $phone; + + return $this; + } + + /** + * Gets user_status + * + * @return int|null + */ + public function getUserStatus() + { + return $this->container['user_status']; + } + + /** + * Sets user_status + * + * @param int|null $user_status User Status + * + * @return self + */ + public function setUserStatus($user_status) + { + if (is_null($user_status)) { + throw new \InvalidArgumentException('non-nullable user_status cannot be null'); + } + $this->container['user_status'] = $user_status; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/lib/ObjectSerializer.php b/samples/client/petstore/php/lib/ObjectSerializer.php new file mode 100644 index 000000000000..eb0205f4c8a4 --- /dev/null +++ b/samples/client/petstore/php/lib/ObjectSerializer.php @@ -0,0 +1,599 @@ +format('Y-m-d') : $data->format(self::$dateTimeFormat); + } + + if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = self::sanitizeForSerialization($value); + } + return $data; + } + + if (is_object($data)) { + $values = []; + if ($data instanceof ModelInterface) { + $formats = $data::openAPIFormats(); + foreach ($data::openAPITypes() as $property => $openAPIType) { + $getter = $data::getters()[$property]; + $value = $data->$getter(); + if ($value !== null && !in_array($openAPIType, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + $callable = [$openAPIType, 'getAllowableEnumValues']; + if (is_callable($callable)) { + /** array $callable */ + $allowedEnumTypes = $callable(); + if (!in_array($value, $allowedEnumTypes, true)) { + $imploded = implode("', '", $allowedEnumTypes); + throw new \InvalidArgumentException("Invalid value for enum '$openAPIType', must be one of: '$imploded'"); + } + } + } + if (($data::isNullable($property) && $data->isNullableSetToNull($property)) || $value !== null) { + $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $openAPIType, $formats[$property]); + } + } + } else { + foreach($data as $property => $value) { + $values[$property] = self::sanitizeForSerialization($value); + } + } + return (object)$values; + } else { + return (string)$data; + } + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param string $filename filename to be sanitized + * + * @return string the sanitized filename + */ + public static function sanitizeFilename($filename) + { + if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { + return $match[1]; + } else { + return $filename; + } + } + + /** + * Shorter timestamp microseconds to 6 digits length. + * + * @param string $timestamp Original timestamp + * + * @return string the shorten timestamp + */ + public static function sanitizeTimestamp($timestamp) + { + if (!is_string($timestamp)) return $timestamp; + + return preg_replace('/(:\d{2}.\d{6})\d*/', '$1', $timestamp); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * + * @param string $value a string which will be part of the path + * + * @return string the serialized object + */ + public static function toPathValue($value) + { + return rawurlencode(self::toString($value)); + } + + /** + * Checks if a value is empty, based on its OpenAPI type. + * + * @param mixed $value + * @param string $openApiType + * + * @return bool true if $value is empty + */ + private static function isEmptyValue($value, string $openApiType): bool + { + # If empty() returns false, it is not empty regardless of its type. + if (!empty($value)) { + return false; + } + + # Null is always empty, as we cannot send a real "null" value in a query parameter. + if ($value === null) { + return true; + } + + switch ($openApiType) { + # For numeric values, false and '' are considered empty. + # This comparison is safe for floating point values, since the previous call to empty() will + # filter out values that don't match 0. + case 'int': + case 'integer': + return $value !== 0; + + case 'number': + case 'float': + return $value !== 0 && $value !== 0.0; + + # For boolean values, '' is considered empty + case 'bool': + case 'boolean': + return !in_array($value, [false, 0], true); + + # For string values, '' is considered empty. + case 'string': + return $value === ''; + + # For all the other types, any value at this point can be considered empty. + default: + return true; + } + } + + /** + * Take query parameter properties and turn it into an array suitable for + * native http_build_query or GuzzleHttp\Psr7\Query::build. + * + * @param mixed $value Parameter value + * @param string $paramName Parameter name + * @param string $openApiType OpenAPIType eg. array or object + * @param string $style Parameter serialization style + * @param bool $explode Parameter explode option + * @param bool $required Whether query param is required or not + * + * @return array + */ + public static function toQueryValue( + $value, + string $paramName, + string $openApiType = 'string', + string $style = 'form', + bool $explode = true, + bool $required = true + ): array { + + # Check if we should omit this parameter from the query. This should only happen when: + # - Parameter is NOT required; AND + # - its value is set to a value that is equivalent to "empty", depending on its OpenAPI type. For + # example, 0 as "int" or "boolean" is NOT an empty value. + if (self::isEmptyValue($value, $openApiType)) { + if ($required) { + return ["{$paramName}" => '']; + } else { + return []; + } + } + + # Handle DateTime objects in query + if($openApiType === "\\DateTime" && $value instanceof \DateTime) { + return ["{$paramName}" => $value->format(self::$dateTimeFormat)]; + } + + $query = []; + $value = (in_array($openApiType, ['object', 'array'], true)) ? (array)$value : $value; + + // since \GuzzleHttp\Psr7\Query::build fails with nested arrays + // need to flatten array first + $flattenArray = function ($arr, $name, &$result = []) use (&$flattenArray, $style, $explode) { + if (!is_array($arr)) return $arr; + + foreach ($arr as $k => $v) { + $prop = ($style === 'deepObject') ? $prop = "{$name}[{$k}]" : $k; + + if (is_array($v)) { + $flattenArray($v, $prop, $result); + } else { + if ($style !== 'deepObject' && !$explode) { + // push key itself + $result[] = $prop; + } + $result[$prop] = $v; + } + } + return $result; + }; + + $value = $flattenArray($value, $paramName); + + // https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values + if ($openApiType === 'array' && $style === 'deepObject' && $explode) { + return $value; + } + + if ($openApiType === 'object' && ($style === 'deepObject' || $explode)) { + return $value; + } + + if ('boolean' === $openApiType && is_bool($value)) { + $value = self::convertBoolToQueryStringFormat($value); + } + + // handle style in serializeCollection + $query[$paramName] = ($explode) ? $value : self::serializeCollection((array)$value, $style); + + return $query; + } + + /** + * Convert boolean value to format for query string. + * + * @param bool $value Boolean value + * + * @return int|string Boolean value in format + */ + public static function convertBoolToQueryStringFormat(bool $value) + { + if (Configuration::BOOLEAN_FORMAT_STRING == Configuration::getDefaultConfiguration()->getBooleanFormatForQueryString()) { + return $value ? 'true' : 'false'; + } + + return (int) $value; + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string $value a string which will be part of the header + * + * @return string the header string + */ + public static function toHeaderValue($value) + { + $callable = [$value, 'toHeaderValue']; + if (is_callable($callable)) { + return $callable(); + } + + return self::toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * If it's a boolean, convert it to "true" or "false". + * + * @param float|int|bool|\DateTime $value the value of the parameter + * + * @return string the header string + */ + public static function toString($value) + { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(self::$dateTimeFormat); + } elseif (is_bool($value)) { + return $value ? 'true' : 'false'; + } else { + return (string) $value; + } + } + + /** + * Serialize an array to a string. + * + * @param array $collection collection to serialize to a string + * @param string $style the format use for serialization (csv, + * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array + * + * @return string + */ + public static function serializeCollection(array $collection, $style, $allowCollectionFormatMulti = false) + { + if ($allowCollectionFormatMulti && ('multi' === $style)) { + // http_build_query() almost does the job for us. We just + // need to fix the result of multidimensional arrays. + return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&')); + } + switch ($style) { + case 'pipeDelimited': + case 'pipes': + return implode('|', $collection); + + case 'tsv': + return implode("\t", $collection); + + case 'spaceDelimited': + case 'ssv': + return implode(' ', $collection); + + case 'simple': + case 'csv': + // Deliberate fall through. CSV is default format. + default: + return implode(',', $collection); + } + } + + /** + * Deserialize a JSON string into an object + * + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[]|null $httpHeaders HTTP headers + * + * @return object|array|null a single or an array of $class instances + */ + public static function deserialize($data, $class, $httpHeaders = null) + { + if (null === $data) { + return null; + } + + if (strcasecmp(substr($class, -2), '[]') === 0) { + $data = is_string($data) ? json_decode($data) : $data; + + if (!is_array($data)) { + throw new \InvalidArgumentException("Invalid array '$class'"); + } + + $subClass = substr($class, 0, -2); + $values = []; + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass, null); + } + return $values; + } + + if (preg_match('/^(array<|map\[)/', $class)) { // for associative array e.g. array + $data = is_string($data) ? json_decode($data) : $data; + settype($data, 'array'); + $inner = substr($class, 4, -1); + $deserialized = []; + if (strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = self::deserialize($value, $subClass, null); + } + } + return $deserialized; + } + + if ($class === 'object') { + settype($data, 'array'); + return $data; + } elseif ($class === 'mixed') { + settype($data, gettype($data)); + return $data; + } + + if ($class === '\DateTime') { + // Some APIs return an invalid, empty string as a + // date-time property. DateTime::__construct() will return + // the current time for empty input which is probably not + // what is meant. The invalid empty string is probably to + // be interpreted as a missing field/value. Let's handle + // this graceful. + if (!empty($data)) { + try { + return new \DateTime($data); + } catch (\Exception $exception) { + // Some APIs return a date-time with too high nanosecond + // precision for php's DateTime to handle. + // With provided regexp 6 digits of microseconds saved + return new \DateTime(self::sanitizeTimestamp($data)); + } + } else { + return null; + } + } + + if ($class === '\SplFileObject') { + $data = Utils::streamFor($data); + + /** @var \Psr\Http\Message\StreamInterface $data */ + + // determine file name + if ( + is_array($httpHeaders) + && array_key_exists('Content-Disposition', $httpHeaders) + && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match) + ) { + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]); + } else { + $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); + } + + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); + } + fclose($file); + + return new \SplFileObject($filename, 'r'); + } + + /** @psalm-suppress ParadoxicalCondition */ + if (in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + settype($data, $class); + return $data; + } + + + if (method_exists($class, 'getAllowableEnumValues')) { + if (!in_array($data, $class::getAllowableEnumValues(), true)) { + $imploded = implode("', '", $class::getAllowableEnumValues()); + throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'"); + } + return $data; + } else { + $data = is_string($data) ? json_decode($data) : $data; + + if (is_array($data)) { + $data = (object)$data; + } + + // If a discriminator is defined and points to a valid subclass, use it. + $discriminator = $class::DISCRIMINATOR; + if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { + $subclass = '\OpenAPI\Client\Model\\' . $data->{$discriminator}; + if (is_subclass_of($subclass, $class)) { + $class = $subclass; + } + } + + /** @var ModelInterface $instance */ + $instance = new $class(); + foreach ($instance::openAPITypes() as $property => $type) { + $propertySetter = $instance::setters()[$property]; + + if (!isset($propertySetter)) { + continue; + } + + if (!isset($data->{$instance::attributeMap()[$property]})) { + if ($instance::isNullable($property)) { + $instance->$propertySetter(null); + } + + continue; + } + + if (isset($data->{$instance::attributeMap()[$property]})) { + $propertyValue = $data->{$instance::attributeMap()[$property]}; + $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); + } + } + return $instance; + } + } + + /** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of `parse()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like `http_build_query()` would). + * + * The function is copied from https://github.com/guzzle/psr7/blob/a243f80a1ca7fe8ceed4deee17f12c1930efe662/src/Query.php#L59-L112 + * with a modification which is described in https://github.com/guzzle/psr7/pull/603 + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + */ + public static function buildQuery(array $params, $encoding = PHP_QUERY_RFC3986): string + { + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function (string $str): string { + return $str; + }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $castBool = Configuration::BOOLEAN_FORMAT_INT == Configuration::getDefaultConfiguration()->getBooleanFormatForQueryString() + ? function ($v) { return (int) $v; } + : function ($v) { return $v ? 'true' : 'false'; }; + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder((string) $k); + if (!is_array($v)) { + $qs .= $k; + $v = is_bool($v) ? $castBool($v) : $v; + if ($v !== null) { + $qs .= '='.$encoder((string) $v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + $vv = is_bool($vv) ? $castBool($vv) : $vv; + if ($vv !== null) { + $qs .= '='.$encoder((string) $vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; + } +} diff --git a/samples/client/petstore/php/phpunit.xml.dist b/samples/client/petstore/php/phpunit.xml.dist new file mode 100644 index 000000000000..485899aaf215 --- /dev/null +++ b/samples/client/petstore/php/phpunit.xml.dist @@ -0,0 +1,18 @@ + + + + + ./lib/Api + ./lib/Model + + + + + ./test/Api + ./test/Model + + + + + + diff --git a/samples/client/petstore/php/test/Api/PetApiTest.php b/samples/client/petstore/php/test/Api/PetApiTest.php new file mode 100644 index 000000000000..cdecd3050814 --- /dev/null +++ b/samples/client/petstore/php/test/Api/PetApiTest.php @@ -0,0 +1,169 @@ +