diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..bd44d64 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,36 @@ +name: PHPUnit + +on: [push] + +jobs: + phpunit: + runs-on: ubuntu-latest + + strategy: + matrix: + php_version: + - "7.3" + - "7.4" + - "8.0" + - "8.1" + - "8.2" + + steps: + - uses: actions/checkout@v3 + - uses: php-actions/composer@v6 + with: + php_version: "${{ matrix.php_version }}" + - uses: php-actions/phpunit@v3 + with: + configuration: "phpunit.xml" + php_version: "${{ matrix.php_version }}" + version: "9" + + pre-commit: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: php-actions/composer@v6 + - uses: actions/setup-python@v3 + - uses: pre-commit/action@v3.0.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cf7a885 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +composer.phar +/vendor/ +/coverage/ +/.phpunit.result.cache +/.phpunit.cache/ +/.php-cs-fixer.cache + +# Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file +# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file +composer.lock diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 0000000..7b0828d --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,8 @@ +setRules([ + 'braces' => false, +]); + +return $config; diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..83cc74e --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,31 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: check-added-large-files + - id: check-case-conflict + - id: check-executables-have-shebangs + - id: check-json + - id: check-merge-conflict + - id: check-shebang-scripts-are-executable + - id: check-symlinks + - id: check-toml + - id: check-xml + - id: check-yaml + - id: destroyed-symlinks + - id: detect-private-key + - id: end-of-file-fixer + - id: fix-byte-order-marker + - id: mixed-line-ending + - id: trailing-whitespace + + - repo: https://github.com/Greenreader9Hosting/pre-commit-php + rev: 1.3.1 + hooks: + - id: php-lint +# - id: php-cs +# - id: php-cbf + - id: php-cs-fixer + args: + - --config=.php-cs-fixer.php +# - id: pint diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..053e212 --- /dev/null +++ b/README.md @@ -0,0 +1,85 @@ +# MyOwnFreeHost API Client + +An API client to use the free hosting system from [MyOwnFreeHost](https://myownfreehost.net). + +**IMPORTANT: THIS LIBRARY IS AIMED AT EXPERIENCED PHP DEVELOPERS. Experience with object-oriented PHP and Composer is required. If you can't use oo-PHP and Composer, don't bother with this library.** + +## Installation + +This package is best installed through Composer: + +```bash +composer require Greenreader9/mofh-client +``` + +## Usage + +Before you can get started, you need to get the API credentials from MyOwnFreeHost. Login to the [reseller panel](https://panel.myownfreehost.net), go to API -> Setup WHM API -> select the domain you want to configure. Copy the API Username and API password and set your own IP address as the Allowed IP Address (the IP address of your computer, server, or wherever you want to use this API client). + +### Available Methods + +The MyOwnFreeHost API exposes the following methods. The available parameters are listed below. + +- createAccount: Create a new hosting account. + - username: A unique, 8 character identifier of the account. + - password: A password to login to the control panel, FTP and databases. + - domain: A domain name to create the account. Can be a subdomain or a custom domain. + - email: The email address of the user. + - plan: The name of the hosting plan to create the account on. Requires a hosting package to be configured through MyOwnFreeHost. +- suspend: Suspend a hosting account. + - username: The unique, 8 character identifier of the account. + - reason: A string with information about why you are suspending the account. + - linked: If true, related accounts will be suspended as well. +- unsuspend: Reactivate a hosting account. + - username: The unique, 8 character identifier of the account. +- password: Change the password of a hosting account. + - username: The unique, 8 character identifier of the account. + - password: The new password to set for the account. +- availability: Check if a given domain name is available to be added to an account. + - domain: The domain name or subdomain to check. +- getUserDomains: Get the domain names linked to a given account. + - username: The vistaPanel login username (e.g. abcd_12345678). +- getDomainUser: Get the information of a particular hosting domain name, including the account it's hosted on and the document root. + - domain: The domain name to search for. + +### Example + +```php +use \Greenreader9\MofhClient\Client; + +// Create a new API client with your API credentials. +$client = new Client("", ""); + +// Create a new hosting account. +$createResponse = $client->createAccount( + 'abcd1234', // A unique, 8 character identifier of the account. Primarily used as internal identifier. + 'password123', // A password to login to the control panel, FTP and databases. + 'user@example.com', // The email address of the user. + 'userdomain.example.com', // Initial domain of the account. Can be a subdomain or a custom domain. + 'my_plan', // The hosting plan name at MyOwnFreeHost. +); + +// Check whether the request was successful. +if ($createResponse->isSuccessful()) { + echo "Created account with username: ".$createResponse->getVpUsername(); +} else { + echo 'Failed to create account: ' . $response->getMessage(); + die(); +} +``` + +## License + +Copyright 2023 Greenreader9 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..e6b432d --- /dev/null +++ b/composer.json @@ -0,0 +1,30 @@ +{ + "name": "greenreader9/mofh-client", + "description": "A WHM API client for MyOwnFreeHost in PHP", + "minimum-stability": "stable", + "license": "Apache-2.0", + "authors": [ + { + "name": "GREENREADER9", + "email": "hello@tinkertechlab.com" + } + ], + "require": { + "php": ">=7.1", + "ext-json": "*", + "ext-simplexml": "*", + "guzzlehttp/guzzle": "~6.0|~7.0" + }, + "require-dev": { + "fakerphp/faker": "^1.7", + "friendsofphp/php-cs-fixer": "^3.4", + "mockery/mockery": "^1.3", + "phpunit/phpunit": "^7.0|^8.0|^9.0" + }, + "autoload": { + "psr-4": { + "Greenreader9\\MofhClient\\": "src/", + "Greenreader9\\MofhClient\\Tests\\": "tests/" + } + } +} diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..f59247c --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,16 @@ + + + + + ./src + + + + + ./tests/ + + + diff --git a/src/Client.php b/src/Client.php new file mode 100644 index 0000000..73a9a07 --- /dev/null +++ b/src/Client.php @@ -0,0 +1,238 @@ +apiUsername = $apiUsername; + $this->apiPassword = $apiPassword; + $this->apiUrl = $apiUrl; + + $this->httpClient = $httpClient ?: new Guzzle([ + 'connect_timeout' => 5.0, + ]); + } + + /** + * Send a POST query to the XML API. + * + * @param string $function The MOFH API function name + * @param array $parameters The API function arguments + * + * @throws MofhClientHttpException + */ + protected function sendPostRequest(string $function, array $parameters): ResponseInterface + { + return $this->sendRawRequest('POST', $function, [ + 'form_params' => $parameters, + 'auth' => [$this->apiUsername, $this->apiPassword], + 'timeout' => 60.0, + ]); + } + + /** + * Send a GET query to the XML API. + * + * @param string $function The MOFH API function name + * @param array $parameters The API function arguments + * + * @throws MofhClientHttpException + */ + protected function sendGetRequest(string $function, array $parameters): ResponseInterface + { + return $this->sendRawRequest('GET', $function, [ + 'query' => array_replace([ + 'api_user' => $this->apiUsername, + 'api_key' => $this->apiPassword, + ], $parameters), + 'timeout' => 5.0, + ]); + } + + /** + * Send the actual HTTP request to the API. + * + * @throws MofhClientHttpException + */ + private function sendRawRequest(string $method, string $function, array $requestOptions = []): ResponseInterface + { + try { + return $this->httpClient->request($method, $this->apiUrl.$function, $requestOptions); + } catch (GuzzleException $e) { + throw new MofhClientHttpException('The MOFH API returned a HTTP error: '.$e->getMessage(), 0, $e); + } + } + + /** + * Create a new hosting account. + * + * @param string $username A custom username, max. 8 characters of letters and numbers. + * @param string $password A password used to access the control panel, FTP and database. + * @param string $email The contact email address of the account owner. + * @param string $domain The primary domain name of the account. + * @param string $plan The name of the plan to use at MyOwnFreeHost. Create this in MOFH -> Quotas & Packages -> Set Packages. + * @param string ipaddy + * + * @throws MofhClientHttpException + */ + public function createAccount(string $username, string $password, string $email, string $domain, string $plan, string $ipaddy): CreateAccountResponse + { + $response = $this->sendPostRequest('createacct', [ + 'username' => $username, + 'password' => $password, + 'contactemail' => $email, + 'domain' => $domain, + 'plan' => $plan, + 'ipaddy' => $ipaddy, + ]); + + return new CreateAccountResponse($response); + } + + /** + * Suspend an account on MyOwnFreeHost. + * + * @param string $username The custom username of the account. This is the 8 character username used in createAccount, not the FTP username. + * @param string $reason The reason why the account is suspended. Will be prefixed with RES_CLOSE by the system. + * @param bool $linked If set to true, related accounts (from the same email or IP address) will be suspended as well. + * + * @throws MofhClientHttpException + */ + public function suspend(string $username, string $reason, bool $linked = false): SuspendResponse + { + $response = $this->sendPostRequest('suspendacct', [ + 'user' => $username, + 'reason' => $reason, + 'linked' => $linked ? '1' : '0', + ]); + + return new SuspendResponse($response); + } + + /** + * Unsuspend the account with the given username at MyOwnFreeHost. + * + * @param string $username The custom username of the account. This is the 8 character username used in createAccount, not the FTP username. + * + * @throws MofhClientHttpException + */ + public function unsuspend(string $username): UnsuspendResponse + { + $response = $this->sendPostRequest('unsuspendacct', [ + 'user' => $username, + ]); + + return new UnsuspendResponse($response); + } + + /** + * Change the password of an (active) account. + * + * @param string $username The custom username of the account. This is the 8 character username used in createAccount, not the FTP username. + * @param string $password The new password used to access the control panel, FTP and database. + * + * @throws MofhClientHttpException + */ + public function password(string $username, string $password): PasswordResponse + { + $response = $this->sendPostRequest('passwd', [ + 'user' => $username, + 'pass' => $password, + ]); + + return new PasswordResponse($response); + } + + /** + * Check whether a domain is available to use at MyOwnFreeHost. + * + * This checks if the domain is in use on another account or not. It doesn't check + * + * @param string $domain The domain name or subdomain to check. + * + * @throws MofhClientHttpException + */ + public function availability(string $domain): AvailabilityResponse + { + $response = $this->sendGetRequest('checkavailable', [ + 'domain' => $domain, + ]); + + return new AvailabilityResponse($response); + } + + /** + * Get the domains belonging to an account. + * + * @param string $username The generated username for the account (e.g. test_12345678). + * + * @throws MofhClientHttpException + */ + public function getUserDomains(string $username): GetUserDomainsResponse + { + $response = $this->sendGetRequest('getuserdomains', [ + 'username' => $username, + ]); + + return new GetUserDomainsResponse($response); + } + + /** + * Get the account details corresponding to a domain name. + * + * @param string $domain The domain name to search for. + * + * @throws MofhClientHttpException + */ + public function getDomainUser(string $domain): GetDomainUserResponse + { + $response = $this->sendGetRequest('getdomainuser', [ + 'domain' => $domain, + ]); + + return new GetDomainUserResponse($response); + } +} diff --git a/src/Exception/MismatchedStatusesException.php b/src/Exception/MismatchedStatusesException.php new file mode 100644 index 0000000..15eafa7 --- /dev/null +++ b/src/Exception/MismatchedStatusesException.php @@ -0,0 +1,7 @@ +response = $response; + + $this->parseResponse(); + } + + /** + * Parse the response after it has been received. + */ + protected function parseResponse() + { + $data = (string) $this->response->getBody(); + + $xmlData = @simplexml_load_string($data, \SimpleXMLElement::class, LIBXML_NOERROR); + + if ($xmlData !== false) { + $this->data = $this->xmlToArray((array) $xmlData); + } else { + $this->data = $data; + } + } + + /** + * Get the response data. + * + * @return mixed + */ + public function getData() + { + return $this->data; + } + + /** + * Recursively convert a SimpleXMLElement array to regular arrays + */ + protected function xmlToArray(array $input): array + { + foreach ($input as $key => $value) { + if ($value instanceof \SimpleXMLElement) { + $value = (array) $value; + } + + if (is_array($value)) { + $input[$key] = $this->xmlToArray($value); + } + } + + return $input; + } + + /** + * Get the error message from the response if the call failed. + */ + public function getMessage(): ?string + { + if ($this->isSuccessful()) { + return null; + } elseif ($this->getData() && isset($this->getData()['result']['statusmsg'])) { + return trim($this->getData()['result']['statusmsg']); + } else { + return trim($this->response->getBody()); + } + } + + /** + * Whether the action was successful + */ + public function isSuccessful(): bool + { + if ($this->getData() && isset($this->getData()['result']['status'])) { + return $this->getData()['result']['status'] == 1; + } else { + return false; + } + } +} diff --git a/src/Message/AvailabilityResponse.php b/src/Message/AvailabilityResponse.php new file mode 100644 index 0000000..c0f69f8 --- /dev/null +++ b/src/Message/AvailabilityResponse.php @@ -0,0 +1,27 @@ +isSuccessful() ? null : $this->getData(); + } + + /** + * Whether the request was successful. + */ + public function isSuccessful(): bool + { + return in_array($this->data, ['0', '1']); + } + + /** + * Whether the selected domain name is available or not. + */ + public function isAvailable(): bool + { + return $this->data === '1'; + } +} diff --git a/src/Message/CreateAccountResponse.php b/src/Message/CreateAccountResponse.php new file mode 100644 index 0000000..9130b40 --- /dev/null +++ b/src/Message/CreateAccountResponse.php @@ -0,0 +1,14 @@ +getData()['result']['options']['vpusername'] ?? null; + } +} diff --git a/src/Message/GetDomainUserResponse.php b/src/Message/GetDomainUserResponse.php new file mode 100644 index 0000000..15b90fe --- /dev/null +++ b/src/Message/GetDomainUserResponse.php @@ -0,0 +1,92 @@ +response->getBody(); + + if (strpos($responseBody, '[') === 0) { + $this->data = json_decode($responseBody, true); + + if ($this->data && count($this->data) == 4) { + [$this->status, $this->domain, $this->documentRoot, $this->username] = $this->data; + } + } elseif ($responseBody === 'null') { + $this->data = []; + } else { + $this->data = trim($responseBody); + } + } + + /** + * Get the error message, if defined. + */ + public function getMessage(): ?string + { + return $this->isSuccessful() ? null : $this->getData(); + } + + /** + * Check if the request was successful. + */ + public function isSuccessful(): bool + { + return is_array($this->data); + } + + /** + * Check if the domain was found. + */ + public function isFound(): bool + { + return is_array($this->data) && $this->data !== []; + } + + /** + * Get the domain name which was searched for. + */ + public function getDomain(): ?string + { + return $this->domain; + } + + /** + * Get the status of the account (ACTIVE or SUSPENDED). + */ + public function getStatus(): ?string + { + return $this->status; + } + + /** + * Get the full document root of the domain name. + * + * For example: + * /home/volXX_X/epizy.com/host_12345678/example.com/htdocs + */ + public function getDocumentRoot(): ?string + { + return $this->documentRoot; + } + + /** + * Get the username of the account to which this domain name belongs. + * + * For example: host_12345678 + */ + public function getUsername(): ?string + { + return $this->username; + } +} diff --git a/src/Message/GetUserDomainsResponse.php b/src/Message/GetUserDomainsResponse.php new file mode 100644 index 0000000..6d2b209 --- /dev/null +++ b/src/Message/GetUserDomainsResponse.php @@ -0,0 +1,73 @@ +response->getBody(); + + if (strpos($responseBody, '[') === 0) { + $this->data = json_decode($responseBody, true); + } elseif ($responseBody === 'null') { + $this->data = []; + } else { + $this->data = trim($responseBody); + } + } + + /** + * Get the error message, if defined. + * + * @return array|null|string + */ + public function getMessage(): ?string + { + return $this->isSuccessful() ? null : $this->getData(); + } + + /** + * Check if the request was successful. + */ + public function isSuccessful(): bool + { + return is_array($this->data); + } + + /** + * Get the list of domains on the account. + */ + public function getDomains(): array + { + return array_map(function ($item) { + return $item[1]; + }, is_array($this->data) ? $this->data : []); + } + + /** + * Get the status of the account, either ACTIVE or SUSPENDED. + * + * @throws MismatchedStatusesException + */ + public function getStatus(): ?string + { + if (is_array($this->data)) { + $statuses = array_unique(array_map(function ($item) { + return $item[0]; + }, $this->data)); + + if (count($statuses) == 1) { + return $statuses[0]; + } elseif (count($statuses) > 1) { + throw new MismatchedStatusesException('The account domains have different statuses: '.implode($statuses)); + } else { + return null; + } + } else { + return null; + } + } +} diff --git a/src/Message/PasswordResponse.php b/src/Message/PasswordResponse.php new file mode 100644 index 0000000..bd2bbfa --- /dev/null +++ b/src/Message/PasswordResponse.php @@ -0,0 +1,61 @@ +getData()['passwd']['status'])) { + if ($this->getData()['passwd']['status'] == '1') { + $this->status = 'a'; + } elseif (strpos($this->getData()['passwd']['statusmsg'], 'error occured changing this password') !== false) { + // This error means the password is identical. We consider this to be successful (making this call idempotent). + $this->status = 'a'; + } else { + $this->message = trim($this->getData()['passwd']['statusmsg']); + if (preg_match('/the account must be active to change the password\s+\((.+)\)/', $this->message, $matches)) { + $this->status = $matches[1]; + } + } + } else { + $this->message = trim($this->response->getBody()); + } + } + + /** + * Get the error message of the response, if it failed. + */ + public function getMessage(): ?string + { + return $this->message; + } + + /** + * Whether the action was successful + */ + public function isSuccessful(): bool + { + return $this->status == 'a'; + } + + /** + * Get the status of the account if the account is not active. + * + * The result is one of the following chars: + * - a: active + * - x: suspended + * - r: reactivating + * - c: closing + */ + public function getStatus(): ?string + { + return $this->status; + } +} diff --git a/src/Message/SuspendResponse.php b/src/Message/SuspendResponse.php new file mode 100644 index 0000000..c901936 --- /dev/null +++ b/src/Message/SuspendResponse.php @@ -0,0 +1,61 @@ +isSuccessful()) { + if (preg_match( + '/This account is not active so can not be suspended \( vPuser : (\S+) , status : (\S+) , reason : (.*) \) ../s', + $this->getMessage(), + $matches) + ) { + $this->username = trim($matches[1]); + $this->status = trim($matches[2]); + $this->reason = trim($matches[3]); + } + } + } + + /** + * Get the status of the account if it's not active. + * + * The result is one of the following chars: + * - x: suspended + * - r: reactivating + * - c: closing + */ + public function getStatus(): ?string + { + return $this->status; + } + + /** + * Get the username of the account if it's not active. + */ + public function getVpUsername(): ?string + { + return $this->username; + } + + /** + * Get the suspension reason of the account if it's not active. + */ + public function getReason(): ?string + { + return $this->reason; + } +} diff --git a/src/Message/UnsuspendResponse.php b/src/Message/UnsuspendResponse.php new file mode 100644 index 0000000..6034134 --- /dev/null +++ b/src/Message/UnsuspendResponse.php @@ -0,0 +1,39 @@ +isSuccessful()) { + if (preg_match('/account is NOT currently suspended \(status : (\w*) \)/', $this->getMessage(), $matches)) { + if (trim($matches[1]) == '') { + $this->status = 'd'; + } else { + $this->status = trim($matches[1]); + } + } + } + } + + /** + * Get the status of the account if it's not suspended. + * + * Is one of the following chars: + * - a: active + * - r: reactivating + * - c: closing + */ + public function getStatus(): ?string + { + return $this->status; + } +} diff --git a/tests/ClientTest.php b/tests/ClientTest.php new file mode 100644 index 0000000..1a1f3e1 --- /dev/null +++ b/tests/ClientTest.php @@ -0,0 +1,243 @@ +faker = FakerFactory::create(); + $this->apiUsername = base64_encode($this->faker->randomNumber()); + $this->apiPassword = base64_encode($this->faker->randomNumber()); + + $this->guzzleMockHandler = new MockHandler(); + $this->historyContainer = []; + + $handlerStack = HandlerStack::create($this->guzzleMockHandler); + $handlerStack->push(Middleware::history($this->historyContainer)); + $guzzle = new Guzzle(['handler' => $handlerStack]); + + $this->client = new Client($this->apiUsername, $this->apiPassword, 'https://panel.myownfreehost.net/xml-api/', $guzzle); + } + + public function testCreateAccount() + { + $username = $this->faker->lexify('????????'); + $password = $this->faker->regexify('[a-zA-Z0-9]{8,15}'); + $email = $this->faker->email(); + $domain = $this->faker->domainName(); + $plan = $this->faker->word(); + + $this->guzzleMockHandler->append(new Response()); + + $response = $this->client->createAccount($username, $password, $email, $domain, $plan); + $this->assertInstanceOf(CreateAccountResponse::class, $response); + + $this->assertCount(1, $this->historyContainer); + $request = $this->historyContainer[0]['request']; + $this->assertEquals('POST', $request->getMethod()); + $this->assertEquals('/xml-api/createacct', $request->getUri()->getPath()); + parse_str($request->getBody(), $postData); + $this->assertEquals([ + 'username' => $username, + 'password' => $password, + 'contactemail' => $email, + 'domain' => $domain, + 'plan' => $plan, + ], $postData); + } + + public function testSuspend() + { + $username = $this->faker->bothify('????_########'); + $reason = $this->faker->sentence(); + + $this->guzzleMockHandler->append(new Response()); + + $response = $this->client->suspend($username, $reason, true); + $this->assertInstanceOf(SuspendResponse::class, $response); + + $this->assertCount(1, $this->historyContainer); + $request = $this->historyContainer[0]['request']; + $this->assertEquals('POST', $request->getMethod()); + $this->assertEquals('/xml-api/suspendacct', $request->getUri()->getPath()); + parse_str($request->getBody(), $postData); + $this->assertEquals([ + 'user' => $username, + 'reason' => $reason, + 'linked' => '1', + ], $postData); + } + + public function testUnsuspend() + { + $username = $this->faker->bothify('????_########'); + + $this->guzzleMockHandler->append(new Response()); + + $response = $this->client->unsuspend($username); + $this->assertInstanceOf(UnsuspendResponse::class, $response); + + $this->assertCount(1, $this->historyContainer); + $request = $this->historyContainer[0]['request']; + $this->assertEquals('POST', $request->getMethod()); + $this->assertEquals('/xml-api/unsuspendacct', $request->getUri()->getPath()); + parse_str($request->getBody(), $postData); + $this->assertEquals([ + 'user' => $username, + ], $postData); + } + + public function testPassword() + { + $username = $this->faker->bothify('????_########'); + $password = $this->faker->regexify('[a-zA-Z0-9]{8,15}'); + + $this->guzzleMockHandler->append(new Response()); + + $response = $this->client->password($username, $password); + $this->assertInstanceOf(PasswordResponse::class, $response); + + $this->assertCount(1, $this->historyContainer); + $request = $this->historyContainer[0]['request']; + $this->assertEquals('POST', $request->getMethod()); + $this->assertEquals('/xml-api/passwd', $request->getUri()->getPath()); + parse_str($request->getBody(), $postData); + $this->assertEquals([ + 'user' => $username, + 'pass' => $password, + ], $postData); + } + + public function testPasswordHttpError() + { + $username = $this->faker->bothify('????_########'); + $password = $this->faker->regexify('[a-zA-Z0-9]{8,15}'); + + $this->guzzleMockHandler->append(new Response(500)); + + $this->expectException(MofhClientHttpException::class); + $this->client->password($username, $password); + } + + public function testAvailability() + { + $domain = $this->faker->domainName(); + + $this->guzzleMockHandler->append(new Response()); + + $response = $this->client->availability($domain); + $this->assertInstanceOf(AvailabilityResponse::class, $response); + + $this->assertCount(1, $this->historyContainer); + $request = $this->historyContainer[0]['request']; + $this->assertEquals('GET', $request->getMethod()); + $this->assertEquals('/xml-api/checkavailable', $request->getUri()->getPath()); + parse_str($request->getUri()->getQuery(), $queryData); + $this->assertEquals([ + 'api_user' => $this->apiUsername, + 'api_key' => $this->apiPassword, + 'domain' => $domain, + ], $queryData); + } + + public function testAvailabilityHttpError() + { + $domain = $this->faker->domainName(); + + $this->guzzleMockHandler->append(new Response(403)); + + $this->expectException(MofhClientHttpException::class); + $this->client->availability($domain); + } + + public function testGetUserDomains() + { + $username = $this->faker->bothify('????_########'); + + $this->guzzleMockHandler->append(new Response()); + + $response = $this->client->getUserDomains($username); + $this->assertInstanceOf(GetUserDomainsResponse::class, $response); + + $this->assertCount(1, $this->historyContainer); + $request = $this->historyContainer[0]['request']; + $this->assertEquals('GET', $request->getMethod()); + $this->assertEquals('/xml-api/getuserdomains', $request->getUri()->getPath()); + parse_str($request->getUri()->getQuery(), $queryData); + $this->assertEquals([ + 'api_user' => $this->apiUsername, + 'api_key' => $this->apiPassword, + 'username' => $username, + ], $queryData); + } + + public function testGetDomainUser() + { + $domain = $this->faker->domainName(); + + $this->guzzleMockHandler->append(new Response()); + + $response = $this->client->getDomainUser($domain); + $this->assertInstanceOf(GetDomainUserResponse::class, $response); + + $this->assertCount(1, $this->historyContainer); + $request = $this->historyContainer[0]['request']; + $this->assertEquals('GET', $request->getMethod()); + $this->assertEquals('/xml-api/getdomainuser', $request->getUri()->getPath()); + parse_str($request->getUri()->getQuery(), $queryData); + $this->assertEquals([ + 'api_user' => $this->apiUsername, + 'api_key' => $this->apiPassword, + 'domain' => $domain, + ], $queryData); + } +} diff --git a/tests/Message/AvailabilityResponseTest.php b/tests/Message/AvailabilityResponseTest.php new file mode 100644 index 0000000..90da4c4 --- /dev/null +++ b/tests/Message/AvailabilityResponseTest.php @@ -0,0 +1,45 @@ +assertTrue($availabilityResponse->isSuccessful()); + $this->assertTrue($availabilityResponse->isAvailable()); + $this->assertNull($availabilityResponse->getMessage()); + } + + public function testNotAvailableDomain() + { + $httpResponse = new Response(200, [], '0'); + + $availabilityResponse = new AvailabilityResponse($httpResponse); + + $this->assertTrue($availabilityResponse->isSuccessful()); + $this->assertFalse($availabilityResponse->isAvailable()); + $this->assertNull($availabilityResponse->getMessage()); + } + + public function testError() + { + $message = 'ERROR :Illegal charachters in domain name . . This domain name does not appear to be valid (to short !). .'; + + $httpResponse = new Response(200, [], $message); + + $availabilityResponse = new AvailabilityResponse($httpResponse); + + $this->assertFalse($availabilityResponse->isSuccessful()); + $this->assertFalse($availabilityResponse->isAvailable()); + $this->assertEquals($message, $availabilityResponse->getMessage()); + } +} diff --git a/tests/Message/CreateAccountResponseTest.php b/tests/Message/CreateAccountResponseTest.php new file mode 100644 index 0000000..2055d6e --- /dev/null +++ b/tests/Message/CreateAccountResponseTest.php @@ -0,0 +1,160 @@ +faker = FakerFactory::create(); + } + + public function testSuccessful() + { + $username = $this->faker->bothify('????_########'); + + $httpResponse = new Response(200, [], " + + + + n + {$username} + ns1.byet.org + ns2.byet.org + + + + + + + + + + + + + + account added to queue to be added + + 1 + This account has been successfuly created + + + "); + + $createAccountResponse = new CreateAccountResponse($httpResponse); + $this->assertTrue($createAccountResponse->isSuccessful()); + $this->assertEquals($username, $createAccountResponse->getVpUsername()); + $this->assertNull($createAccountResponse->getMessage()); + } + + public function testError() + { + $httpResponse = new Response(200, [], ' + + + + n + ns1.byet.org + ns2.byet.org + + + + + + + + + + + + + + account added to queue to be added + + 0 + The API username you are using appears to be invalid 1 (0). . The API username you are using appears to be invalid 2. + + + '); + + $createAccountResponse = new CreateAccountResponse($httpResponse); + + $this->assertFalse($createAccountResponse->isSuccessful()); + $this->assertEquals('The API username you are using appears to be invalid 1 (0). . The API username you are using appears to be invalid 2.', $createAccountResponse->getMessage()); + $this->assertNull($createAccountResponse->getVpUsername()); + } + + public function testDuplicateXmlDocument() + { + $httpResponse = new Response(200, [], ' + + + + n + ns1.byet.org + ns2.byet.org + + + + + + + + + + + + + + account added to queue to be added + + 0 + Name servers for domain are not valid 84572435 + + + + + n + ns1.byet.org + ns2.byet.org + + + + + + + + + + + + + + account added to queue to be added + + 0 + Name servers for domain are not valid 84572435 The name servers for example.com are not set to valid name servers. + + + '); + + $createAccountResponse = new CreateAccountResponse($httpResponse); + + $this->assertFalse($createAccountResponse->isSuccessful()); + $this->assertNull($createAccountResponse->getVpUsername()); + } +} diff --git a/tests/Message/GetDomainUserResponseTest.php b/tests/Message/GetDomainUserResponseTest.php new file mode 100644 index 0000000..21e07b7 --- /dev/null +++ b/tests/Message/GetDomainUserResponseTest.php @@ -0,0 +1,74 @@ +faker = FakerFactory::create(); + } + + public function testFound() + { + $domain = $this->faker->domainName(); + $username = $this->faker->bothify('????_########'); + $documentRoot = "/home/vol12_3/example.com/{$username}/{$domain}/htdocs"; + + $httpResponse = new Response(200, [], json_encode(['ACTIVE', $domain, $documentRoot, $username])); + + $getDomainUserResponse = new GetDomainUserResponse($httpResponse); + + $this->assertTrue($getDomainUserResponse->isSuccessful()); + $this->assertTrue($getDomainUserResponse->isFound()); + $this->assertEquals($domain, $getDomainUserResponse->getDomain()); + $this->assertEquals($username, $getDomainUserResponse->getUsername()); + $this->assertEquals($documentRoot, $getDomainUserResponse->getDocumentRoot()); + $this->assertEquals('ACTIVE', $getDomainUserResponse->getStatus()); + $this->assertNull($getDomainUserResponse->getMessage()); + } + + public function testNotFound() + { + $httpResponse = new Response(200, [], 'null'); + + $getDomainUserResponse = new GetDomainUserResponse($httpResponse); + + $this->assertTrue($getDomainUserResponse->isSuccessful()); + $this->assertFalse($getDomainUserResponse->isFound()); + $this->assertNull($getDomainUserResponse->getDomain()); + $this->assertNull($getDomainUserResponse->getUsername()); + $this->assertNull($getDomainUserResponse->getDocumentRoot()); + $this->assertNull($getDomainUserResponse->getStatus()); + $this->assertNull($getDomainUserResponse->getMessage()); + } + + public function testError() + { + $message = 'ERROR :The API key you are using appears to be invalid 1. . The API key you are using appears to be invalid 2. . '; + $httpResponse = new Response(200, [], $message); + + $getDomainUserResponse = new GetDomainUserResponse($httpResponse); + + $this->assertFalse($getDomainUserResponse->isSuccessful()); + $this->assertFalse($getDomainUserResponse->isFound()); + $this->assertNull($getDomainUserResponse->getDomain()); + $this->assertNull($getDomainUserResponse->getUsername()); + $this->assertNull($getDomainUserResponse->getDocumentRoot()); + $this->assertNull($getDomainUserResponse->getStatus()); + $this->assertEquals(trim($message), $getDomainUserResponse->getMessage()); + } +} diff --git a/tests/Message/GetUserDomainsResponseTest.php b/tests/Message/GetUserDomainsResponseTest.php new file mode 100644 index 0000000..0ad8d6c --- /dev/null +++ b/tests/Message/GetUserDomainsResponseTest.php @@ -0,0 +1,86 @@ +faker = FakerFactory::create(); + } + + public function testReturnsDomains() + { + $domain1 = $this->faker->domainName(); + $domain2 = $this->faker->domainName(); + + $httpResponse = new Response(200, [], json_encode([ + ['ACTIVE', $domain1], + ['ACTIVE', $domain2], + ])); + + $getUserDomainsResponse = new GetUserDomainsResponse($httpResponse); + + $this->assertTrue($getUserDomainsResponse->isSuccessful()); + $this->assertEquals([$domain1, $domain2], $getUserDomainsResponse->getDomains()); + $this->assertEquals('ACTIVE', $getUserDomainsResponse->getStatus()); + $this->assertNull($getUserDomainsResponse->getMessage()); + } + + public function testNoDomains() + { + $httpResponse = new Response(200, [], 'null'); + + $getUserDomainsResponse = new GetUserDomainsResponse($httpResponse); + + $this->assertTrue($getUserDomainsResponse->isSuccessful()); + $this->assertEquals([], $getUserDomainsResponse->getDomains()); + $this->assertEquals(null, $getUserDomainsResponse->getStatus()); + $this->assertNull($getUserDomainsResponse->getMessage()); + } + + public function testError() + { + $message = 'ERROR :The API key you are using appears to be invalid 1. . The API key you are using appears to be invalid 2. . '; + $httpResponse = new Response(200, [], $message); + + $getUserDomainsResponse = new GetUserDomainsResponse($httpResponse); + + $this->assertFalse($getUserDomainsResponse->isSuccessful()); + $this->assertEquals([], $getUserDomainsResponse->getDomains()); + $this->assertEquals(null, $getUserDomainsResponse->getStatus()); + $this->assertEquals(trim($message), $getUserDomainsResponse->getMessage()); + } + + public function testMistmachedStatuses() + { + $domain1 = $this->faker->domainName(); + $domain2 = $this->faker->domainName(); + + $httpResponse = new Response(200, [], json_encode([ + ['ACTIVE', $domain1], + ['SUSPENDED', $domain2], + ])); + + $getUserDomainsResponse = new GetUserDomainsResponse($httpResponse); + + $this->assertTrue($getUserDomainsResponse->isSuccessful()); + + $this->expectException(MismatchedStatusesException::class); + $getUserDomainsResponse->getStatus(); + } +} diff --git a/tests/Message/PasswordResponseTest.php b/tests/Message/PasswordResponseTest.php new file mode 100644 index 0000000..6dc52cf --- /dev/null +++ b/tests/Message/PasswordResponseTest.php @@ -0,0 +1,155 @@ +faker = FakerFactory::create(); + } + + public function testSuccess() + { + $shortUsername = $this->faker->lexify('????????'); + + $httpResponse = new Response(200, [], " + + + + Changing password for {$shortUsername} + Password for {$shortUsername} has been changed + Updating ftp passwords for {$shortUsername} + Ftp password files updated. + Ftp vhost passwords synced + + + system + + + ftp + + + mail + + + mySQL + + 1 + Password changed for user {$shortUsername} + + + "); + + $passwordResponse = new PasswordResponse($httpResponse); + + $this->assertTrue($passwordResponse->isSuccessful()); + $this->assertEquals('a', $passwordResponse->getStatus()); + $this->assertNull($passwordResponse->getMessage()); + } + + public function testPasswordIdentical() + { + $shortUsername = $this->faker->lexify('????????'); + + $httpResponse = new Response(200, [], " + + + + Changing password for {$shortUsername} + Password for {$shortUsername} has been changed + Updating ftp passwords for {$shortUsername} + Ftp password files updated. + Ftp vhost passwords synced + + + system + + + ftp + + + mail + + + mySQL + + 0 + An error occured changing this password. + + + "); + + $passwordResponse = new PasswordResponse($httpResponse); + + $this->assertTrue($passwordResponse->isSuccessful()); + $this->assertEquals('a', $passwordResponse->getStatus()); + $this->assertNull($passwordResponse->getMessage()); + } + + public function testAccountNotActive() + { + $shortUsername = $this->faker->lexify('????????'); + + $httpResponse = new Response(200, [], " + + + + Changing password for {$shortUsername} + Password for {$shortUsername} has been changed + Updating ftp passwords for {$shortUsername} + Ftp password files updated. + Ftp vhost passwords synced + + + system + + + ftp + + + mail + + + mySQL + + 0 + This account currently not active, the account must be active to change the password (x). . + + + "); + + $passwordResponse = new PasswordResponse($httpResponse); + + $this->assertFalse($passwordResponse->isSuccessful()); + $this->assertEquals('x', $passwordResponse->getStatus()); + $this->assertEquals( + 'This account currently not active, the account must be active to change the password (x). .', + $passwordResponse->getMessage() + ); + } + + public function testError() + { + $httpResponse = new Response(200, [], 'The API username you are using appears to be invalid 1. . '); + + $passwordResponse = new PasswordResponse($httpResponse); + + $this->assertFalse($passwordResponse->isSuccessful()); + $this->assertNull($passwordResponse->getStatus()); + $this->assertEquals('The API username you are using appears to be invalid 1. .', $passwordResponse->getMessage()); + } +} diff --git a/tests/Message/SuspendResponseTest.php b/tests/Message/SuspendResponseTest.php new file mode 100644 index 0000000..cf77be6 --- /dev/null +++ b/tests/Message/SuspendResponseTest.php @@ -0,0 +1,152 @@ +faker = FakerFactory::create(); + } + + public function testSuccess() + { + $httpResponse = new Response(200, [], " + + + 1 + + + Changing Shell to /bin/false...Changing shell for utlvigl7. + Shell changed. + Locking Password...Locking password for user utlvigl7. + marking user vhosts / databases for suspension. + .. + .. + Completed, this account will be fully suspended in 2 minutes. + + + + "); + + $suspendResponse = new SuspendResponse($httpResponse); + + $this->assertTrue($suspendResponse->isSuccessful()); + $this->assertNull($suspendResponse->getStatus()); + $this->assertNull($suspendResponse->getVpUsername()); + $this->assertNull($suspendResponse->getReason()); + $this->assertNull($suspendResponse->getMessage()); + } + + public function testNotActive() + { + $username = $this->faker->bothify('????_########'); + $reason = $this->faker->sentence(); + + $httpResponse = new Response(200, [], " + + + 0 + + This account is not active so can not be suspended ( vPuser : {$username} , status : x , reason : {$reason} ) .. + + + + "); + + $suspendResponse = new SuspendResponse($httpResponse); + + $this->assertFalse($suspendResponse->isSuccessful()); + $this->assertEquals('x', $suspendResponse->getStatus()); + $this->assertEquals($username, $suspendResponse->getVpUsername()); + $this->assertEquals($reason, $suspendResponse->getReason()); + $this->assertEquals( + "This account is not active so can not be suspended ( vPuser : {$username} , status : x , reason : {$reason} ) ..", + $suspendResponse->getMessage() + ); + } + + public function testSuspendedWithEmptyReason() + { + $username = $this->faker->bothify('????_########'); + + $httpResponse = new Response(200, [], " + + + 0 + + This account is not active so can not be suspended ( vPuser : {$username} , status : x , reason : ) .. + + + + "); + + $suspendResponse = new SuspendResponse($httpResponse); + + $this->assertFalse($suspendResponse->isSuccessful()); + $this->assertEquals('x', $suspendResponse->getStatus()); + $this->assertEquals($username, $suspendResponse->getVpUsername()); + $this->assertEquals('', $suspendResponse->getReason()); + $this->assertEquals( + "This account is not active so can not be suspended ( vPuser : {$username} , status : x , reason : ) ..", + $suspendResponse->getMessage() + ); + } + + public function testSuspendedWithReasonOnMultipleLines() + { + $username = $this->faker->bothify('????_########'); + + $reason = $this->faker->sentence." +

