diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..1623cc9 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Global owners. +* @othercodes \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..9228d43 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,44 @@ +name: Tests + +on: + pull_request: + types: [ opened, synchronize, reopened ] + +jobs: + test: + runs-on: ubuntu-latest + + strategy: + matrix: + php-version: + - "7.4" + - "8.0" + - "8.1" + + steps: + - name: Checkout source code + uses: actions/checkout@v2 + + - name: Install PHP ${{ matrix.php-version }} + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-version }} + extensions: mbstring,xmlrpc,xml,json + coverage: pcov + tools: composer:v2 + + - name: Cache dependencies + uses: actions/cache@v2 + with: + path: ~/.composer/cache + key: php-${{ matrix.php-version }}-composer-${{ hashFiles('**/composer.json') }} + restore-keys: php-${{ matrix.php-version }}-composer- + + - name: Validate composer.json and composer.lock + run: composer validate + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-suggest + + - name: Execute tests (Unit and Feature tests) via PHPUnit + run: composer test diff --git a/.gitignore b/.gitignore index cdb3d20..97a6a13 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .idea/ vendor/ -composer.lock \ No newline at end of file +composer.lock +.phpunit.result.cache diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 905216a..0000000 --- a/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: php - -php: - - '5.5' - - '5.6' - - '7.0' - -install: - - composer install - -script: - - ./vendor/bin/phpunit -c ./phpunit.xml - - ./vendor/bin/phpunit --coverage-clover=coverage.xml - -after_success: - - bash <(curl -s https://codecov.io/bash) \ No newline at end of file diff --git a/README.md b/README.md index 6a73fd0..4d70c1f 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,19 @@ # Rest Client -[![Build Status](https://travis-ci.org/othercodes/rest.svg?branch=master)](https://travis-ci.org/othercodes/rest) [![Latest Stable Version](https://poser.pugx.org/othercode/rest/v/stable)](https://packagist.org/packages/othercode/rest) [![License](https://poser.pugx.org/othercode/rest/license)](https://packagist.org/packages/othercode/rest) -[![Total Downloads](https://poser.pugx.org/othercode/rest/downloads)](https://packagist.org/packages/othercode/rest) [![codecov](https://codecov.io/gh/othercodes/rest/branch/master/graph/badge.svg)](https://codecov.io/gh/othercodes/rest) +[![Tests](https://github.com/othercodes/rest/actions/workflows/test.yml/badge.svg)](https://github.com/othercodes/rest/actions/workflows/test.yml) [![Latest Stable Version](https://poser.pugx.org/othercode/rest/v/stable)](https://packagist.org/packages/othercode/rest) [![License](https://poser.pugx.org/othercode/rest/license)](https://packagist.org/packages/othercode/rest) +[![Total Downloads](https://poser.pugx.org/othercode/rest/downloads)](https://packagist.org/packages/othercode/rest) - -[Rest client](http://othercode.es/packages/rest-client.html) to make GET, POST, PUT, DELETE, PATCH, etc calls. +[Rest client](http://othercode.es/packages/rest-client.html) to make GET, POST, PUT, DELETE, PATCH, etc. ## Installation To install the package we only have to add the dependency to ***composer.json*** file: -```javascript +```json { - "require": { - "othercode/rest": "*" - } + "require": { + "othercode/rest": "*" + } } ``` @@ -26,20 +25,20 @@ composer install ## Usage -To use the Rest we only have to instantiate it and configure the params we want. We can -establish the configuration accessing to the `->configuration->configure_property`, for example +To use the Rest we only have to instantiate it and configure the params we want. We can +establish the configuration accessing to the `->configuration->configure_property`, for example to configure the url of the call we only have to set the `->configuration->url parameter` like we can see as follows: ```php $api = new \OtherCode\Rest\Rest(); -$api->configuration->url = "http://jsonplaceholder.typicode.com/"; +$api->configuration->url = "https://jsonplaceholder.typicode.com/"; ``` or ```php $api = new \OtherCode\Rest\Rest(new \OtherCode\Rest\Core\Configuration(array( - 'url' => 'http://jsonplaceholder.typicode.com/', + 'url' => 'https://jsonplaceholder.typicode.com/', ))); ``` @@ -50,11 +49,12 @@ going to perform a **GET** request to the **"posts/1"** endpoint: $response = $api->get("posts/1"); ``` -The rest client will throw a `ConnectionException` if there any problem related to the connection. +The rest client will throw a `ConnectionException` if there are any problem related to the connection. -**NOTE: These errors are related to the session cURL, here is the [complete list](https://curl.haxx.se/libcurl/c/libcurl-errors.html)** +**NOTE: These errors are related to the session cURL, here is +the [complete list](https://curl.haxx.se/libcurl/c/libcurl-errors.html)** -## Methods +## Methods The available methods to work with are: @@ -62,10 +62,10 @@ The available methods to work with are: Perform a GET request. -Parameters | Type | Description ------------------------------ | ------- | ------------------------------------------- -`$url` | String | Required. The URL to which the request is made -`$data` | Array | Optional. Associative array of data parameters +| Parameters | Type | Description | +|------------|--------|------------------------------------------------| +| `$url` | String | Required. The URL to which the request is made | +| `$data` | Array | Optional. Associative array of data parameters | **Return**: Response object @@ -73,9 +73,9 @@ Parameters | Type | Description Perform a HEAD request. -Parameters | Type | Description ------------------------------ | ------- | ------------------------------------------- -`$url` | String | Required. The URL to which the request is made +| Parameters | Type | Description | +|------------|--------|------------------------------------------------| +| `$url` | String | Required. The URL to which the request is made | **Return**: Response object (no body) @@ -83,10 +83,10 @@ Parameters | Type | Description Perform a POST request. -Parameters | Type | Description ------------------------------ | ------- | ------------------------------------------- -`$url` | String | Required. The URL to which the request is made -`$data` | Array | Optional. Associative array of data parameters +| Parameters | Type | Description | +|------------|--------|------------------------------------------------| +| `$url` | String | Required. The URL to which the request is made | +| `$data` | Array | Optional. Associative array of data parameters | **Return**: Response object @@ -94,10 +94,10 @@ Parameters | Type | Description Perform a DELETE request. -Parameters | Type | Description ------------------------------ | ------- | ------------------------------------------- -`$url` | String | Required. The URL to which the request is made -`$data` | Array | Optional. Associative array of data parameters +| Parameters | Type | Description | +|------------|--------|------------------------------------------------| +| `$url` | String | Required. The URL to which the request is made | +| `$data` | Array | Optional. Associative array of data parameters | **Return**: Response object @@ -105,10 +105,10 @@ Parameters | Type | Description Perform a PUT request. -Parameters | Type | Description ------------------------------ | ------- | ------------------------------------------- -`$url` | String | Required. The URL to which the request is made -`$data` | Array | Optional. Associative array of data parameters +| Parameters | Type | Description | +|------------|--------|------------------------------------------------| +| `$url` | String | Required. The URL to which the request is made | +| `$data` | Array | Optional. Associative array of data parameters | **Return**: Response object @@ -116,10 +116,10 @@ Parameters | Type | Description Perform a PATCH request. -Parameters | Type | Description ------------------------------ | ------- | ------------------------------------------- -`$url` | String | Required. The URL to which the request is made -`$data` | Array | Optional. Associative array of data parameters +| Parameters | Type | Description | +|------------|--------|------------------------------------------------| +| `$url` | String | Required. The URL to which the request is made | +| `$data` | Array | Optional. Associative array of data parameters | **Return**: Response object @@ -145,10 +145,10 @@ Return an array with the `Response` and `Request` objects. Set a new Decoder. -Parameters | Type | Description ------------------------------ | ------- | ------------------------------------------- -`$name` | String | Required. The unique name of the decoder. -`$decoder` | String | Optional. The class name with namespace of the new decoder. +| Parameters | Type | Description | +|------------|--------|-------------------------------------------------------------| +| `$name` | String | Required. The unique name of the decoder. | +| `$decoder` | String | Optional. The class name with namespace of the new decoder. | **Return**: Rest object @@ -156,10 +156,10 @@ Parameters | Type | Description Set a new Encoder. -Parameters | Type | Description ------------------------------ | ------- | ------------------------------------------- -`$name` | String | Required. The unique name of the encoder. -`$encoder` | String | Optional. The class name with namespace of the new encoder. +| Parameters | Type | Description | +|------------|--------|-------------------------------------------------------------| +| `$name` | String | Required. The unique name of the encoder. | +| `$encoder` | String | Optional. The class name with namespace of the new encoder. | **Return**: Rest object @@ -167,11 +167,11 @@ Parameters | Type | Description Set a new Module. -Parameters | Type | Description ------------------------------ | ------- | ------------------------------------------- -`$name` | String | Required. The unique name of the module. -`$module` | String | Required. The class name with namespace of the new module. -`$hook` | String | Optional. The hook name (after/before) that will trigger the module, 'after' by default. +| Parameters | Type | Description | +|------------|--------|------------------------------------------------------------------------------------------| +| `$name` | String | Required. The unique name of the module. | +| `$module` | String | Required. The class name with namespace of the new module. | +| `$hook` | String | Optional. The hook name (after/before) that will trigger the module, 'after' by default. | **Return**: Rest object @@ -179,10 +179,10 @@ Parameters | Type | Description Unregister a module. -Parameters | Type | Description ------------------------------ | ------ | ------------------------------------------- -`$moduleName` | String | Required. The unique name of the decoder. -`$hook` | String | Optional. The hook name (after/before) from where delete the module. +| Parameters | Type | Description | +|---------------|--------|----------------------------------------------------------------------| +| `$moduleName` | String | Required. The unique name of the decoder. | +| `$hook` | String | Optional. The hook name (after/before) from where delete the module. | **Return**: Rest object @@ -190,10 +190,10 @@ Parameters | Type | Description Add a new header. -Parameters | Type | Description ------------------------------ | ------ | ------------------------------------------- -`$header` | String | Required. The unique name of the header. -`$value` | String | Requires. The value of the header. +| Parameters | Type | Description | +|------------|--------|------------------------------------------| +| `$header` | String | Required. The unique name of the header. | +| `$value` | String | Requires. The value of the header. | **Return**: Rest object @@ -201,13 +201,14 @@ Parameters | Type | Description Add an array of headers. -Parameters | Type | Description ------------------------------ | ------ | ------------------------------------------- -`$headers` | String | Required. An array of headers. +| Parameters | Type | Description | +|------------|--------|--------------------------------| +| `$headers` | String | Required. An array of headers. | **Return**: Rest object -**NOTE: We can use the `addHeader()` and `addHeaders()` methods with the `Rest` instance or with the `configuration` object** +**NOTE: We can use the `addHeader()` and `addHeaders()` methods with the `Rest` instance or with the `configuration` +object** ```php $api->addHeader('some_header','some_value'); @@ -225,9 +226,9 @@ $api->configuration->addHeaders(array('some_header' => 'some_value','other_heade Remove a header offset. -Parameters | Type | Description ------------------------------ | ------ | ------------------------------------------- -`$header` | String | Required. The unique name of the header. +| Parameters | Type | Description | +|------------|--------|------------------------------------------| +| `$header` | String | Required. The unique name of the header. | **Return**: Rest object @@ -235,15 +236,15 @@ Parameters | Type | Description Remove an array of headers. -Parameters | Type | Description ------------------------------ | ------ | ------------------------------------------- -`$headers` | String | Required. An array of headers to remove. +| Parameters | Type | Description | +|------------|--------|------------------------------------------| +| `$headers` | String | Required. An array of headers to remove. | **Return**: Rest object ## Modules -This package allow you to create modules to perform task before and after the request.. +This package allow you to create modules to perform task before and after the request. To create a new module we only have to use this template: ```php @@ -261,9 +262,9 @@ class CustomModule extends BaseModule The only method that is mandatory is `->run()`, this method execute your custom code of the module. Once we have our module we can register it with the `->setModule()` method. This method needs three parameters, -the first one is the name of the module, the second one is the complete namespace of the module, and the third one -is the hook name for our module, it can be "before" and "after" depends when we want to launch our module. - +the first one is the name of the module, the second one is the complete namespace of the module, and the third one +is the hook name for our module, it can be "before" and "after" depends on when we want to launch our module. + ```php $api->setModule('module_name','Module\Complete\Namespace','after'); ``` @@ -271,7 +272,7 @@ $api->setModule('module_name','Module\Complete\Namespace','after'); For "before" modules you can use all the properties of the Request object. * `method` -* `url` +* `url` * `headers` * `body` @@ -285,20 +286,21 @@ For "after" modules you can use all the properties of the Response object. * `error` * `metadata` -All modules are executed in the order that we register them into the Rest client, this also affect +All modules are executed in the order that we register them into the Rest client, this also affect to Decoders and Encoders. ## Decoders -A decoder is a kind of module that allows you to automatically decode de response in xml or json, to use them +A decoder is a kind of module that allows you to automatically decode de response in xml or json, to use them we only have to set the decoder we want with the `->setDecoder()` method: ```php $api->setDecoder("json"); ``` -The default allowed values for this method are: ***json***, ***xml*** and ***xmlrpc***. All the decoders are always executed -in the "after" hook. +The default allowed values for this method are: ***json***, ***xml*** and ***xmlrpc***. All the decoders are always +executed +in the "after" hook. ### Custom Decoders @@ -316,18 +318,17 @@ class CustomDecoder extends BaseDecoder } ``` -Like in modules, we have the Response object available to work. The $contentType property is the content-type -that will trigger the decoder, in the example above all responses with content-type "application/json" will +Like in modules, we have the Response object available to work. The $contentType property is the content-type +that will trigger the decoder, in the example above all responses with content-type "application/json" will trigger this decoder. - ### Quick Calls We can do quick calls using the `\OtherCode\Rest\Payloads\Request::call()` method. This static method returns a -Rest instance so we can use all the methods from it. +Rest instance, so we can use all the methods from it. ``` -$response = \OtherCode\Rest\Payloads\Request::call('http://jsonplaceholder.typicode.com') +$response = \OtherCode\Rest\Payloads\Request::call('https://jsonplaceholder.typicode.com') ->setDecoder('json') ->get('/posts/1'); ``` @@ -340,7 +341,7 @@ require_once '../autoload.php'; try { $api = new \OtherCode\Rest\Rest(new \OtherCode\Rest\Core\Configuration(array( - 'url' => 'http://jsonplaceholder.typicode.com/', + 'url' => 'https://jsonplaceholder.typicode.com/', 'httpheader' => array( 'some_header' => 'some_value', ) diff --git a/composer.json b/composer.json index 170983d..4f81b9d 100644 --- a/composer.json +++ b/composer.json @@ -18,10 +18,14 @@ } ], "require": { - "php": ">=5.5", - "ext-curl": "*" + "php": ">=7.4.33", + "ext-curl": "*", + "ext-xmlrpc": "*", + "ext-simplexml": "*", + "ext-json": "*" }, "require-dev": { + "pestphp/pest": "^1.0", "phpunit/phpunit": "*" }, "autoload": { @@ -33,5 +37,18 @@ "psr-4": { "Tests\\": "tests/" } - } -} \ No newline at end of file + }, + "scripts": { + "test": "pest" + }, + "config": { + "preferred-install": "dist", + "sort-packages": true, + "optimize-autoloader": true, + "allow-plugins": { + "pestphp/pest-plugin": true + } + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/phpunit.xml b/phpunit.xml index f098a60..0aceb86 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,9 +1,9 @@ - - - - ./src/ - - + + + tests/ConfigurationTest.php @@ -19,4 +19,9 @@ tests/ModulesTest.php - \ No newline at end of file + + + ./src/ + + + diff --git a/src/Core/Configuration.php b/src/Core/Configuration.php index 9053aa7..16fc54f 100755 --- a/src/Core/Configuration.php +++ b/src/Core/Configuration.php @@ -2,21 +2,23 @@ namespace OtherCode\Rest\Core; +use OtherCode\Rest\Exceptions\RestException; +use OtherCode\Rest\Payloads\Headers; + /** * Class Configuration * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Core */ -class Configuration extends \OtherCode\Rest\Core\CurlOpts +class Configuration extends CurlOpts { /** * Configuration constructor. - * @param array $source + * @param array $source */ - public function __construct($source = array()) + public function __construct(array $source = []) { - $this->httpheader = new \OtherCode\Rest\Payloads\Headers(); + $this->httpheader = new Headers(); $allowed = array_keys(get_class_vars(get_class($this))); foreach ($source as $key => $value) { @@ -34,11 +36,11 @@ public function __construct($source = array()) /** * Add a single new header - * @param $header - * @param $value + * @param string $header + * @param mixed $value * @return $this */ - public function addHeader($header, $value) + public function addHeader(string $header, $value): Configuration { $this->httpheader[$header] = $value; return $this; @@ -46,10 +48,10 @@ public function addHeader($header, $value) /** * Add a bunch of headers - * @param array $headers + * @param array $headers * @return $this */ - public function addHeaders(array $headers) + public function addHeaders(array $headers): Configuration { foreach ($headers as $header => $value) { $this->addHeader($header, $value); @@ -59,21 +61,21 @@ public function addHeaders(array $headers) /** * Remove a header - * @param string $header + * @param string $header * @return $this */ - public function removeHeader($header) + public function removeHeader(string $header): Configuration { unset($this->httpheader[$header]); return $this; } /** - * Remove an set of headers - * @param array $headers + * Remove a set of headers + * @param array $headers * @return $this */ - public function removeHeaders(array $headers) + public function removeHeaders(array $headers): Configuration { foreach ($headers as $header) { $this->removeHeader($header); @@ -83,22 +85,22 @@ public function removeHeaders(array $headers) /** * Set the basic http auth - * @param $username - * @param $password + * @param string $username + * @param string $password * @return $this */ - public function basicAuth($username, $password) + public function basicAuth(string $username, string $password): Configuration { - $this->userpwd = $username . '=' . $password; + $this->userpwd = $username.'='.$password; return $this; } /** * Add a SSL Certificate - * @param string $certificate + * @param string $certificate * @return $this */ - public function setSSLCertificate($certificate) + public function setSSLCertificate(string $certificate): Configuration { $this->sslcert = $certificate; return $this; @@ -106,15 +108,15 @@ public function setSSLCertificate($certificate) /** * Set a CA Certificate to validate peers - * @param string $path - * @param string $type Can be capath or cainfo - * @throws \OtherCode\Rest\Exceptions\RestException + * @param string $path + * @param string $type Can be capath or cainfo * @return $this + * @throws RestException */ - public function setCACertificates($path, $type) + public function setCACertificates(string $path, string $type): Configuration { - if (!in_array($type, array('capath', 'cainfo'))) { - throw new \OtherCode\Rest\Exceptions\RestException('Invalid param "type" in for ' . __METHOD__ . 'method.'); + if (!in_array($type, ['capath', 'cainfo'])) { + throw new RestException('Invalid param "type" in for '.__METHOD__.'method.'); } $this->ssl_verifypeer = true; @@ -127,13 +129,14 @@ public function setCACertificates($path, $type) * Transform the object to array. * @return array */ - public function toArray() + public function toArray(): array { - $array = array(); + $array = []; $allowed = get_class_vars(get_class($this)); foreach (get_object_vars($this) as $key => $item) { if (array_key_exists($key, $allowed) && isset($item)) { - $array[constant(strtoupper("CURLOPT_" . $key))] = ((is_string($item) || is_object($item)) && method_exists($item, 'build') ? $item->build() : $item); + $array[constant(strtoupper("CURLOPT_".$key))] = ((is_string($item) || is_object($item)) + && method_exists($item, 'build') ? $item->build() : $item); } } return $array; diff --git a/src/Core/Core.php b/src/Core/Core.php index 00c1873..fd79282 100755 --- a/src/Core/Core.php +++ b/src/Core/Core.php @@ -2,10 +2,15 @@ namespace OtherCode\Rest\Core; +use OtherCode\Rest\Exceptions\ConnectionException; +use OtherCode\Rest\Exceptions\RestException; +use OtherCode\Rest\Modules\BaseModule; +use OtherCode\Rest\Payloads\Request; +use OtherCode\Rest\Payloads\Response; + /** * Class Core * @author Unay Santisteban - * @version 1.3.1 * @package OtherCode\Rest\Core */ abstract class Core @@ -14,39 +19,39 @@ abstract class Core /** * Core version */ - const VERSION = "1.4.0"; + const VERSION = "1.5.0"; /** * Configuration class - * @var \OtherCode\Rest\Core\Configuration + * @var Configuration */ - public $configuration; + public Configuration $configuration; /** * Last known error - * @var \OtherCode\Rest\Core\Error + * @var Error */ - public $error; + public Error $error; /** - * The data to be send - * @var \OtherCode\Rest\Payloads\Request + * The data to be sent + * @var Request */ - protected $request; + protected Request $request; /** * Stack with the response data - * @var \OtherCode\Rest\Payloads\Response + * @var Response */ - protected $response; + protected Response $response; /** * List of loaded modules * @var array */ - protected $modules = array( - 'before' => array(), - 'after' => array(), + protected array $modules = array( + 'before' => [], + 'after' => [], ); /** @@ -57,28 +62,28 @@ abstract class Core /** * Main constructor - * @param Configuration $configuration + * @param Configuration|null $configuration + * @throws RestException */ - public function __construct(\OtherCode\Rest\Core\Configuration $configuration = null) + public function __construct(Configuration $configuration = null) { - $this->response = new \OtherCode\Rest\Payloads\Response(); - $this->request = new \OtherCode\Rest\Payloads\Request(); + $this->response = new Response(); + $this->request = new Request(); $this->configure($configuration); } /** * Configure main options - * @param Configuration $configuration - * @throws \OtherCode\Rest\Exceptions\RestException + * @param Configuration|null $configuration * @return $this */ - public function configure(\OtherCode\Rest\Core\Configuration $configuration = null) + public function configure(Configuration $configuration = null): Core { if (isset($configuration)) { $this->configuration = $configuration; } else { - $this->configuration = new \OtherCode\Rest\Core\Configuration(); + $this->configuration = new Configuration(); } $this->request->setHeaders($this->configuration->httpheader); return $this; @@ -86,15 +91,14 @@ public function configure(\OtherCode\Rest\Core\Configuration $configuration = nu /** * Method: POST, PUT, GET etc - * @param string $method - * @param string $url - * @param mixed $body - * @throws \OtherCode\Rest\Exceptions\RestException - * @throws \OtherCode\Rest\Exceptions\ConfigurationException - * @throws \OtherCode\Rest\Exceptions\ConnectionException - * @return \OtherCode\Rest\Payloads\Response + * @param string $method + * @param string $url + * @param mixed $body + * @return Response + * @throws ConnectionException + * @throws RestException */ - protected function call($method, $url, $body = null) + protected function call(string $method, string $url, $body = null): Response { $this->curl = curl_init(); @@ -105,7 +109,10 @@ protected function call($method, $url, $body = null) $this->request->body = $body; $this->request->method = strtoupper($method); - $this->request->url = $this->configuration->url . $url; + + $this->request->url = isset($this->configuration->url) + ? $this->configuration->url.$url + : $url; /** * In case we have some modules attached to @@ -115,7 +122,7 @@ protected function call($method, $url, $body = null) /** * Switch between the different configurations - * depending the method used + * depending on the method used. */ switch ($this->request->method) { case "HEAD": @@ -135,7 +142,7 @@ protected function call($method, $url, $body = null) curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->request->body); break; default: - throw new \OtherCode\Rest\Exceptions\RestException('Method "' . $this->request->method . '" not supported!'); + throw new RestException('Method "'.$this->request->method.'" not supported!'); } /** @@ -151,12 +158,12 @@ protected function call($method, $url, $body = null) /** * we get the last request headers and the - * possible error and description. Also + * possible error and description. Also, * we launch a ConnectionException if needed. */ $this->setError(curl_errno($this->curl), curl_error($this->curl)); if ($this->error->code !== 0) { - throw new \OtherCode\Rest\Exceptions\ConnectionException($this->error->message, $this->error->code); + throw new ConnectionException($this->error->message, $this->error->code); } $this->response->parseResponse($response); @@ -185,7 +192,7 @@ protected function call($method, $url, $body = null) * Return the payloads of the las call * @return array */ - public function getPayloads() + public function getPayloads(): array { return array( 'request' => $this->request, @@ -197,16 +204,16 @@ public function getPayloads() * Get the curl request headers * @return array */ - public function getMetadata() + public function getMetadata(): array { return $this->response->metadata; } /** * Return the last error. - * @return \OtherCode\Rest\Core\Error + * @return Error */ - public function getError() + public function getError(): Error { return $this->error; } @@ -218,15 +225,15 @@ public function getError() */ protected function setError($code, $message) { - $this->error = new \OtherCode\Rest\Core\Error($code, $message); + $this->error = new Error($code, $message); } /** * Run all the registered modules - * @param string $hook Hook module name - * @throws \OtherCode\Rest\Exceptions\RestException + * @param string $hook Hook module name + * @throws RestException */ - private function dispatchModules($hook) + private function dispatchModules(string $hook) { foreach ($this->modules[$hook] as $module) { if (method_exists($module, 'run')) { @@ -237,12 +244,12 @@ private function dispatchModules($hook) /** * Register a new module instance - * @param string $moduleName - * @param \OtherCode\Rest\Modules\BaseModule $moduleInstance - * @param string $hook + * @param string $moduleName + * @param BaseModule $moduleInstance + * @param string $hook * @return boolean */ - protected function registerModule($moduleName, \OtherCode\Rest\Modules\BaseModule $moduleInstance, $hook) + protected function registerModule(string $moduleName, BaseModule $moduleInstance, string $hook): bool { if (!in_array($hook, array_keys($this->modules))) { return false; @@ -257,10 +264,10 @@ protected function registerModule($moduleName, \OtherCode\Rest\Modules\BaseModul /** * Unregister the module specified by $moduleName * @param $moduleName string - * @param string $hook + * @param string $hook * @return boolean */ - protected function unregisterModule($moduleName, $hook) + protected function unregisterModule(string $moduleName, string $hook): bool { if (!in_array($hook, array_keys($this->modules))) { return false; @@ -274,10 +281,10 @@ protected function unregisterModule($moduleName, $hook) /** * Return the list of registered modules. - * @param string $hook + * @param string|null $hook * @return array */ - public function getModules($hook = null) + public function getModules(string $hook = null): array { if (isset($hook) && in_array($hook, array_keys($this->modules))) { return $this->modules[$hook]; @@ -286,4 +293,4 @@ public function getModules($hook = null) return $this->modules; } -} \ No newline at end of file +} diff --git a/src/Core/CurlOpts.php b/src/Core/CurlOpts.php index f9173b9..185c8f3 100644 --- a/src/Core/CurlOpts.php +++ b/src/Core/CurlOpts.php @@ -2,11 +2,12 @@ namespace OtherCode\Rest\Core; +use OtherCode\Rest\Payloads\Headers; + /** * Class CurlOpts * @see http://php.net/manual/es/function.curl-setopt.php * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Core */ abstract class CurlOpts @@ -17,27 +18,27 @@ abstract class CurlOpts * follows a Location: redirect. * @var boolean */ - public $autoreferer; + public bool $autoreferer; /** * TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used. * @var boolean */ - public $binarytransfer; + public bool $binarytransfer; /** * TRUE to reset the HTTP request method to GET. Since GET is the default, * this is only necessary if the request method has been changed. * @var boolean */ - public $httpget; + public bool $httpget; /** * TRUE to output verbose information. Writes output to STDERR, or * the file specified using CURLOPT_STDERR. * @var boolean */ - public $verbose = false; + public bool $verbose = false; /** * FALSE to stop cURL from verifying the peer's certificate. Alternate @@ -46,7 +47,7 @@ abstract class CurlOpts * option. * @var boolean */ - public $ssl_verifypeer = false; + public bool $ssl_verifypeer = false; /** * 1 to check the existence of a common name in the SSL peer @@ -56,7 +57,7 @@ abstract class CurlOpts * kept at 2 (default value). * @var int */ - public $ssl_verifyhost; + public int $ssl_verifyhost; /** * The HTTP authentication method(s) to use. The options are: @@ -74,7 +75,7 @@ abstract class CurlOpts * CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM. * @var int */ - public $httpauth; + public int $httpauth; /** * CURL_HTTP_VERSION_NONE (default, lets CURL decide which version @@ -82,20 +83,20 @@ abstract class CurlOpts * (forces HTTP/1.1). * @var int */ - public $http_version; + public int $http_version; /** * An alternative port number to connect to. * @var int */ - public $port; + public int $port; /** * The number of seconds to wait while trying to connect. * Use 0 to wait indefinitely. * @var int */ - public $connecttimeout; + public int $connecttimeout; /** * The number of milliseconds to wait while trying to connect. @@ -105,24 +106,24 @@ abstract class CurlOpts * minimum timeout allowed of one second. * @var int */ - public $connecttimeout_ms; + public int $connecttimeout_ms; /** * The maximum number of seconds to allow cURL functions * to execute. * @var int */ - public $timeout; + public int $timeout; /** * The maximum number of milliseconds to allow cURL functions * to execute. If libcurl is built to use the standard system - * name resolver, that portion of the connect will still use + * name resolver, that portion of the connection will still use * full-second resolution for timeouts with a minimum timeout * allowed of one second. * @var int */ - public $timeout_ms; + public int $timeout_ms; /** * The contents of the "Cookie: " header to be used in @@ -131,7 +132,7 @@ abstract class CurlOpts * (e.g., "fruit=apple; colour=red") * @var string */ - public $cookie; + public string $cookie; /** * The name of the file containing the cookie data. The cookie @@ -140,21 +141,21 @@ abstract class CurlOpts * no cookies are loaded, but cookie handling is still enabled. * @var string */ - public $cookiefile; + public string $cookiefile; /** * The name of a file to save all internal cookies to when the handle * is closed, e.g. after a call to curl_close. * @var string */ - public $cookiejar; + public string $cookiejar; /** * A directory that holds multiple CA certificates. * Use this option alongside CURLOPT_SSL_VERIFYPEER. * @var string */ - public $capath; + public string $capath; /** * The name of a file holding one or more certificates @@ -162,7 +163,7 @@ abstract class CurlOpts * used in combination with CURLOPT_SSL_VERIFYPEER. * @var string */ - public $cainfo; + public string $cainfo; /** * The contents of the "Accept-Encoding: " header. This @@ -172,14 +173,14 @@ abstract class CurlOpts * encoding types is sent. * @var string */ - public $encoding; + public string $encoding; /** * The password required to use the CURLOPT_SSLKEY * or CURLOPT_SSH_PRIVATE_KEYFILE private key. * @var string */ - public $keypasswd; + public string $keypasswd; /** * A string containing 32 hexadecimal digits. The @@ -189,7 +190,7 @@ abstract class CurlOpts * This option is only for SCP and SFTP transfers. * @var string */ - public $ssh_host_public_key_md5; + public string $ssh_host_public_key_md5; /** * The file name for your public key. If not used, libcurl @@ -198,7 +199,7 @@ abstract class CurlOpts * directory if HOME is not set. * @var string */ - public $ssh_public_keyfile; + public string $ssh_public_keyfile; /** * The file name for your private key. If not used, libcurl @@ -208,67 +209,67 @@ abstract class CurlOpts * set the password with CURLOPT_KEYPASSWD. * @var string */ - public $ssh_private_keyfile; + public string $ssh_private_keyfile; /** * A list of ciphers to use for SSL. For example, RC4-SHA * and TLSv1 are valid cipher lists. * @var string */ - public $ssl_cipher_list; + public string $ssl_cipher_list; /** * The name of a file containing a PEM formatted certificate * @var string */ - public $sslcert; + public string $sslcert; /** * The password required to use the CURLOPT_SSLCERT certificate. * @var string */ - public $sslcertpasswd; + public string $sslcertpasswd; /** * The format of the certificate. Supported formats are * "PEM" (default), "DER", and "ENG" * @var string */ - public $sslcerttype; + public string $sslcerttype; /** * The identifier for the crypto engine of the private SSL * key specified in CURLOPT_SSLKEY. * @var string */ - public $sslengine; + public string $sslengine; /** * The identifier for the crypto engine used for * asymmetric crypto operations. * @var string */ - public $sslengine_default; + public string $sslengine_default; /** * The name of a file containing a private SSL key. * @var string */ - public $sslkey; + public string $sslkey; /** * The secret password needed to use the private * SSL key specified in CURLOPT_SSLKEY. * @var string */ - public $sslkeypasswd; + public string $sslkeypasswd; /** * The identifier for the CURLOPT_SSLVERSION * property. * @var integer */ - public $sslversion; + public int $sslversion; /** * The key type of the private SSL key specified in @@ -276,7 +277,7 @@ abstract class CurlOpts * (default), "DER", and "ENG". * @var string */ - public $sslkeytype; + public string $sslkeytype; /** * The KRB4 (Kerberos 4) security level. Any of the following @@ -287,79 +288,79 @@ abstract class CurlOpts * security only works with FTP transactions. * @var string */ - public $krb4level; + public string $krb4level; /** * The HTTP proxy to tunnel requests through. * @var string */ - public $proxy; + public string $proxy; /** * A username and password formatted as "[username]:[password]" * to use for the connection to the proxy. * @var string */ - public $proxyuserpwd; + public string $proxyuserpwd; /** * The contents of the "Referer: " header to be used - * in a HTTP request. + * in an HTTP request. * @var string */ - public $referer; + public string $referer; /** * The contents of the "User-Agent: " header to be used - * in a HTTP request. + * in an HTTP request. * @var string */ - public $useragent; + public string $useragent; /** * The URL to fetch. * @var string */ - public $url; + public string $url; /** * User and password in * format user=pass * @var string */ - public $userpwd; + public string $userpwd; /** * Main headers - * @var \OtherCode\Rest\Payloads\Headers + * @var Headers */ - public $httpheader; + public Headers $httpheader; /** * Array of 200 codes that will be * considered as success * @var array */ - public $http200aliases; + public array $http200aliases; /** * Array of ftp commands o perform * before the request * @var array */ - public $postquote; + public array $postquote; /** * Array of ftp commands o perform * after the request * @var array */ - public $quote; + public array $quote; /** * File path for log errors * @var string */ - public $stderr; + public string $stderr; -} \ No newline at end of file +} diff --git a/src/Core/Error.php b/src/Core/Error.php index 166338f..a355bf5 100644 --- a/src/Core/Error.php +++ b/src/Core/Error.php @@ -5,7 +5,6 @@ /** * Class Error * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Core */ class Error @@ -14,19 +13,19 @@ class Error * The last error code * @var int */ - public $code = 0; + public int $code = 0; /** * The last error message * @var string */ - public $message; + public string $message; /** - * @param $code - * @param $message + * @param int $code + * @param string $message */ - public function __construct($code = 0, $message = 'none') + public function __construct(int $code = 0, string $message = 'none') { $this->code = $code; $this->message = $message; @@ -34,10 +33,10 @@ public function __construct($code = 0, $message = 'none') /** * Return if an error exists - * @deprecated Will be removed in v2 * @return bool + * @deprecated Will be removed in v2 */ - public function hasError() + public function hasError(): bool { if ($this->code !== 0) { return true; @@ -49,8 +48,8 @@ public function hasError() * Return the object in string format * @return string */ - public function __toString() + public function __toString(): string { - return 'There was a connection error, code: ' . $this->code . ' ' . $this->message; + return 'There was a connection error, code: '.$this->code.' '.$this->message; } -} \ No newline at end of file +} diff --git a/src/Exceptions/ConfigurationException.php b/src/Exceptions/ConfigurationException.php index e1cbf24..f7e3356 100644 --- a/src/Exceptions/ConfigurationException.php +++ b/src/Exceptions/ConfigurationException.php @@ -2,13 +2,14 @@ namespace OtherCode\Rest\Exceptions; +use Exception; + /** * Class ConfigurationException * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Exceptions */ -class ConfigurationException extends \Exception +class ConfigurationException extends Exception { -} \ No newline at end of file +} diff --git a/src/Exceptions/ConnectionException.php b/src/Exceptions/ConnectionException.php index cae37e3..ca0df58 100644 --- a/src/Exceptions/ConnectionException.php +++ b/src/Exceptions/ConnectionException.php @@ -2,13 +2,14 @@ namespace OtherCode\Rest\Exceptions; +use Exception; + /** * Class ConfigurationException * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Exceptions */ -class ConnectionException extends \Exception +class ConnectionException extends Exception { -} \ No newline at end of file +} diff --git a/src/Exceptions/ModuleNotFoundException.php b/src/Exceptions/ModuleNotFoundException.php index 412ee83..8e5c515 100755 --- a/src/Exceptions/ModuleNotFoundException.php +++ b/src/Exceptions/ModuleNotFoundException.php @@ -2,13 +2,14 @@ namespace OtherCode\Rest\Exceptions; +use Exception; + /** * Class ModuleNotFoundException * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Exceptions */ -class ModuleNotFoundException extends \Exception +class ModuleNotFoundException extends Exception { -} \ No newline at end of file +} diff --git a/src/Exceptions/RestException.php b/src/Exceptions/RestException.php index 74c2c50..4feb3ab 100755 --- a/src/Exceptions/RestException.php +++ b/src/Exceptions/RestException.php @@ -2,13 +2,14 @@ namespace OtherCode\Rest\Exceptions; +use Exception; + /** * Class RestException * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Exceptions */ -class RestException extends \Exception +class RestException extends Exception { -} \ No newline at end of file +} diff --git a/src/Modules/BaseModule.php b/src/Modules/BaseModule.php index 7e42e9e..a45d69d 100755 --- a/src/Modules/BaseModule.php +++ b/src/Modules/BaseModule.php @@ -1,24 +1,25 @@ - - * @version 1.0 * @package OtherCode\Rest */ -abstract class BaseModule implements \OtherCode\Rest\Modules\ModuleInterface +abstract class BaseModule implements ModuleInterface { /** * Main data to work with - * @var \stdClass + * @var object */ - private $bindings; + private object $bindings; /** * Class constructor - * @param $bindings + * @param object $bindings */ - public function __construct($bindings) + public function __construct(object $bindings) { $this->bindings = $bindings; } @@ -27,7 +28,7 @@ public function __construct($bindings) * Return the processed data * @return object */ - public function output() + public function output(): object { return $this->bindings; } @@ -37,7 +38,7 @@ public function output() * @param $key string * @return mixed */ - public function __get($key) + public function __get(string $key) { if (isset($this->bindings->$key)) { return $this->bindings->$key; @@ -49,13 +50,12 @@ public function __get($key) * Provide an access set the linked data * @param $key string * @param $value mixed - * @return mixed + * @return void */ - public function __set($key, $value) + public function __set(string $key, $value) { if (isset($this->bindings->$key)) { $this->bindings->$key = $value; } } - -} \ No newline at end of file +} diff --git a/src/Modules/Decoders/BaseDecoder.php b/src/Modules/Decoders/BaseDecoder.php index a241adb..fb771c4 100755 --- a/src/Modules/Decoders/BaseDecoder.php +++ b/src/Modules/Decoders/BaseDecoder.php @@ -2,27 +2,30 @@ namespace OtherCode\Rest\Modules\Decoders; +use OtherCode\Rest\Core\Error; +use OtherCode\Rest\Modules\BaseModule; +use OtherCode\Rest\Payloads\Headers; + /** * Class BaseDecoder * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Modules\Decoders * * @property int $code * @property string $content_type * @property string $charset * @property string $body - * @property \OtherCode\Rest\Payloads\Headers $headers - * @property \OtherCode\Rest\Core\Error $error + * @property Headers $headers + * @property Error $error * @property array $metadata */ -abstract class BaseDecoder extends \OtherCode\Rest\Modules\BaseModule implements \OtherCode\Rest\Modules\Decoders\DecoderInterface +abstract class BaseDecoder extends BaseModule implements DecoderInterface { /** * The content type that trigger the decoder * @var string */ - protected $contentType = 'text/plain'; + protected string $contentType = 'text/plain'; /** * Run the main decode method @@ -31,11 +34,8 @@ public function run() { $body = $this->body; $content_type = $this->content_type; - if (!empty($body) && isset($content_type)) { - - if ($this->contentType == $content_type) { - $this->decode(); - } + if (!empty($body) && isset($content_type) && $this->contentType == $content_type) { + $this->decode(); } } -} \ No newline at end of file +} diff --git a/src/Modules/Decoders/DecoderInterface.php b/src/Modules/Decoders/DecoderInterface.php index 09f0877..1772867 100644 --- a/src/Modules/Decoders/DecoderInterface.php +++ b/src/Modules/Decoders/DecoderInterface.php @@ -5,10 +5,9 @@ /** * Interface DecoderInterface * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Modules\Decoders */ interface DecoderInterface { public function decode(); -} \ No newline at end of file +} diff --git a/src/Modules/Decoders/JSONDecoder.php b/src/Modules/Decoders/JSONDecoder.php index 1b89c2f..34fd50e 100755 --- a/src/Modules/Decoders/JSONDecoder.php +++ b/src/Modules/Decoders/JSONDecoder.php @@ -2,22 +2,24 @@ namespace OtherCode\Rest\Modules\Decoders; +use OtherCode\Rest\Exceptions\RestException; + /** * Class JSONDecoder * @author Unay Santisteban * @package OtherCode\Rest\Modules\Decoders */ -class JSONDecoder extends \OtherCode\Rest\Modules\Decoders\BaseDecoder +class JSONDecoder extends BaseDecoder { /** * The content type that trigger the decoder * @var string */ - protected $contentType = 'application/json'; + protected string $contentType = 'application/json'; /** * Decode the data of a request - * @throws \OtherCode\Rest\Exceptions\RestException + * @throws RestException */ public function decode() { @@ -27,7 +29,7 @@ public function decode() $errorMessage = json_last_error_msg(); if ($errorCode !== 0 && isset($errorMessage)) { - throw new \OtherCode\Rest\Exceptions\RestException($errorMessage, $errorCode); + throw new RestException($errorMessage, $errorCode); } } -} \ No newline at end of file +} diff --git a/src/Modules/Decoders/XMLDecoder.php b/src/Modules/Decoders/XMLDecoder.php index dbef422..540a9cb 100644 --- a/src/Modules/Decoders/XMLDecoder.php +++ b/src/Modules/Decoders/XMLDecoder.php @@ -1,30 +1,33 @@ - * @package OtherCode\Rest\Modules\Decoders */ -class XMLDecoder extends \OtherCode\Rest\Modules\Decoders\BaseDecoder +class XMLDecoder extends BaseDecoder { /** * The content type that trigger the decoder * @var string */ - protected $contentType = 'application/xml'; + protected string $contentType = 'application/xml'; /** * Decode the data of a request + * @throws RestException */ public function decode() { try { - - $this->body = new \SimpleXMLElement($this->body, LIBXML_NOWARNING); + $this->body = new SimpleXMLElement($this->body, LIBXML_NOWARNING); } catch (\Exception $e) { - - throw new \OtherCode\Rest\Exceptions\RestException($e->getMessage(), $e->getCode()); + throw new RestException($e->getMessage(), $e->getCode()); } } -} \ No newline at end of file +} diff --git a/src/Modules/Decoders/XMLRPCDecoder.php b/src/Modules/Decoders/XMLRPCDecoder.php index 5b0e6ce..fc87278 100644 --- a/src/Modules/Decoders/XMLRPCDecoder.php +++ b/src/Modules/Decoders/XMLRPCDecoder.php @@ -1,30 +1,33 @@ * @package OtherCode\Rest\Modules\Decoders */ -class XMLRPCDecoder extends \OtherCode\Rest\Modules\Decoders\BaseDecoder +class XMLRPCDecoder extends BaseDecoder { /** * The content type that trigger the decoder * @var string */ - protected $contentType = 'text/xml'; + protected string $contentType = 'text/xml'; /** * Decode the data of a request + * @throws RestException */ public function decode() { $response = xmlrpc_decode($this->body); if (is_array($response) && xmlrpc_is_fault($response)) { - throw new \OtherCode\Rest\Exceptions\RestException($response['faultString'], $response['faultCode']); + throw new RestException($response['faultString'], $response['faultCode']); } $this->body = $response; } -} \ No newline at end of file +} diff --git a/src/Modules/Encoders/BaseEncoder.php b/src/Modules/Encoders/BaseEncoder.php index 95d542e..27b7175 100644 --- a/src/Modules/Encoders/BaseEncoder.php +++ b/src/Modules/Encoders/BaseEncoder.php @@ -2,41 +2,42 @@ namespace OtherCode\Rest\Modules\Encoders; +use OtherCode\Rest\Exceptions\RestException; +use OtherCode\Rest\Modules\BaseModule; +use OtherCode\Rest\Payloads\Headers; + /** * Class BaseEncoder * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Modules\Encoders * * @property string $method * @property string $url - * @property \OtherCode\Rest\Payloads\Headers $headers + * @property Headers $headers * @property string $body */ -abstract class BaseEncoder extends \OtherCode\Rest\Modules\BaseModule implements \OtherCode\Rest\Modules\Encoders\EncoderInterface +abstract class BaseEncoder extends BaseModule implements EncoderInterface { /** * The content type that trigger the decoder - * @var string + * @var mixed */ - protected $methods = array('POST', 'PUT', 'PATCH'); + protected $methods = ['POST', 'PUT', 'PATCH']; /** * Run the main decode method + * @throws RestException */ public function run() { if (!is_array($this->methods)) { - throw new \OtherCode\Rest\Exceptions\RestException('The "methods" property MUST be an array.'); + throw new RestException('The "methods" property MUST be an array.'); } $body = $this->body; $method = $this->method; - if (!empty($body) && isset($method)) { - - if (in_array($this->method, $this->methods)) { - $this->encode(); - } + if (!empty($body) && isset($method) && in_array($this->method, $this->methods)) { + $this->encode(); } } -} \ No newline at end of file +} diff --git a/src/Modules/Encoders/EncoderInterface.php b/src/Modules/Encoders/EncoderInterface.php index 3013df5..c19b732 100644 --- a/src/Modules/Encoders/EncoderInterface.php +++ b/src/Modules/Encoders/EncoderInterface.php @@ -5,10 +5,9 @@ /** * Interface EncoderInterface * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Modules\Encoders */ interface EncoderInterface { public function encode(); -} \ No newline at end of file +} diff --git a/src/Modules/Encoders/JSONEncoder.php b/src/Modules/Encoders/JSONEncoder.php index 2c271f6..d5c1679 100644 --- a/src/Modules/Encoders/JSONEncoder.php +++ b/src/Modules/Encoders/JSONEncoder.php @@ -2,12 +2,14 @@ namespace OtherCode\Rest\Modules\Encoders; +use OtherCode\Rest\Exceptions\RestException; + /** * Class JSONEncoder * @author Unay Santisteban * @package OtherCode\Rest\Modules\Encoders */ -class JSONEncoder extends \OtherCode\Rest\Modules\Encoders\BaseEncoder +class JSONEncoder extends BaseEncoder { /** * Method @@ -17,7 +19,7 @@ class JSONEncoder extends \OtherCode\Rest\Modules\Encoders\BaseEncoder /** * create a xml rpc document based on the provided data. - * @throws \OtherCode\Rest\Exceptions\RestException + * @throws RestException */ public function encode() { @@ -28,7 +30,7 @@ public function encode() $errorMessage = json_last_error_msg(); if ($errorCode !== 0 && isset($errorMessage)) { - throw new \OtherCode\Rest\Exceptions\RestException($errorMessage, $errorCode); + throw new RestException($errorMessage, $errorCode); } } -} \ No newline at end of file +} diff --git a/src/Modules/Encoders/XMLRPCEncoder.php b/src/Modules/Encoders/XMLRPCEncoder.php index 56ba43e..42426e9 100644 --- a/src/Modules/Encoders/XMLRPCEncoder.php +++ b/src/Modules/Encoders/XMLRPCEncoder.php @@ -7,7 +7,7 @@ * @author Unay Santisteban * @package OtherCode\Rest\Modules\Encoders */ -class XMLRPCEncoder extends \OtherCode\Rest\Modules\Encoders\BaseEncoder +class XMLRPCEncoder extends BaseEncoder { /** * Method @@ -25,10 +25,9 @@ public function encode() if (isset($this->body->params)) { if (isset($this->body->methodName)) { $this->body = xmlrpc_encode_request($this->body->methodName, $this->body->params); - } else { $this->body = xmlrpc_encode($this->body->params); } } } -} \ No newline at end of file +} diff --git a/src/Modules/ModuleInterface.php b/src/Modules/ModuleInterface.php index ab64f7f..ae349d2 100644 --- a/src/Modules/ModuleInterface.php +++ b/src/Modules/ModuleInterface.php @@ -5,10 +5,9 @@ /** * Interface ModuleInterface * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Modules */ interface ModuleInterface { public function run(); -} \ No newline at end of file +} diff --git a/src/Payloads/Headers.php b/src/Payloads/Headers.php index 36c46f1..8442b59 100644 --- a/src/Payloads/Headers.php +++ b/src/Payloads/Headers.php @@ -2,17 +2,21 @@ namespace OtherCode\Rest\Payloads; +use ArrayAccess; +use ArrayIterator; +use Countable; +use IteratorAggregate; + /** * Class Headers * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest\Payloads */ -class Headers implements \ArrayAccess, \Countable, \IteratorAggregate +class Headers implements ArrayAccess, Countable, IteratorAggregate { /** * Class constructor - * @param string|array $headers + * @param string|array $headers */ public function __construct($headers = null) { @@ -30,23 +34,20 @@ public function __construct($headers = null) } } - /** - * Build the headers - */ - public function build() + public function build(): array { $headers = array(); foreach (get_object_vars($this) as $header => $value) { - $headers[] = $header . ": " . (string)$value; + $headers[] = "$header: $value"; } return $headers; } /** * Parse a header string into the object - * @param $headers + * @param string $headers */ - public function parse($headers) + public function parse(string $headers) { $lines = preg_split("/(\r|\n)+/", $headers, -1, PREG_SPLIT_NO_EMPTY); array_shift($lines); @@ -70,28 +71,29 @@ public function reset() /** * Return the iterator element - * @return mixed + * @return ArrayIterator */ - public function getIterator() + public function getIterator(): ArrayIterator { - return new \ArrayIterator($this); + return new ArrayIterator($this); } /** * Check if an offset exists - * @param string $offset + * @param mixed $offset * @return bool */ - public function offsetExists($offset) + public function offsetExists($offset): bool { return isset($this->{strtolower($offset)}); } /** * Return an offset - * @param string $offset + * @param mixed $offset * @return mixed */ + #[\ReturnTypeWillChange] public function offsetGet($offset) { if (isset($this->{$name = strtolower($offset)})) { @@ -102,9 +104,11 @@ public function offsetGet($offset) /** * Set an offset - * @param string $offset - * @param string $value + * @param mixed $offset + * @param mixed $value + * @return void */ + #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { $this->{strtolower($offset)} = $value; @@ -112,9 +116,10 @@ public function offsetSet($offset, $value) /** * Unset an offset - * @param string $offset + * @param mixed $offset + * @return void */ - public function offsetUnset($offset) + public function offsetUnset($offset): void { unset($this->{strtolower($offset)}); } @@ -123,8 +128,8 @@ public function offsetUnset($offset) * Return the number of properties * @return int */ - public function count() + public function count(): int { return count(get_object_vars($this)); } -} \ No newline at end of file +} diff --git a/src/Payloads/Request.php b/src/Payloads/Request.php index c257839..88a857a 100644 --- a/src/Payloads/Request.php +++ b/src/Payloads/Request.php @@ -36,13 +36,17 @@ class Request /** * Request constructor. - * @param string $method - * @param string $url - * @param array|object $body - * @param Headers|null $headers + * @param string $method + * @param string $url + * @param array|object $body + * @param Headers|null $headers */ - public function __construct($method = null, $url = null, $body = null, \OtherCode\Rest\Payloads\Headers $headers = null) - { + public function __construct( + $method = null, + $url = null, + $body = null, + \OtherCode\Rest\Payloads\Headers $headers = null + ) { $this->method = $method; $this->url = $url; $this->body = $body; @@ -52,7 +56,7 @@ public function __construct($method = null, $url = null, $body = null, \OtherCod /** * Set the headers - * @param Headers $headers + * @param Headers $headers */ public function setHeaders(\OtherCode\Rest\Payloads\Headers $headers = null) { @@ -65,7 +69,7 @@ public function setHeaders(\OtherCode\Rest\Payloads\Headers $headers = null) /** * Initialize a short chained call. - * @param string $uri + * @param string $uri * @return \OtherCode\Rest\Rest */ public static function call($uri) @@ -75,4 +79,4 @@ public static function call($uri) ))); } -} \ No newline at end of file +} diff --git a/src/Payloads/Response.php b/src/Payloads/Response.php index 960120f..686aedf 100644 --- a/src/Payloads/Response.php +++ b/src/Payloads/Response.php @@ -2,6 +2,8 @@ namespace OtherCode\Rest\Payloads; +use OtherCode\Rest\Core\Error; + /** * Class Response * @author Unay Santisteban @@ -15,50 +17,50 @@ class Response * Http status code * @var int */ - public $code; + public int $code; /** * The Content Type * @var string */ - public $content_type; + public string $content_type; /** * The Charset * @var string */ - public $charset; + public string $charset; /** * The response body - * @var string + * @var mixed */ public $body; /** * The response headers - * @var \OtherCode\Rest\Payloads\Headers + * @var Headers */ - public $headers; + public Headers $headers; /** * The last known error - * @var \OtherCode\Rest\Core\Error + * @var Error */ - public $error; + public Error $error; /** * Metadata array * @var array */ - public $metadata; + public array $metadata; /** - * @param null $response - * @param null $error - * @param null $metadata + * @param null $response + * @param Error|null $error + * @param null $metadata */ - public function __construct($response = null, $error = null, $metadata = null) + public function __construct($response = null, Error $error = null, $metadata = null) { if (isset($response)) { $this->parseResponse($response); @@ -67,7 +69,7 @@ public function __construct($response = null, $error = null, $metadata = null) if (isset($error)) { $this->setError($error); } else { - $this->setError(new \OtherCode\Rest\Core\Error()); + $this->setError(new Error()); } if (isset($metadata)) { @@ -88,8 +90,7 @@ public function parseResponse($response) $this->body = null; } - $this->headers = new \OtherCode\Rest\Payloads\Headers(array_pop($response)); - + $this->headers = new Headers(array_pop($response)); if (isset($this->headers['Content-Type'])) { $content_type = explode(';', $this->headers['Content-Type']); @@ -97,15 +98,17 @@ public function parseResponse($response) } if (!isset($this->charset)) { - $this->charset = substr($this->content_type, 5) === 'text/' ? 'iso-8859-1' : 'utf-8'; + $this->charset = substr($this->content_type, 5) === 'text/' + ? 'iso-8859-1' + : 'utf-8'; } } /** * Set the Metadata - * @param $metadata + * @param array $metadata */ - public function setMetadata($metadata) + public function setMetadata(array $metadata) { $this->code = $metadata['http_code']; $this->metadata = $metadata; @@ -113,10 +116,10 @@ public function setMetadata($metadata) /** * Set the Error - * @param $error + * @param Error $error */ - public function setError($error) + public function setError(Error $error) { $this->error = $error; } -} \ No newline at end of file +} diff --git a/src/Rest.php b/src/Rest.php index 4bada27..2c622bd 100755 --- a/src/Rest.php +++ b/src/Rest.php @@ -2,80 +2,98 @@ namespace OtherCode\Rest; +use InvalidArgumentException; +use OtherCode\Rest\Core\Core; +use OtherCode\Rest\Exceptions\ConnectionException; +use OtherCode\Rest\Exceptions\ModuleNotFoundException; +use OtherCode\Rest\Exceptions\RestException; +use OtherCode\Rest\Payloads\Response; + /** * Perform request to Rest API * @author Unay Santisteban - * @version 1.0 * @package OtherCode\Rest */ -class Rest extends \OtherCode\Rest\Core\Core +class Rest extends Core { /** - * @param string $url - * @return \OtherCode\Rest\Payloads\Response + * @param string $url + * @return Response + * @throws ConnectionException + * @throws RestException */ - public function get($url) + public function get(string $url): Response { return $this->call("GET", $url); } /** - * @param string $url - * @param mixed $body - * @return \OtherCode\Rest\Payloads\Response + * @param string $url + * @param mixed $body + * @return Response + * @throws ConnectionException + * @throws RestException */ - public function post($url, $body = null) + public function post(string $url, $body = null): Response { return $this->call("POST", $url, $body); } /** - * @param string $url - * @param mixed $body - * @return \OtherCode\Rest\Payloads\Response + * @param string $url + * @param mixed $body + * @return Response + * @throws ConnectionException + * @throws RestException */ - public function delete($url, $body = null) + public function delete(string $url, $body = null): Response { return $this->call("DELETE", $url, $body); } /** - * @param string $url - * @param mixed $body - * @return \OtherCode\Rest\Payloads\Response + * @param string $url + * @param mixed $body + * @return Response + * @throws ConnectionException + * @throws RestException */ - public function put($url, $body = null) + public function put(string $url, $body = null): Response { return $this->call("PUT", $url, $body); } /** - * @param string $url - * @param mixed $body - * @return \OtherCode\Rest\Payloads\Response + * @param string $url + * @param mixed $body + * @return Response + * @throws ConnectionException + * @throws RestException */ - public function patch($url, $body = null) + public function patch(string $url, $body = null): Response { return $this->call("PATCH", $url, $body); } /** - * @param $url - * @return \OtherCode\Rest\Payloads\Response + * @param string $url + * @return Response + * @throws ConnectionException + * @throws RestException */ - public function head($url) + public function head(string $url): Response { return $this->call('HEAD', $url); } /** * Add a single new header - * @param $header - * @param $value + * @param string $header + * @param mixed $value * @return $this */ - public function addHeader($header, $value) + public function addHeader(string $header, $value): Rest { $this->configuration->addHeader($header, $value); return $this; @@ -83,10 +101,10 @@ public function addHeader($header, $value) /** * Add a bunch of headers - * @param array $headers + * @param array $headers * @return $this */ - public function addHeaders(array $headers) + public function addHeaders(array $headers): Rest { foreach ($headers as $header => $value) { $this->configuration->addHeader($header, $value); @@ -96,10 +114,10 @@ public function addHeaders(array $headers) /** * Remove a header - * @param string $header + * @param string $header * @return $this */ - public function removeHeader($header) + public function removeHeader(string $header): Rest { $this->configuration->removeHeader($header); return $this; @@ -107,10 +125,10 @@ public function removeHeader($header) /** * Remove a set of headers - * @param array $headers + * @param array $headers * @return $this */ - public function removeHeaders(array $headers) + public function removeHeaders(array $headers): Rest { $this->configuration->removeHeaders($headers); return $this; @@ -118,58 +136,58 @@ public function removeHeaders(array $headers) /** * Set a new decoder instance - * @param string $name Decoder unique name - * @param string $decoder Decoder class name with namespace - * @throws \OtherCode\Rest\Exceptions\ModuleNotFoundException + * @param string $name Decoder unique name + * @param string|null $decoder Decoder class name with namespace * @return $this + * @throws ModuleNotFoundException */ - public function setDecoder($name, $decoder = null) + public function setDecoder(string $name, string $decoder = null): Rest { if (!isset($decoder)) { - $decoder = '\OtherCode\Rest\Modules\Decoders\\' . strtoupper($name) . 'Decoder'; + $decoder = '\OtherCode\Rest\Modules\Decoders\\'.strtoupper($name).'Decoder'; } - if (class_exists($decoder, true)) { + if (class_exists($decoder)) { $this->registerModule($name, new $decoder($this->response), 'after'); } else { - throw new \OtherCode\Rest\Exceptions\ModuleNotFoundException('Decoder ' . $name . ' not found!'); + throw new ModuleNotFoundException("Decoder $name not found!"); } return $this; } /** * Set a new encoder instance - * @param string $name Encoder unique name - * @param string $encoder Encoder class name with namespace - * @throws \OtherCode\Rest\Exceptions\ModuleNotFoundException + * @param string $name Encoder unique name + * @param string|null $encoder Encoder class name with namespace * @return $this + * @throws ModuleNotFoundException */ - public function setEncoder($name, $encoder = null) + public function setEncoder(string $name, string $encoder = null): Rest { if (!isset($encoder)) { - $encoder = '\OtherCode\Rest\Modules\Encoders\\' . strtoupper($name) . 'Encoder'; + $encoder = '\OtherCode\Rest\Modules\Encoders\\'.strtoupper($name).'Encoder'; } - if (class_exists($encoder, true)) { + if (class_exists($encoder)) { $this->registerModule($name, new $encoder($this->request), 'before'); } else { - throw new \OtherCode\Rest\Exceptions\ModuleNotFoundException('Encoder ' . $name . ' not found!'); + throw new ModuleNotFoundException('Encoder '.$name.' not found!'); } return $this; } /** * Set a new module instance - * @param string $name Module unique name - * @param string $module Module class name with namespace - * @param string $hook The name the hook - * @throws \InvalidArgumentException - * @throws \OtherCode\Rest\Exceptions\ModuleNotFoundException + * @param string $name Module unique name + * @param string $module Module class name with namespace + * @param string $hook The name the hook * @return $this + * @throws ModuleNotFoundException + * @throws InvalidArgumentException */ - public function setModule($name, $module, $hook = 'after') + public function setModule(string $name, string $module, string $hook = 'after'): Rest { - if (class_exists($module, true)) { + if (class_exists($module)) { switch ($hook) { case 'before': $param = $this->request; @@ -178,24 +196,24 @@ public function setModule($name, $module, $hook = 'after') $param = $this->response; break; default: - throw new \InvalidArgumentException("Invalid hook name!"); + throw new InvalidArgumentException("Invalid hook name!"); } $this->registerModule($name, new $module($param), $hook); } else { - throw new \OtherCode\Rest\Exceptions\ModuleNotFoundException('Module ' . $name . ' not found!'); + throw new ModuleNotFoundException('Module '.$name.' not found!'); } return $this; } /** * Unset a registered module or decoder - * @param string $moduleName - * @param string $hook + * @param string $moduleName + * @param string $hook * @return $this */ - public function unsetModule($moduleName, $hook = 'after') + public function unsetModule(string $moduleName, string $hook = 'after'): Rest { $this->unregisterModule($moduleName, $hook); return $this; } -} \ No newline at end of file +} diff --git a/tests/ConfigurationTest.php b/tests/ConfigurationTest.php index e6ea116..1758b4b 100644 --- a/tests/ConfigurationTest.php +++ b/tests/ConfigurationTest.php @@ -1,143 +1,86 @@ assertInstanceOf('\OtherCode\Rest\Core\Configuration', $configuration); - - $this->assertInternalType('array', $configuration->toArray()); - $this->assertCount(3, $configuration->toArray()); - } - - /** - * @return \OtherCode\Rest\Core\Configuration - */ - public function testInstantiationWithParams() - { - $configuration = new \OtherCode\Rest\Core\Configuration(array( - 'url' => 'http://jsonplaceholder.typicode.com/', - 'thisConfigurationIsNotAllowed' => 'Some invalid value', - 'httpheader' => array( - 'some_header1' => 'some_value1', - 'some_header2' => 'some_value2' - ) - )); - $this->assertInstanceOf('\OtherCode\Rest\Core\Configuration', $configuration); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $configuration->httpheader); - $this->assertCount(2, $configuration->httpheader); - $this->assertInternalType('array', $configuration->toArray()); - $this->assertCount(4, $configuration->toArray()); - - return $configuration; - } - - /** - * @depends testInstantiationWithParams - * @param \OtherCode\Rest\Core\Configuration $configuration - * @return \OtherCode\Rest\Core\Configuration - */ - public function testAddHeader(\OtherCode\Rest\Core\Configuration $configuration) - { - $configuration->addHeader('one_more_header', 'one_more_value'); - $this->assertCount(3, $configuration->httpheader); - - return $configuration; - } - - /** - * @depends testAddHeader - * @param \OtherCode\Rest\Core\Configuration $configuration - */ - public function testRemoveHeader(\OtherCode\Rest\Core\Configuration $configuration) - { - $configuration->removeHeader('one_more_header'); - $this->assertCount(2, $configuration->httpheader); - } - - /** - * @depends testInstantiationWithParams - * @param \OtherCode\Rest\Core\Configuration $configuration - * @return \OtherCode\Rest\Core\Configuration - */ - public function testAddHeaders(\OtherCode\Rest\Core\Configuration $configuration) - { - $configuration->addHeaders(array( - 'one_more_header' => 'one_more_value', - 'two_more_header' => 'two_more_value' - )); - $this->assertCount(4, $configuration->httpheader); - - return $configuration; - } - - /** - * @depends testAddHeaders - * @param \OtherCode\Rest\Core\Configuration $configuration - */ - public function testRemoveHeaders(\OtherCode\Rest\Core\Configuration $configuration) - { - $configuration->removeHeaders(array( - 'one_more_header', - 'two_more_header' - )); - $this->assertCount(2, $configuration->httpheader); - } - - /** - * @depends testInstantiationWithParams - * @param \OtherCode\Rest\Core\Configuration $configuration - */ - public function testBasicAuth(\OtherCode\Rest\Core\Configuration $configuration) - { - $configuration->basicAuth('username', 'password'); - $this->assertCount(5, $configuration->toArray()); - $this->assertEquals('username=password', $configuration->userpwd); - } - - /** - * @depends testInstantiationWithParams - * @param \OtherCode\Rest\Core\Configuration $configuration - */ - public function testSetSSLCertificate(\OtherCode\Rest\Core\Configuration $configuration) - { - $configuration->setSSLCertificate('/some/path/to/ssl.cert'); - $this->assertCount(6, $configuration->toArray()); - $this->assertEquals('/some/path/to/ssl.cert', $configuration->sslcert); - } - - /** - * @depends testInstantiationWithParams - * @param \OtherCode\Rest\Core\Configuration $configuration - */ - public function testSetCACertificatesCapath(\OtherCode\Rest\Core\Configuration $configuration) - { - $configuration->setCACertificates('/some/path/to/capath', 'capath'); - $this->assertCount(8, $configuration->toArray()); - $this->assertEquals('/some/path/to/capath', $configuration->capath); - } - - /** - * @depends testInstantiationWithParams - * @param \OtherCode\Rest\Core\Configuration $configuration - */ - public function testSetCACertificatesCainfo(\OtherCode\Rest\Core\Configuration $configuration) - { - $configuration->setCACertificates('/some/path/to/cainfo', 'cainfo'); - $this->assertCount(9, $configuration->toArray()); - $this->assertEquals('/some/path/to/cainfo', $configuration->cainfo); - } - - /** - * @depends testInstantiationWithParams - * @param \OtherCode\Rest\Core\Configuration $configuration - * @expectedException \OtherCode\Rest\Exceptions\RestException - */ - public function testWrongSetCACertificates(\OtherCode\Rest\Core\Configuration $configuration) - { - $configuration->setCACertificates('/some/path/to/wrong', 'wrong'); - $this->assertCount(8, $configuration->toArray()); - } -} \ No newline at end of file +use OtherCode\Rest\Core\Configuration; +use OtherCode\Rest\Exceptions\RestException; +use OtherCode\Rest\Payloads\Headers; + +test('basic instantiation', function () { + $configuration = new Configuration(); + expect($configuration)->toBeInstanceOf(Configuration::class); + expect($configuration->toArray())->toBeArray(); + expect($configuration->toArray())->toHaveCount(3); +}); + +test('instantiation with params', function () { + $configuration = new Configuration(array( + 'url' => 'http://jsonplaceholder.typicode.com/', + 'thisConfigurationIsNotAllowed' => 'Some invalid value', + 'httpheader' => array( + 'some_header1' => 'some_value1', + 'some_header2' => 'some_value2' + ) + )); + expect($configuration)->toBeInstanceOf(Configuration::class); + expect($configuration->httpheader)->toBeInstanceOf(Headers::class); + expect($configuration->httpheader)->toHaveCount(2); + expect($configuration->toArray())->toBeArray(); + expect($configuration->toArray())->toHaveCount(4); + return $configuration; +}); + +test('add header', function (Configuration $configuration) { + $configuration->addHeader('one_more_header', 'one_more_value'); + expect($configuration->httpheader)->toHaveCount(3); + return $configuration; +})->depends('instantiation with params'); + +test('remove header', function (Configuration $configuration) { + $configuration->removeHeader('one_more_header'); + expect($configuration->httpheader)->toHaveCount(2); +})->depends('add header'); + +test('add headers', function (Configuration $configuration) { + $configuration->addHeaders(array( + 'one_more_header' => 'one_more_value', + 'two_more_header' => 'two_more_value' + )); + expect($configuration->httpheader)->toHaveCount(4); + return $configuration; +})->depends('instantiation with params'); + +test('remove headers', function (Configuration $configuration) { + $configuration->removeHeaders(array( + 'one_more_header', + 'two_more_header' + )); + expect($configuration->httpheader)->toHaveCount(2); +})->depends('add headers'); + +test('basic auth', function (Configuration $configuration) { + $configuration->basicAuth('username', 'password'); + expect($configuration->toArray())->toHaveCount(5); + expect($configuration->userpwd)->toEqual('username=password'); +})->depends('instantiation with params'); + +test('set SSL certificate', function (Configuration $configuration) { + $configuration->setSSLCertificate('/some/path/to/ssl.cert'); + expect($configuration->toArray())->toHaveCount(6); + expect($configuration->sslcert)->toEqual('/some/path/to/ssl.cert'); +})->depends('instantiation with params'); + +test('set CA certificates capath', function (Configuration $configuration) { + $configuration->setCACertificates('/some/path/to/capath', 'capath'); + expect($configuration->toArray())->toHaveCount(8); + expect($configuration->capath)->toEqual('/some/path/to/capath'); +})->depends('instantiation with params'); + +test('set CA certificates cainfo', function (Configuration $configuration) { + $configuration->setCACertificates('/some/path/to/cainfo', 'cainfo'); + expect($configuration->toArray())->toHaveCount(9); + expect($configuration->cainfo)->toEqual('/some/path/to/cainfo'); +})->depends('instantiation with params'); + +test('wrong set CA certificates', function (Configuration $configuration) { + $configuration->setCACertificates('/some/path/to/wrong', 'wrong'); + expect($configuration->toArray())->toHaveCount(8); +})->throws(RestException::class)->depends('instantiation with params'); diff --git a/tests/DecodersTest.php b/tests/DecodersTest.php index d081d6c..998ed0f 100644 --- a/tests/DecodersTest.php +++ b/tests/DecodersTest.php @@ -1,147 +1,91 @@ configuration->url = "http://www.mocky.io"; - - $response = $api->get("/v2/59db36550f0000120402a66f"); - $this->assertInternalType('string', $response->body); - - return $api; - } - - /** - * @depends testJSonDecoderOFF - */ - public function testSetJSonDecoder(\OtherCode\Rest\Rest $api) - { - $this->assertInstanceOf('\OtherCode\Rest\Rest', $api->setDecoder("json")); - return $api; - } - - /** - * @depends testSetJSonDecoder - */ - public function testJSonDecoderON(\OtherCode\Rest\Rest $api) - { - $response = $api->get("/v2/59db36550f0000120402a66f"); - - $this->assertInternalType('object', $response->body); - $this->assertInstanceOf('\stdClass', $response->body); - } - - /** - * @depends testSetJSonDecoder - * @expectedException \OtherCode\Rest\Exceptions\RestException - */ - public function testJSonDecoderONFail(\OtherCode\Rest\Rest $api) - { - $api->get("/v2/59e3e2211100006602aabeac"); - } - - public function testXMLDecoderOFF() - { - $api = new OtherCode\Rest\Rest(); - $api->configuration->url = "http://www.mocky.io"; - - $response = $api->get("/v2/59db37720f0000220402a676"); - $this->assertInternalType('string', $response->body); - - return $api; - } - - /** - * @depends testXMLDecoderOFF - */ - public function testSetXMLDecoder(\OtherCode\Rest\Rest $api) - { - $this->assertInstanceOf('\OtherCode\Rest\Rest', $api->setDecoder("xml")); - return $api; - } - - /** - * @depends testSetXMLDecoder - */ - public function testXMLDecoderON(\OtherCode\Rest\Rest $api) - { - $response = $api->get("/v2/59db37720f0000220402a676"); - - $this->assertInternalType('object', $response->body); - $this->assertInstanceOf('\SimpleXMLElement', $response->body); - } - - /** - * @depends testSetXMLDecoder - * @expectedException \OtherCode\Rest\Exceptions\RestException - */ - public function testXMLDecoderONFail(\OtherCode\Rest\Rest $api) - { - $api->get("/v2/59e3de1e1100006302aabeaa"); - } - - /** - * @expectedException \OtherCode\Rest\Exceptions\ModuleNotFoundException - */ - public function testExceptionOnBadDecoder() - { - $api = new OtherCode\Rest\Rest(); - $api->setDecoder('non_existant_decoder'); - } - - public function testDecoderOn204Response() - { - $api = new OtherCode\Rest\Rest(); - $api->configuration->url = "http://www.mocky.io"; - $api->setDecoder("json"); - - $response = $api->get("/v2/59db36550f0000120402a66f"); - $this->assertInternalType('object', $response->body); - - $response = $api->get("/v2/59db35850f00000b0402a669"); - $this->assertNull($response->body); - } - - public function testXMLRPCDecoderOFF() - { - $api = new OtherCode\Rest\Rest(); - $api->configuration->url = "http://www.mocky.io"; - - $response = $api->get("/v2/59e3e9481100006b02aabec3"); - $this->assertInternalType('string', $response->body); - - return $api; - } - - /** - * @depends testXMLRPCDecoderOFF - */ - public function testSetXMLRPCDecoder(\OtherCode\Rest\Rest $api) - { - $this->assertInstanceOf('\OtherCode\Rest\Rest', $api->setDecoder("xmlrpc")); - return $api; - } - - /** - * @depends testSetXMLRPCDecoder - */ - public function testXMLRPCDecoderON(\OtherCode\Rest\Rest $api) - { - $response = $api->get("/v2/59e3e9481100006b02aabec3"); - - $this->assertInternalType('array', $response->body); - } - - /** - * @depends testSetXMLRPCDecoder - * @expectedException \OtherCode\Rest\Exceptions\RestException - */ - public function testXMLRPCDecoderONFail(\OtherCode\Rest\Rest $api) - { - $api->get("/v2/59e3ed1f1100005b01aabec5"); - } -} \ No newline at end of file +test('JSON decoder off', function () { + $api = new Rest(); + $api->configuration->url = "https://run.mocky.io"; + + $response = $api->get("/v3/150aee50-5361-46e1-b7ce-6c67f3985fe7"); + expect($response->body)->toBeString(); + + return $api; +}); + +test('set JSON decoder', function (Rest $api) { + expect($api->setDecoder("json"))->toBeInstanceOf(Rest::class); + return $api; +})->depends('JSON decoder off'); + +test('JSON decoder on', function (Rest $api) { + $response = $api->get("/v3/150aee50-5361-46e1-b7ce-6c67f3985fe7"); + + expect($response->body)->toBeObject(); + expect($response->body)->toBeInstanceOf('\stdClass'); +})->depends('set JSON decoder'); + +test('JSON decoder on fail', function (Rest $api) { + $api->get("/v3/c288e024-7c1c-4233-9c53-6f6af83df800"); +})->throws(RestException::class)->depends('set JSON decoder'); + +test('XML decoder off', function () { + $api = new Rest(); + $api->configuration->url = "https://run.mocky.io"; + + $response = $api->get("/v2/59db37720f0000220402a676"); + expect($response->body)->toBeString(); + + return $api; +}); + +test('set XML decoder', function (Rest $api) { + expect($api->setDecoder("xml"))->toBeInstanceOf(Rest::class); + return $api; +})->depends('XML decoder off'); + +test('XML decoder on', function (Rest $api) { + $response = $api->get("/v3/3939c8c3-46fe-423d-abb7-b57ac4eadb86"); + + expect($response->body)->toBeObject(); + expect($response->body)->toBeInstanceOf(SimpleXMLElement::class); +})->depends('set XML decoder'); + +test('exception on bad decoder', function () { + $api = new Rest(); + $api->setDecoder('non_existant_decoder'); +})->throws(ModuleNotFoundException::class); + +test('decoder on 204 response', function () { + $api = new Rest(); + $api->configuration->url = "https://run.mocky.io"; + $api->setDecoder("json"); + + $response = $api->get("/v3/150aee50-5361-46e1-b7ce-6c67f3985fe7"); + expect($response->body)->toBeObject(); + + $response = $api->get("/v3/a6f75a45-b2f1-4e7c-9ef7-851eff99fac1"); + expect($response->body)->toBeNull(); +}); + +test('XML-RPC decoder off', function () { + $api = new Rest(); + $api->configuration->url = "https://run.mocky.io"; + + $response = $api->get("/v3/35d914d0-0934-4abb-9f8f-7a656e425c1e"); + expect($response->body)->toBeString(); + + return $api; +}); + +test('set XML-RPC decoder', function (Rest $api) { + expect($api->setDecoder("xmlrpc"))->toBeInstanceOf(Rest::class); + return $api; +})->depends('XML-RPC decoder off'); + +test('XML-RPC decoder on', function (Rest $api) { + $response = $api->get("/v3/35d914d0-0934-4abb-9f8f-7a656e425c1e"); + + expect($response->body)->toBeArray(); +})->depends('set XML-RPC decoder'); diff --git a/tests/EncodersTest.php b/tests/EncodersTest.php index 8d1acaa..74b40ae 100644 --- a/tests/EncodersTest.php +++ b/tests/EncodersTest.php @@ -1,27 +1,19 @@ setEncoder('nonExistentEncoder'); +})->throws(ModuleNotFoundException::class); - /** - * @expectedException \OtherCode\Rest\Exceptions\ModuleNotFoundException - */ - public function testEncoderNotFound() - { - $api = new OtherCode\Rest\Rest(); - $api->setEncoder('nonExistentEncoder'); - } +test('decoder on wrong method', function () { + $api = new Rest(); + $api->configuration->url = "http://www.mocky.io"; - /** - * @expectedException \OtherCode\Rest\Exceptions\RestException - */ - public function testDecoderOnWrongMethod() - { - $api = new OtherCode\Rest\Rest(); - $api->configuration->url = "http://www.mocky.io"; - - $api->setEncoder('dummy', '\Tests\Modules\Encoders\DummyEncoder'); - $api->post("/v2/59db36550f0000120402a66f"); - } -} \ No newline at end of file + $api->setEncoder('dummy', DummyEncoder::class); + $api->post("/v2/59db36550f0000120402a66f"); +})->throws(RestException::class); diff --git a/tests/ErrorTest.php b/tests/ErrorTest.php index d8809c3..860d7fb 100644 --- a/tests/ErrorTest.php +++ b/tests/ErrorTest.php @@ -1,23 +1,19 @@ assertEquals(0, $error->code); - $this->assertEquals('none', $error->message); - $this->assertFalse($error->hasError()); - $this->assertInternalType('string', $error->__toString()); - } +test('instantiation default', function () { + $error = new Error(); + expect($error->code)->toEqual(0); + expect($error->message)->toEqual('none'); + expect($error->hasError())->toBeFalse(); + expect($error->__toString())->toBeString(); +}); - public function testInstantiationSample() - { - $error = new \OtherCode\Rest\Core\Error(500, "Something has exploded"); - $this->assertEquals(500, $error->code); - $this->assertEquals("Something has exploded", $error->message); - $this->assertTrue($error->hasError()); - $this->assertInternalType('string', $error->__toString()); - } -} \ No newline at end of file +test('instantiation sample', function () { + $error = new Error(500, "Something has exploded"); + expect($error->code)->toEqual(500); + expect($error->message)->toEqual("Something has exploded"); + expect($error->hasError())->toBeTrue(); + expect($error->__toString())->toBeString(); +}); diff --git a/tests/HeadersTest.php b/tests/HeadersTest.php index ad92938..164b681 100644 --- a/tests/HeadersTest.php +++ b/tests/HeadersTest.php @@ -1,12 +1,9 @@ assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $headers); - $this->assertCount(14, $headers); - } + $headers = new Headers($rawHeaders); + expect($headers)->toBeInstanceOf('\OtherCode\Rest\Payloads\Headers'); + expect($headers)->toHaveCount(14); +}); - public function testConstructWithArray() - { - $arrayHeaders = array( - 'some_header' => 'some_value', - 'other_header' => 'other_value' - ); +test('construct with array', function () { + $arrayHeaders = array( + 'some_header' => 'some_value', + 'other_header' => 'other_value' + ); - $headers = new \OtherCode\Rest\Payloads\Headers($arrayHeaders); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $headers); - $this->assertCount(2, $headers); + $headers = new Headers($arrayHeaders); + expect($headers)->toBeInstanceOf('\OtherCode\Rest\Payloads\Headers'); + expect($headers)->toHaveCount(2); - return $headers; - } + return $headers; +}); - /** - * @depends testConstructWithArray - */ - public function testBuildHeaders(\OtherCode\Rest\Payloads\Headers $headers) - { - $this->assertInternalType('array', $headers->build()); - $this->assertCount(2, $headers); - } +test('build headers', function (Headers $headers) { + expect($headers->build())->toBeArray(); + expect($headers)->toHaveCount(2); +})->depends('construct with array'); - public function testResetHeaders() - { - $rawHeaders = 'HTTP/1.1 200 OK +test('reset headers', function () { + $rawHeaders = 'HTTP/1.1 200 OK Server: Cowboy Connection: keep-alive X-Powered-By: Express @@ -68,27 +59,20 @@ public function testResetHeaders() Date: Mon, 07 Mar 2016 09:51:49 GMT Via: 1.1 vegur'; - $headers = new \OtherCode\Rest\Payloads\Headers($rawHeaders); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $headers); - $this->assertCount(14, $headers); - - $headers->reset(); - $this->assertCount(0, $headers); - } + $headers = new Headers($rawHeaders); + expect($headers)->toBeInstanceOf('\OtherCode\Rest\Payloads\Headers'); + expect($headers)->toHaveCount(14); - public function testGetArrayIterator() - { - $headers = new \OtherCode\Rest\Payloads\Headers(); - $this->assertInstanceOf('\ArrayIterator', $headers->getIterator()); - } + $headers->reset(); + expect($headers)->toHaveCount(0); +}); - /** - * @depends testConstructWithArray - */ - public function testGetValues(\OtherCode\Rest\Payloads\Headers $headers) - { - $this->assertNull($headers->offsetGet('nonExistantHeader')); - $this->assertEquals('some_value', $headers->offsetGet('some_header')); - } +test('get array iterator', function () { + $headers = new Headers(); + expect($headers->getIterator())->toBeInstanceOf('\ArrayIterator'); +}); -} \ No newline at end of file +test('get values', function (Headers $headers) { + expect($headers->offsetGet('nonExistantHeader'))->toBeNull(); + expect($headers->offsetGet('some_header'))->toEqual('some_value'); +})->depends('construct with array'); diff --git a/tests/Modules/Decoders/DummyDecoder.php b/tests/Modules/Decoders/DummyDecoder.php index f37a53b..64f5f25 100644 --- a/tests/Modules/Decoders/DummyDecoder.php +++ b/tests/Modules/Decoders/DummyDecoder.php @@ -5,7 +5,7 @@ class DummyDecoder extends \OtherCode\Rest\Modules\Decoders\BaseDecoder { - protected $contentType = 'application/json'; + protected string $contentType = 'application/json'; public function decode() { diff --git a/tests/Modules/Encoders/DummyEncoder.php b/tests/Modules/Encoders/DummyEncoder.php index 6be2648..ccc09c0 100644 --- a/tests/Modules/Encoders/DummyEncoder.php +++ b/tests/Modules/Encoders/DummyEncoder.php @@ -3,7 +3,9 @@ namespace Tests\Modules\Encoders; -class DummyEncoder extends \OtherCode\Rest\Modules\Encoders\BaseEncoder +use OtherCode\Rest\Modules\Encoders\BaseEncoder; + +class DummyEncoder extends BaseEncoder { protected $methods = 'POST'; diff --git a/tests/ModulesTest.php b/tests/ModulesTest.php index b715225..97efbbe 100644 --- a/tests/ModulesTest.php +++ b/tests/ModulesTest.php @@ -1,72 +1,59 @@ assertInternalType('array', $http->getModules()); - $this->assertCount(2, $http->getModules()); - - $this->assertCount(0, $http->getModules('before')); - $this->assertCount(0, $http->getModules('after')); - } - - public function testSetModule() - { - $http = new \OtherCode\Rest\Rest(); - - $http->setModule('dummy', '\Tests\Modules\Dummy', 'after'); - $this->assertCount(1, $http->getModules('after')); - - $http->unsetModule('dummy', 'after'); - $this->assertCount(0, $http->getModules('after')); - - $http->setModule('dummy', '\Tests\Modules\Dummy', 'before'); - $this->assertCount(1, $http->getModules('before')); - - $http->unsetModule('dummy', 'before'); - $this->assertCount(0, $http->getModules('before')); - } - - /** - * @expectedException \OtherCode\Rest\Exceptions\ModuleNotFoundException - */ - public function testSetModuleFailed() - { - $http = new \OtherCode\Rest\Rest(); - $http->setModule('dummy', '\Tests\Modules\DummyNotExists'); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testSetModuleInvalidHookName() - { - $http = new \OtherCode\Rest\Rest(); - $http->setModule('dummy', '\Tests\Modules\Dummy', 'notexisthook'); - } - - public function testCoreRegisterUnRegisterModule() - { - $core = new \Tests\Rest\CoreTester(); - - $this->assertTrue($core->returnRegisterModule('dummy', 'after')); - $this->assertFalse($core->returnRegisterModule('dummy', 'wrong')); - $this->assertFalse($core->returnRegisterModule('dummy', 'after')); - - $this->assertTrue($core->returnUnRegisterModule('dummy', 'after')); - $this->assertFalse($core->returnUnRegisterModule('dummy', 'wrong')); - $this->assertFalse($core->returnUnRegisterModule('dummy', 'after')); - } - - - public function testRunModuleOnResponse() - { - $dummy = new \Tests\Modules\Dummy(new \OtherCode\Rest\Payloads\Response()); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $dummy->output()); - $this->assertNull($dummy->run()); - } -} \ No newline at end of file +use OtherCode\Rest\Exceptions\ModuleNotFoundException; +use OtherCode\Rest\Payloads\Response; +use OtherCode\Rest\Rest; +use Tests\Modules\Dummy; +use Tests\Rest\CoreTester; +use Tests\Modules\DummyNotExist; + +test('get modules', function () { + $http = new Rest(); + expect($http->getModules())->toBeArray(); + expect($http->getModules())->toHaveCount(2); + expect($http->getModules('before'))->toHaveCount(0); + expect($http->getModules('after'))->toHaveCount(0); +}); + +test('set module', function () { + $http = new Rest(); + + $http->setModule('dummy', '\Tests\Modules\Dummy', 'after'); + expect($http->getModules('after'))->toHaveCount(1); + + $http->unsetModule('dummy', 'after'); + expect($http->getModules('after'))->toHaveCount(0); + + $http->setModule('dummy', '\Tests\Modules\Dummy', 'before'); + expect($http->getModules('before'))->toHaveCount(1); + + $http->unsetModule('dummy', 'before'); + expect($http->getModules('before'))->toHaveCount(0); +}); + +test('set module failed', function () { + $http = new Rest(); + $http->setModule('dummy', DummyNotExists::class); +})->throws(ModuleNotFoundException::class); + +test('set module invalid hook name', function () { + $http = new Rest(); + $http->setModule('dummy', Dummy::class, 'notexisthook'); +})->throws(InvalidArgumentException::class); + +test('core register un register module', function () { + $core = new CoreTester(); + + expect($core->returnRegisterModule('dummy', 'after'))->toBeTrue(); + expect($core->returnRegisterModule('dummy', 'wrong'))->toBeFalse(); + expect($core->returnRegisterModule('dummy', 'after'))->toBeFalse(); + expect($core->returnUnRegisterModule('dummy', 'after'))->toBeTrue(); + expect($core->returnUnRegisterModule('dummy', 'wrong'))->toBeFalse(); + expect($core->returnUnRegisterModule('dummy', 'after'))->toBeFalse(); +}); + +test('run module on response', function () { + $dummy = new Dummy(new Response()); + expect($dummy->output())->toBeInstanceOf(OtherCode\Rest\Payloads\Response::class); + expect($dummy->run())->toBeNull(); +}); diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..5949c61 --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,45 @@ +in('Feature'); + +/* +|-------------------------------------------------------------------------- +| Expectations +|-------------------------------------------------------------------------- +| +| When you're writing tests, you often need to check that values meet certain conditions. The +| "expect()" function gives you access to a set of "expectations" methods that you can use +| to assert different things. Of course, you may extend the Expectation API at any time. +| +*/ + +expect()->extend('toBeOne', function () { + return $this->toBe(1); +}); + +/* +|-------------------------------------------------------------------------- +| Functions +|-------------------------------------------------------------------------- +| +| While Pest is very powerful out-of-the-box, you may have some testing code specific to your +| project that you don't want to repeat in every file. Here you can also expose helpers as +| global functions to help you to reduce the number of lines of code in your test files. +| +*/ + +function something() +{ + // .. +} diff --git a/tests/QuickCallsTest.php b/tests/QuickCallsTest.php index 7327b92..eb20b41 100644 --- a/tests/QuickCallsTest.php +++ b/tests/QuickCallsTest.php @@ -1,114 +1,100 @@ setDecoder('json') - ->get('/posts/1'); - - $this->assertInstanceOf('OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - } - - public function testQuickPostJSON() - { - $response = \OtherCode\Rest\Payloads\Request::call('http://jsonplaceholder.typicode.com') - ->setEncoder('json') - ->post("/posts", array( - 'title' => 'foo', - 'body' => 'bar', - 'userId' => 1 - )); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - } - - public function testQuickPutJSON() - { - $response = \OtherCode\Rest\Payloads\Request::call('http://jsonplaceholder.typicode.com') - ->setEncoder('json') - ->put("/posts/1", array( - 'id' => 1, - 'title' => 'foo', - 'body' => 'bar', - 'userId' => 1 - )); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - - } - - public function testQuickPatch() - { - $response = \OtherCode\Rest\Payloads\Request::call('http://jsonplaceholder.typicode.com') - ->setEncoder('json') - ->patch("/posts/1", array( - 'body' => 'bar', - )); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - } - - public function testQuickDelete() - { - $response = \OtherCode\Rest\Payloads\Request::call('http://jsonplaceholder.typicode.com') - ->delete("/posts/1"); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - } - - public function testQuickHead() - { - $response = \OtherCode\Rest\Payloads\Request::call('http://jsonplaceholder.typicode.com') - ->head("/posts"); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - - $this->assertNull($response->body); - } - -} \ No newline at end of file +use OtherCode\Rest\Payloads\Request; +use OtherCode\Rest\Payloads\Response; +use OtherCode\Rest\Payloads\Headers; +use OtherCode\Rest\Core\Error; + +test('quick get JSON', function () { + $response = Request::call('http://jsonplaceholder.typicode.com') + ->setDecoder('json') + ->get('/posts/1'); + + expect($response)->toBeInstanceOf(Response::class); + expect($response->headers)->toBeInstanceOf(Headers::class); + expect($response->error)->toBeInstanceOf(Error::class); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +}); + +test('quick post JSON', function () { + $response = Request::call('http://jsonplaceholder.typicode.com') + ->setEncoder('json') + ->post("/posts", array( + 'title' => 'foo', + 'body' => 'bar', + 'userId' => 1 + )); + + expect($response)->toBeInstanceOf('\OtherCode\Rest\Payloads\Response'); + expect($response->headers)->toBeInstanceOf('\OtherCode\Rest\Payloads\Headers'); + expect($response->error)->toBeInstanceOf('\OtherCode\Rest\Core\Error'); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +}); + +test('quick put JSON', function () { + $response = Request::call('http://jsonplaceholder.typicode.com') + ->setEncoder('json') + ->put("/posts/1", array( + 'id' => 1, + 'title' => 'foo', + 'body' => 'bar', + 'userId' => 1 + )); + + expect($response)->toBeInstanceOf('\OtherCode\Rest\Payloads\Response'); + expect($response->headers)->toBeInstanceOf('\OtherCode\Rest\Payloads\Headers'); + expect($response->error)->toBeInstanceOf('\OtherCode\Rest\Core\Error'); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +}); + +test('quick patch', function () { + $response = Request::call('http://jsonplaceholder.typicode.com') + ->setEncoder('json') + ->patch("/posts/1", array( + 'body' => 'bar', + )); + + expect($response)->toBeInstanceOf('\OtherCode\Rest\Payloads\Response'); + expect($response->headers)->toBeInstanceOf('\OtherCode\Rest\Payloads\Headers'); + expect($response->error)->toBeInstanceOf('\OtherCode\Rest\Core\Error'); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +}); + +test('quick delete', function () { + $response = Request::call('http://jsonplaceholder.typicode.com') + ->delete("/posts/1"); + + expect($response)->toBeInstanceOf('\OtherCode\Rest\Payloads\Response'); + expect($response->headers)->toBeInstanceOf('\OtherCode\Rest\Payloads\Headers'); + expect($response->error)->toBeInstanceOf('\OtherCode\Rest\Core\Error'); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +}); + +test('quick head', function () { + $response = Request::call('http://jsonplaceholder.typicode.com') + ->head("/posts"); + + expect($response)->toBeInstanceOf('\OtherCode\Rest\Payloads\Response'); + expect($response->headers)->toBeInstanceOf('\OtherCode\Rest\Payloads\Headers'); + expect($response->error)->toBeInstanceOf('\OtherCode\Rest\Core\Error'); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); + expect($response->body)->toBeNull(); +}); diff --git a/tests/ResponseTest.php b/tests/ResponseTest.php index c0fe84c..e27c431 100644 --- a/tests/ResponseTest.php +++ b/tests/ResponseTest.php @@ -1 +1 @@ -assertEquals('application/json', $response->content_type); $this->assertEquals('utf-8', $response->charset); $this->assertEquals("{ \"userId\": 1, \"id\": 1, \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\", \"body\": \"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto\" }", $response->body); $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); $this->assertCount(17, $response->headers); } public function testInstantiationWithError() { $response = new \OtherCode\Rest\Payloads\Response(null, new \OtherCode\Rest\Core\Error(500, "Server Error")); $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); $this->assertEquals(500, $response->error->code); $this->assertEquals('Server Error', $response->error->message); } public function testInstantiationWithMetadata() { $response = new \OtherCode\Rest\Payloads\Response(null, null, array( 'http_code' => 200 )); $this->assertInternalType('array', $response->metadata); $this->assertCount(1, $response->metadata); $this->assertEquals(200, $response->metadata['http_code']); $this->assertEquals(200, $response->code); } } \ No newline at end of file +content_type)->toEqual('application/json'); expect($response->charset)->toEqual('utf-8'); expect($response->body)->toEqual("{ \"userId\": 1, \"id\": 1, \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\", \"body\": \"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto\" }"); expect($response->headers)->toBeInstanceOf('\OtherCode\Rest\Payloads\Headers'); expect($response->headers)->toHaveCount(17); }); test('instantiation with error', function () { $response = new Response(null, new Error(500, "Server Error")); expect($response->error)->toBeInstanceOf('\OtherCode\Rest\Core\Error'); expect($response->error->code)->toEqual(500); expect($response->error->message)->toEqual('Server Error'); }); test('instantiation with metadata', function () { $response = new Response(null, null, array( 'http_code' => 200 )); expect($response->metadata)->toBeArray(); expect($response->metadata)->toHaveCount(1); expect($response->metadata['http_code'])->toEqual(200); expect($response->code)->toEqual(200); }); \ No newline at end of file diff --git a/tests/Rest/CoreTester.php b/tests/Rest/CoreTester.php index aa344fb..affacfc 100644 --- a/tests/Rest/CoreTester.php +++ b/tests/Rest/CoreTester.php @@ -2,11 +2,13 @@ namespace Tests\Rest; +use OtherCode\Rest\Core\Core; + /** * Class CoreTester * @package Tests\Rest */ -class CoreTester extends \OtherCode\Rest\Core\Core +class CoreTester extends Core { public function returnCall($method, $url, $body = null) diff --git a/tests/RestTest.php b/tests/RestTest.php index ca73963..45dc16b 100644 --- a/tests/RestTest.php +++ b/tests/RestTest.php @@ -1,242 +1,175 @@ assertInstanceOf('\OtherCode\Rest\Rest', $api); - $this->assertInstanceOf('\OtherCode\Rest\Core\Configuration', $api->configuration); - - $api->configuration->url = "http://jsonplaceholder.typicode.com/"; - $api->configuration->timeout = 10; - - $this->assertInternalType('array', $api->configuration->toArray()); - - /** - * There are 3 options configured by default, so if we configure - * two we have a total of 5 - */ - $this->assertCount(5, $api->configuration->toArray()); +use OtherCode\Rest\Exceptions\ConnectionException; +use OtherCode\Rest\Exceptions\RestException; +use OtherCode\Rest\Payloads\Headers; +use OtherCode\Rest\Payloads\Request; +use OtherCode\Rest\Payloads\Response; +use OtherCode\Rest\Rest; +use OtherCode\Rest\Core\Configuration; +use OtherCode\Rest\Core\Error; +use Tests\Rest\CoreTester; - return $api; - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testInstantiationAndConfiguration - */ - public function testDirectConfiguration(\OtherCode\Rest\Rest $api) - { - $api->addHeader('some_header', "some_value"); - $this->assertCount(1, $api->configuration->httpheader); - - $api->addHeaders(array( - 'some_header_1' => 'some_value_1', - 'some_header_2' => 'some_value_2', - )); - $this->assertCount(3, $api->configuration->httpheader); - - $api->removeHeader('some_header'); - $this->assertCount(2, $api->configuration->httpheader); - - $api->removeHeaders(array( - 'some_header_1', - 'some_header_2', - )); - $this->assertCount(0, $api->configuration->httpheader); - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testInstantiationAndConfiguration - * @return \OtherCode\Rest\Rest - */ - public function testGetMethod(\OtherCode\Rest\Rest $api) - { - $response = $api->get("posts/1"); +test('instantiation and configuration', function () { + $api = new Rest(); - $this->assertInstanceOf('OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('OtherCode\Rest\Core\Error', $response->error); + expect($api)->toBeInstanceOf(Rest::class); + expect($api->configuration)->toBeInstanceOf(Configuration::class); - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); + $api->configuration->url = "http://jsonplaceholder.typicode.com/"; + $api->configuration->timeout = 10; - return $api; - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testInstantiationAndConfiguration - */ - public function testPostMethod(\OtherCode\Rest\Rest $api) - { - $response = $api->post("posts", json_encode(array( - 'title' => 'foo', - 'body' => 'bar', - 'userId' => 1 - ))); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testInstantiationAndConfiguration - */ - public function testPutMethod(\OtherCode\Rest\Rest $api) - { - $response = $api->put("posts/1", json_encode(array( - 'id' => 1, - 'title' => 'foo', - 'body' => 'bar', - 'userId' => 1 - ))); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testInstantiationAndConfiguration - */ - public function testPatchMethod(\OtherCode\Rest\Rest $api) - { - $response = $api->patch("posts/1", json_encode(array( - 'body' => 'bar', - ))); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testInstantiationAndConfiguration - */ - public function testDeleteMethod(\OtherCode\Rest\Rest $api) - { - $response = $api->delete("posts/1"); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testInstantiationAndConfiguration - */ - public function testHeadMethod(\OtherCode\Rest\Rest $api) - { - $response = $api->head("posts"); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - - $this->assertNull($response->body); - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testGetMethod - */ - public function testPayloads(\OtherCode\Rest\Rest $api) - { - $payloads = $api->getPayloads(); - - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Request', $payloads['request']); - $this->assertInstanceOf('\OtherCode\Rest\Payloads\Response', $payloads['response']); - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testGetMethod - */ - public function testMetadata(\OtherCode\Rest\Rest $api) - { - $this->assertInternalType('array', $api->getMetadata()); - } - - /** - * @depends testInstantiationAndConfiguration - */ - public function testGetError(\OtherCode\Rest\Rest $api) - { - $this->assertInstanceOf('\OtherCode\Rest\Core\Error', $api->getError()); - } - - /** - * @param \OtherCode\Rest\Rest $api - * @depends testInstantiationAndConfiguration - * @expectedException \OtherCode\Rest\Exceptions\ConnectionException - */ - public function testException(\OtherCode\Rest\Rest $api) - { - $api->configuration->url = "http://thisurlnotexists.com/"; - $api->get("posts/1"); - } + expect($api->configuration->toArray())->toBeArray(); /** - * @expectedException \OtherCode\Rest\Exceptions\RestException + * There are 3 options configured by default, so if we configure + * two we have a total of 5 */ - public function testCoreCallWrongVerb() - { - $core = new \Tests\Rest\CoreTester(); - $core->returnCall('wrong', 'http://jsonplaceholder.typicode.com/posts/1'); - } - - public function testGetRawCoreCall() - { - $core = new \Tests\Rest\CoreTester(); - $response = $core->returnCall('GET', 'http://jsonplaceholder.typicode.com/posts/1', 'param=value'); - - $this->assertInstanceOf('OtherCode\Rest\Payloads\Response', $response); - $this->assertInstanceOf('OtherCode\Rest\Payloads\Headers', $response->headers); - $this->assertInstanceOf('OtherCode\Rest\Core\Error', $response->error); - - $this->assertInternalType('array', $response->metadata); - $this->assertInternalType('int', $response->code); - $this->assertInternalType('string', $response->content_type); - $this->assertInternalType('string', $response->charset); - } - -} \ No newline at end of file + expect($api->configuration->toArray())->toHaveCount(5); + + return $api; +}); + +test('direct configuration', function (Rest $api) { + $api->addHeader('some_header', "some_value"); + expect($api->configuration->httpheader)->toHaveCount(1); + + $api->addHeaders(array( + 'some_header_1' => 'some_value_1', + 'some_header_2' => 'some_value_2', + )); + expect($api->configuration->httpheader)->toHaveCount(3); + + $api->removeHeader('some_header'); + expect($api->configuration->httpheader)->toHaveCount(2); + + $api->removeHeaders(array( + 'some_header_1', + 'some_header_2', + )); + expect($api->configuration->httpheader)->toHaveCount(0); +})->depends('instantiation and configuration'); + +test('get method', function (Rest $api) { + $response = $api->get("posts/1"); + + expect($response)->toBeInstanceOf(Response::class); + expect($response->headers)->toBeInstanceOf(Headers::class); + expect($response->error)->toBeInstanceOf(Error::class); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); + + return $api; +})->depends('instantiation and configuration'); + +test('post method', function (Rest $api) { + $response = $api->post("posts", json_encode(array( + 'title' => 'foo', + 'body' => 'bar', + 'userId' => 1 + ))); + + expect($response)->toBeInstanceOf(Response::class); + expect($response->headers)->toBeInstanceOf(Headers::class); + expect($response->error)->toBeInstanceOf(Error::class); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +})->depends('instantiation and configuration'); + +test('put method', function (Rest $api) { + $response = $api->put("posts/1", json_encode(array( + 'id' => 1, + 'title' => 'foo', + 'body' => 'bar', + 'userId' => 1 + ))); + + expect($response)->toBeInstanceOf(Response::class); + expect($response->headers)->toBeInstanceOf(Headers::class); + expect($response->error)->toBeInstanceOf(Error::class); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +})->depends('instantiation and configuration'); + +test('patch method', function (Rest $api) { + $response = $api->patch("posts/1", json_encode(array( + 'body' => 'bar', + ))); + + expect($response)->toBeInstanceOf(Response::class); + expect($response->headers)->toBeInstanceOf(Headers::class); + expect($response->error)->toBeInstanceOf(Error::class); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +})->depends('instantiation and configuration'); + +test('delete method', function (Rest $api) { + $response = $api->delete("posts/1"); + + expect($response)->toBeInstanceOf(Response::class); + expect($response->headers)->toBeInstanceOf(Headers::class); + expect($response->error)->toBeInstanceOf(Error::class); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +})->depends('instantiation and configuration'); + +test('head method', function (Rest $api) { + $response = $api->head("posts"); + + expect($response)->toBeInstanceOf(Response::class); + expect($response->headers)->toBeInstanceOf(Headers::class); + expect($response->error)->toBeInstanceOf(Error::class); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); + expect($response->body)->toBeNull(); +})->depends('instantiation and configuration'); + +test('payloads', function (Rest $api) { + $payloads = $api->getPayloads(); + + expect($payloads['request'])->toBeInstanceOf(Request::class); + expect($payloads['response'])->toBeInstanceOf(Response::class); +})->depends('get method'); + +test('metadata', function (Rest $api) { + expect($api->getMetadata())->toBeArray(); +})->depends('get method'); + +test('get error', function (Rest $api) { + expect($api->getError())->toBeInstanceOf(Error::class); +})->depends('instantiation and configuration'); + +test('exception', function (Rest $api) { + $api->configuration->url = "http://thisurlnotexists.com/"; + $api->get("posts/1"); +})->throws(ConnectionException::class)->depends('instantiation and configuration'); + +test('core call wrong verb', function () { + $core = new CoreTester(); + $core->returnCall('wrong', 'http://jsonplaceholder.typicode.com/posts/1'); +})->throws(RestException::class); + +test('get raw core call', function () { + $core = new CoreTester(); + $response = $core->returnCall('GET', 'http://jsonplaceholder.typicode.com/posts/1', 'param=value'); + + expect($response)->toBeInstanceOf(Response::class); + expect($response->headers)->toBeInstanceOf(Headers::class); + expect($response->error)->toBeInstanceOf(Error::class); + expect($response->metadata)->toBeArray(); + expect($response->code)->toBeInt(); + expect($response->content_type)->toBeString(); + expect($response->charset)->toBeString(); +});