+ Hello world! +

+ + "; + $encodedReason = htmlspecialchars($reason); + + $httpResponse = new Response(200, [], " + + + 0 + + This account is not active so can not be suspended ( vPuser : {$username} , status : x , reason : {$encodedReason} ) .. + + + + "); + + $suspendResponse = new SuspendResponse($httpResponse); + + $this->assertFalse($suspendResponse->isSuccessful()); + $this->assertEquals('x', $suspendResponse->getStatus()); + $this->assertEquals($username, $suspendResponse->getVpUsername()); + $this->assertEquals(trim($reason), $suspendResponse->getReason()); + } + + public function testError() + { + $httpResponse = new Response(200, [], 'The API username you are using appears to be invalid 1. . '); + + $suspendResponse = new SuspendResponse($httpResponse); + + $this->assertFalse($suspendResponse->isSuccessful()); + $this->assertNull($suspendResponse->getStatus()); + $this->assertNull($suspendResponse->getVpUsername()); + $this->assertNull($suspendResponse->getReason()); + $this->assertEquals('The API username you are using appears to be invalid 1. .', $suspendResponse->getMessage()); + } +} diff --git a/tests/Message/UnsuspendResponseTest.php b/tests/Message/UnsuspendResponseTest.php new file mode 100644 index 0000000..a32f8f9 --- /dev/null +++ b/tests/Message/UnsuspendResponseTest.php @@ -0,0 +1,96 @@ +faker = FakerFactory::create(); + } + + public function testSuccess() + { + $httpResponse = new Response(200, [], " + + + 1 + + + abcd1234 account has been unsuspended + + + + "); + + $unsuspendResponse = new UnsuspendResponse($httpResponse); + + $this->assertTrue($unsuspendResponse->isSuccessful()); + $this->assertNull($unsuspendResponse->getStatus()); + $this->assertNull($unsuspendResponse->getMessage()); + } + + public function testNotSuspended() + { + $httpResponse = new Response(200, [], ' + + + 0 + + This account is NOT currently suspended (status : r ) . . + + + + '); + + $unsuspendResponse = new UnsuspendResponse($httpResponse); + + $this->assertFalse($unsuspendResponse->isSuccessful()); + $this->assertEquals('r', $unsuspendResponse->getStatus()); + $this->assertEquals('This account is NOT currently suspended (status : r ) . .', $unsuspendResponse->getMessage()); + } + + public function testNotFound() + { + $httpResponse = new Response(200, [], ' + + + 0 + + This account is NOT currently suspended (status : ) . . + + + + '); + + $unsuspendResponse = new UnsuspendResponse($httpResponse); + + $this->assertFalse($unsuspendResponse->isSuccessful()); + $this->assertEquals('d', $unsuspendResponse->getStatus()); + $this->assertEquals('This account is NOT currently suspended (status : ) . .', $unsuspendResponse->getMessage()); + } + + public function testError() + { + $httpResponse = new Response(200, [], 'The API username you are using appears to be invalid 1. . '); + + $unsuspendResponse = new UnsuspendResponse($httpResponse); + + $this->assertFalse($unsuspendResponse->isSuccessful()); + $this->assertNull($unsuspendResponse->getStatus()); + $this->assertEquals('The API username you are using appears to be invalid 1. .', $unsuspendResponse->getMessage()); + } +}