diff --git a/.codacy.yml b/.codacy.yml new file mode 100644 index 0000000..ab4d072 --- /dev/null +++ b/.codacy.yml @@ -0,0 +1,3 @@ +--- +exclude_paths: + - "tests/**" diff --git a/.codeclimate.yml b/.codeclimate.yml deleted file mode 100644 index c6410a1..0000000 --- a/.codeclimate.yml +++ /dev/null @@ -1,11 +0,0 @@ -languages: - Ruby: false - JavaScript: false - PHP: true - Python: false -exclude_paths: - - "bin/*" - - "vendor/*" - - "features/*" - - "spec/*" - - "tests/*" diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..10ba54d --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,3 @@ +# Bulk formatting commits, ignored by `git blame` (git config blame.ignoreRevsFile .git-blame-ignore-revs). +# Apply PER-CS coding style +ec049c8404c0eb7f7d470f6781429133857bc6c8 diff --git a/.gitattributes b/.gitattributes index 93ae856..66e6d58 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,8 +1,9 @@ +/.github export-ignore /tests export-ignore /.gitattributes export-ignore /.gitignore export-ignore -/.travis.yml export-ignore +/.git-blame-ignore-revs export-ignore +/.php-cs-fixer.dist.php export-ignore /phpunit.xml export-ignore /README.md export-ignore -/.codeclimate.yml export-ignore -/.scrutinizer.yml export-ignore +/.codacy.yml export-ignore diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5a98fda..b3dd88b 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,8 +1,12 @@ version: 2 updates: -- package-ecosystem: composer - directory: "/" - schedule: - interval: daily - time: "04:00" - open-pull-requests-limit: 10 + - package-ecosystem: composer + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 + + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..752dae7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +on: + push: + branches: [develop, master] + pull_request: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + tests: + name: Tests (PHP ${{ matrix.php }}, ${{ matrix.dependencies }} deps) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ['8.3', '8.4', '8.5'] + dependencies: [highest] + include: + - php: '8.3' + dependencies: lowest + steps: + - uses: actions/checkout@v5 + + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + + - uses: ramsey/composer-install@v3 + with: + dependency-versions: ${{ matrix.dependencies }} + + - run: vendor/bin/phpunit + + coding-style: + name: Coding style + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + coverage: none + + - uses: ramsey/composer-install@v3 + + - run: vendor/bin/php-cs-fixer fix --dry-run --diff diff --git a/.gitignore b/.gitignore index 8133e6a..b6b5df8 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ composer.lock .htaccess bin build +.phpunit.cache +.php-cs-fixer.cache +tests/urlMap.cache diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..0f7ca39 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,10 @@ +in([__DIR__ . '/src', __DIR__ . '/tests']); + +return (new PhpCsFixer\Config()) + ->setRules([ + '@PER-CS' => true, + ]) + ->setFinder($finder); diff --git a/.scrutinizer.yml b/.scrutinizer.yml deleted file mode 100644 index 13f4b98..0000000 --- a/.scrutinizer.yml +++ /dev/null @@ -1,41 +0,0 @@ -imports: - - php - -filter: - excluded_paths: - - 'bin/*' - - 'vendor/*' - - 'features/*' - - 'spec/*' - - 'tests/*' - -before_commands: - - rm -rf vendor composer.lock - - composer self-update - - composer install --prefer-source --dev --optimize-autoloader --no-interaction - -tools: - php_sim: true - php_cpd: false - - # PHP Code Sniffer - php_code_sniffer: - config: - standard: PSR2 - - sensiolabs_security_checker: true - - -build: - dependencies: - before: - - 'pecl install SPL_Types' - environment: - timezone: 'UTC' - tests: - override: - - - command: 'phpunit --coverage-clover=`pwd`/coverage.xml' - coverage: - file: 'coverage.xml' - format: 'php-clover' diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index cbfa596..0000000 --- a/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ -language: php -env: - global: - - secure: dprB6lKW9M9qUP11JTKEG3eSQ+1kd4vjo2TYWqXRWEDvYSXAnMaddJqs05caQipSn/OtXGQow1oQyiM0Do39lA3vN24jOrEnky4GpNlPsEupg+7j7sWWkjmOvEE1R5TxZFzn/4qZ/ABrE6VTkXHA38HzuPPmbW95TFIR5LwsSQg= - - secure: DV1aEdppPpM36FnZwHu4eAya2YdIwhkC957HLq+AjR8kRY/x7J1/qDlpaTRSqwRQDGR+5DX4VfxRX6hImG/zUcoy/DNSYXpls0T8QzbPAktCJXj3iYbCKCLUdvnDhINWB/5pv0UUrphkwZwWPuQjnD2lzew4wITH1rNDf+jVB5k= -sudo: false -cache: - directories: - - vendor - - "$HOME/.composer/cache" -matrix: - include: - - php: 7.0 - - php: 7.1 - - php: 7.2 - - php: 7.3 - - php: 7.4 - allow_failures: - - php: 7.4 - fast_finish: true -before_install: -- composer self-update -- composer config -g github-oauth.github.com $GITHUB_COMPOSER_TOKEN -install: -- composer install --prefer-dist --no-interaction --optimize-autoloader -script: -- vendor/bin/phpunit --exclude-group no-travis -after_script: -- vendor/bin/test-reporter diff --git a/README.md b/README.md index 4cccfdc..a5b0ce1 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,28 @@ # RestServer.php -[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/jk/RestServer/badges/quality-score.png?s=f73d03bf31d39ae6d8e6717e59fb37ee9f070a2e)](https://scrutinizer-ci.com/g/jk/RestServer/) -[![Code Coverage](https://scrutinizer-ci.com/g/jk/RestServer/badges/coverage.png?s=04bcecf088febc189f3e7f876802def3bd7a5e16)](https://scrutinizer-ci.com/g/jk/RestServer/) +[![CI](https://github.com/jk/RestServer/actions/workflows/ci.yml/badge.svg?branch=develop)](https://github.com/jk/RestServer/actions/workflows/ci.yml) [![Latest Stable Version](https://poser.pugx.org/jk/restserver/v/stable.svg)](https://packagist.org/packages/jk/restserver) [![License](https://poser.pugx.org/jk/restserver/license.svg)](https://packagist.org/packages/jk/restserver) [![Total Downloads](https://poser.pugx.org/jk/restserver/downloads.svg)](https://packagist.org/packages/jk/restserver) -[![SensioLabsInsight](https://insight.sensiolabs.com/projects/efa0c47d-3ffa-4fc8-b456-18d2edd29851/mini.png)](https://insight.sensiolabs.com/projects/efa0c47d-3ffa-4fc8-b456-18d2edd29851) [![Documentation Status](https://readthedocs.org/projects/restserver/badge/?version=develop)](https://readthedocs.org/projects/restserver/?badge=develop) -| Master branch | Develop branch | -| :---: | :---: | -[![Master Build Status](https://travis-ci.org/jk/RestServer.svg?branch=master)](https://travis-ci.org/jk/RestServer)|[![Develop Build Status](https://travis-ci.org/jk/RestServer.svg?branch=develop)](https://travis-ci.org/jk/RestServer) +A PHP REST server for providing a very light-weight REST API. Very easy to set +up and get going. Independent from other libraries and frameworks. Supports +HTTP authentication. -A PHP REST server for providing a very light-weight REST API. Very easy to set up and get going. Independent from other libraries and frameworks. Supports HTTP authentication. Supports AMF data if the Zend Framework is present for Flash clients. +As of [Classification of HTTP-based APIs][classification] this implementation +should be considered as an HTTP based type II type of an API. So it is not an +academic version of a real RESTful API, but this is by intention, so it's easy +to understand and install. -As of [Classification of HTTP-based APIs](https://algermissen.io/classification_of_http_apis.html) this implementation should be considered as an HTTP based type II type of an API. So it is not an academic version of a real RESTful API, but this is by intention, so it's easy to understand and install. +[classification]: https://algermissen.io/classification_of_http_apis.html + +## Development + +Requires PHP 8.3 or newer. + +```sh +composer install +composer test # run the PHPUnit test suite +composer cs # check coding style (PER-CS) +composer cs-fix # fix coding style +``` diff --git a/composer.json b/composer.json index 9ae1e5d..8647724 100644 --- a/composer.json +++ b/composer.json @@ -3,27 +3,36 @@ "type": "library", "description": "A PHP REST server for providing a very light-weight REST API without aweful routing configuration", "require": { - "php": "^5.6|~7|~8", + "php": "^8.3", "ext-json": "*", "ext-pcre": "*", "ext-reflection": "*" }, "require-dev": { - "phpunit/phpunit": "~4|~0", - "mockery/mockery": ">=0.9.3", - "fabpot/php-cs-fixer": "~1|~0", - "squizlabs/php_codesniffer": "~2|~0", - "codeclimate/php-test-reporter": "dev-master" + "phpunit/phpunit": "^12.0", + "friendsofphp/php-cs-fixer": "^3.64" }, "suggest": { "ext-simplexml": "*" }, "autoload": { - "psr-0": { - "JK\\RestServer\\": "src/", + "psr-4": { + "JK\\RestServer\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { "JK\\RestServer\\Tests\\": "tests/" } }, + "scripts": { + "test": "phpunit", + "cs": "php-cs-fixer fix --dry-run --diff", + "cs-fix": "php-cs-fixer fix" + }, + "config": { + "sort-packages": true + }, "homepage": "https://github.com/jk/RestServer", "license": "MIT", "authors": [ @@ -35,7 +44,7 @@ } ], "support": { - "issues": "https://github.com/jk/restserver/issues", - "wiki": "https://github.com/jk/restserver/wiki" + "issues": "https://github.com/jk/RestServer/issues", + "wiki": "https://github.com/jk/RestServer/wiki" } } diff --git a/phpunit.xml b/phpunit.xml index f312d08..f862eeb 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,17 +1,12 @@ - - + tests @@ -22,14 +17,9 @@ disabled - - - + + src - - - - - - + + diff --git a/sami_config.php b/sami_config.php deleted file mode 100644 index cf7a35b..0000000 --- a/sami_config.php +++ /dev/null @@ -1,28 +0,0 @@ -files() - ->name('*.php') - ->in($dir); - -$versions = GitVersionCollection::create($dir) - ->addFromTags(function ($version) { - return preg_match('/^v?\d+\.\d+\.\d+$/', $version); - }) - ->add('master', 'production') - ->add('develop', 'development'); - -$options = array( - 'title' => 'jk/restserver API', - 'versions' => $versions, - 'build_dir' => __DIR__ . '/build/sami/%version%', - 'cache_dir' => __DIR__ . '/build/sami_cache/%version%', - 'default_opened_level' => 2, -); - -return new Sami($iterator, $options); diff --git a/src/JK/RestServer/DocBlockParser.php b/src/DocBlockParser.php similarity index 95% rename from src/JK/RestServer/DocBlockParser.php rename to src/DocBlockParser.php index 2c09c80..3b4c9e7 100644 --- a/src/JK/RestServer/DocBlockParser.php +++ b/src/DocBlockParser.php @@ -1,4 +1,5 @@ getDocComment(); - $keys_as_array = array('url'); + $keys_as_array = ['url']; /** * The following RegExpr captures @annotation. It must start with an @ symbol following by a word of one or more * charaters. Optionally followed by a space or a tab and a string. And all these annotations must end in * a proper new line (\n, \r\n etc.) to seperate the findings. */ if (preg_match_all('/@(\w+)([ \t](.*?))?(?:\n|\r)+/', $doc_comment_string, $matches, PREG_SET_ORDER)) { - $keys = array(); + $keys = []; foreach ($matches as $match) { if (in_array($match[1], $keys_as_array)) { $keys[$match[1]][] = $match[3]; diff --git a/src/JK/RestServer/Format.php b/src/Format.php similarity index 90% rename from src/JK/RestServer/Format.php rename to src/Format.php index 4e912d7..58d7a20 100644 --- a/src/JK/RestServer/Format.php +++ b/src/Format.php @@ -1,4 +1,5 @@ self::PLAIN, 'txt' => self::PLAIN, 'html' => self::HTML, 'json' => self::JSON, 'jsonp' => self::JSONP, 'xml' => self::XML, - ); + ]; /** * Get the MIME type for a known format abbreviation diff --git a/src/JK/RestServer/HeaderManager.php b/src/HeaderManager.php similarity index 98% rename from src/JK/RestServer/HeaderManager.php rename to src/HeaderManager.php index 376d50a..ce1b732 100644 --- a/src/JK/RestServer/HeaderManager.php +++ b/src/HeaderManager.php @@ -1,4 +1,5 @@ 'Continue', self::OK => 'OK', self::CREATED => 'Created', @@ -127,7 +127,7 @@ final class HttpStatusCodes self::INTERNAL_SERVER_ERROR => 'Internal Server Error', self::NOT_IMPLEMENTED => 'Not Implemented', self::SERVICE_UNAVAILABLE => 'Service Unavailable', - ); + ]; public function __construct() { diff --git a/src/InputDataTransformationMode.php b/src/InputDataTransformationMode.php new file mode 100644 index 0000000..bb99907 --- /dev/null +++ b/src/InputDataTransformationMode.php @@ -0,0 +1,10 @@ +getClientAcceptedLanguages() as $language => $quality) { foreach ($this->supported_langauges as $supported) { if (strcasecmp($supported, $language) == 0) { - $negotiated_langauges[] = array($language, $quality); + $negotiated_langauges[] = [$language, $quality]; } } } @@ -84,7 +85,7 @@ private function negotiateLanguages() public function getClientAcceptedLanguages() { if ($this->client_accepted_languages === null) { - return array(); + return []; } return $this->client_accepted_languages; diff --git a/src/JK/RestServer/Mode.php b/src/Mode.php similarity index 73% rename from src/JK/RestServer/Mode.php rename to src/Mode.php index 170ccd6..79ec5a5 100644 --- a/src/JK/RestServer/Mode.php +++ b/src/Mode.php @@ -1,10 +1,11 @@ apcCacheSuffix = crc32(__DIR__); if (php_sapi_name() !== 'cli') { - $this->root = ltrim(dirname($_SERVER['SCRIPT_NAME']).DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR); + $this->root = ltrim(dirname($_SERVER['SCRIPT_NAME']) . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR); } else { $this->root = '/'; } @@ -112,16 +113,16 @@ public function __destruct() { if ($this->mode == Mode::PRODUCTION && !$this->cached) { if (function_exists('apc_store')) { - apc_store('urlMap_'.$this->apcCacheSuffix, $this->map); + apc_store('urlMap_' . $this->apcCacheSuffix, $this->map); } else { - file_put_contents($this->cacheDir.DIRECTORY_SEPARATOR.'urlMap.cache', serialize($this->map)); + file_put_contents($this->cacheDir . DIRECTORY_SEPARATOR . 'urlMap.cache', serialize($this->map)); } } } public function refreshCache() { - $this->map = array(); + $this->map = []; $this->cached = false; } @@ -191,11 +192,11 @@ public function handle() $language = new Language( $this->supported_languages, $this->default_language, - $accept_language_header + $accept_language_header, ); $params = $this->injectLanguageIntoMethodParameters($language, $obj, $method, $params); - $result = call_user_func_array(array($obj, $method), $params); + $result = call_user_func_array([$obj, $method], $params); $this->automaticContentLanguageHeaderDispatch($language); @@ -224,7 +225,7 @@ public function handle() protected function handleCorsPreflightRequest() { // Automatic CORS preflight response - $existing_verbs = array(); + $existing_verbs = []; foreach (HttpMethods::getAllMethods() as $http_verb) { if (isset($this->map[$http_verb])) { $urls = $this->map[$http_verb]; @@ -257,8 +258,10 @@ protected function handleCorsPreflightRequest() $this->header_manager->addHeader('Access-Control-Allow-Methods', join($comma_devider, $existing_verbs)); $this->header_manager->addHeader('Access-Control-Max-Age', intval($this->cors_max_age)); if (count($this->cors_allowed_headers) > 0) { - $this->header_manager->addHeader('Access-Control-Allow-Headers', - join($comma_devider, $this->cors_allowed_headers)); + $this->header_manager->addHeader( + 'Access-Control-Allow-Headers', + join($comma_devider, $this->cors_allowed_headers), + ); } $this->sendData(''); @@ -323,12 +326,12 @@ public function handleError($status_code, $error_message = null) $message = $description; } - $output = array( - 'error' => array( + $output = [ + 'error' => [ 'code' => $status_code, - 'message' => $message - ) - ); + 'message' => $message, + ], + ]; $this->setStatus($status_code); $this->sendData($output); @@ -344,9 +347,9 @@ protected function loadCache() if ($this->mode == Mode::PRODUCTION) { if (function_exists('apc_fetch')) { - $map = apc_fetch('urlMap_'.$this->apcCacheSuffix); - } elseif (file_exists($this->cacheDir.DIRECTORY_SEPARATOR.'urlMap.cache')) { - $map = unserialize(file_get_contents($this->cacheDir.DIRECTORY_SEPARATOR.'urlMap.cache')); + $map = apc_fetch('urlMap_' . $this->apcCacheSuffix); + } elseif (file_exists($this->cacheDir . DIRECTORY_SEPARATOR . 'urlMap.cache')) { + $map = unserialize(file_get_contents($this->cacheDir . DIRECTORY_SEPARATOR . 'urlMap.cache')); } if (isset($map) && is_array($map)) { $this->map = $map; @@ -354,9 +357,9 @@ protected function loadCache() } } else { if (function_exists('apc_delete')) { - apc_delete('urlMap_'.$this->apcCacheSuffix); + apc_delete('urlMap_' . $this->apcCacheSuffix); } else { - @unlink($this->cacheDir.DIRECTORY_SEPARATOR.'urlMap.cache'); + @unlink($this->cacheDir . DIRECTORY_SEPARATOR . 'urlMap.cache'); } } } @@ -367,8 +370,7 @@ protected function findUrl() return null; } - if (isset($this->map[$this->getMethod()])) - { + if (isset($this->map[$this->getMethod()])) { $urls = $this->map[$this->getMethod()]; } else { return null; @@ -401,7 +403,7 @@ protected function generateMap($class, $basePath) if (isset($reflection)) { $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC); } else { - $methods = array(); + $methods = []; } /** @var ReflectionMethod $method */ @@ -409,12 +411,12 @@ protected function generateMap($class, $basePath) $doc = $method->getDocComment(); $all_http_verbs_joined_by_pipes = implode('|', HttpMethods::getAllMethods()); - if (preg_match_all('/@url[ \t]+('. $all_http_verbs_joined_by_pipes .')[ \t]+\/?(\S*)/s', $doc, $matches, PREG_SET_ORDER)) { + if (preg_match_all('/@url[ \t]+(' . $all_http_verbs_joined_by_pipes . ')[ \t]+\/?(\S*)/s', $doc, $matches, PREG_SET_ORDER)) { $params = $method->getParameters(); foreach ($matches as $match) { $httpMethod = $match[1]; - $url = $this->root.$basePath.$match[2]; + $url = $this->root . $basePath . $match[2]; // quick fix for running on windows $url = str_replace('\\', '/', $url); @@ -536,7 +538,7 @@ public function getData() $components = preg_split('/\;\s*/', $_SERVER['CONTENT_TYPE']); if (in_array('application/x-www-form-urlencoded', $components)) { $a = explode('&', $data); - $output = array(); + $output = []; foreach ($a as $entry) { if (strpos($entry, '=') > 0) { $tmp = explode('=', $entry); @@ -552,7 +554,7 @@ public function getData() } else { throw new RestException( HttpStatusCodes::INTERNAL_SERVER_ERROR, - 'Content-Type "'.$_SERVER['CONTENT_TYPE'].'" not supported' + 'Content-Type "' . $_SERVER['CONTENT_TYPE'] . '" not supported', ); } } else { @@ -575,8 +577,8 @@ public function sendData($data) $this->header_manager->addHeader('Content-Type', $this->getFormat()); if ($this->getFormat() == Format::XML) { - $output = ''."\n"; - $output .= "".Utilities::arrayToXml($data).''; + $output = '' . "\n"; + $output .= "" . Utilities::arrayToXml($data) . ''; $data = $output; unset($output); } else { @@ -584,7 +586,7 @@ public function sendData($data) if ($this->getFormat() == Format::JSONP) { if (isset($_GET['callback']) && preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/', $_GET['callback'])) { - $data = $_GET['callback'].'('.$data.')'; + $data = $_GET['callback'] . '(' . $data . ')'; } else { throw new RestException(HttpStatusCodes::BAD_REQUEST, 'No callback given.'); } @@ -805,7 +807,7 @@ protected function matchRequestUriWithMap($request_uri, $url_from_map) return $matches; } - return array(); + return []; } /** @@ -820,8 +822,8 @@ protected function parseUrlFromMap($matches, $call) { $original_method_parameters_with_default_values = $call[2]; - $params = array(); - $params_from_request_uri = array(); + $params = []; + $params_from_request_uri = []; if (isset($original_method_parameters_with_default_values['data'])) { $params[$original_method_parameters_with_default_values['data']] = $this->data; } diff --git a/src/JK/RestServer/Utilities.php b/src/Utilities.php similarity index 94% rename from src/JK/RestServer/Utilities.php rename to src/Utilities.php index ba35b18..f7332aa 100644 --- a/src/JK/RestServer/Utilities.php +++ b/src/Utilities.php @@ -1,6 +1,5 @@ $accept) { $parts = explode(';q=', trim($accept)); $type = $parts[0]; $quality = isset($parts[1]) ? floatval($parts[1]) : 1; - $tmp_accept_list[] = array('type' => $type, 'quality' => $quality); + $tmp_accept_list[] = ['type' => $type, 'quality' => $quality]; } // Attention: $acceptList has to be decorated since all PHP sorting functions aren't stable // for more information a deeper explamentation of the issue, have a look here: // @see http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php/17365409#17365409 array_walk($tmp_accept_list, function (&$element, $index) { - $element = array($element, $index); // decorate + $element = [$element, $index]; // decorate }); usort($tmp_accept_list, function ($a, $b) { // $a[0] and $b[0] contain the primary sort key @@ -58,7 +57,7 @@ public static function sortByPriority($accept) $element = $element[0]; }); - $output = array(); + $output = []; foreach ($tmp_accept_list as $accept_entry) { $type = $accept_entry['type']; $quality = $accept_entry['quality']; @@ -113,7 +112,7 @@ public static function arrayToObject($data) */ $self_name = 'self::' . __FUNCTION__; - return (object)array_map($self_name, $data); + return (object) array_map($self_name, $data); } else { // Return object return $data; @@ -177,7 +176,7 @@ public static function getPositionsOfParameterWithTypeHint($obj, $method, $type_ $reflection_method = $reflection_class->getMethod($method); $reflection_parameters = $reflection_method->getParameters(); - $positions = array(); + $positions = []; /** @var ReflectionParameter $parameter */ foreach ($reflection_parameters as $parameter) { diff --git a/tests/Bootstrap.php b/tests/Bootstrap.php index 1e4a1e0..e2ee415 100644 --- a/tests/Bootstrap.php +++ b/tests/Bootstrap.php @@ -1,17 +1,10 @@ reflection_method_with_doc_keys = $reflection_class->getMethod('methodWithVariousDocBlockKeys'); $this->reflection_method_without_doc_keys = $reflection_class->getMethod('methodWithoutDocBlockKeys'); } - public function tearDown() + protected function tearDown(): void { unset($this->reflection_method_with_doc_keys); unset($this->reflection_method_without_doc_keys); } - /** - * @covers ::getDocKeys() - */ public function testGetDocKeysKeyValue() { $result = DocBlockParser::getDocKeys($this->reflection_method_with_doc_keys); @@ -45,20 +41,14 @@ public function testGetDocKeysKeyValue() $this->assertEquals('bool', $result['return']); } - /** - * @covers ::getDocKeys() - */ public function testGetDocKeysUrlKeysAsArray() { $result = DocBlockParser::getDocKeys($this->reflection_method_with_doc_keys); $this->assertArrayHasKey('url', $result); - $this->assertInternalType('array', $result['url']); + $this->assertIsArray($result['url']); } - /** - * @covers ::getDocKeys() - */ public function testGetDocKeysFlag() { $result = DocBlockParser::getDocKeys($this->reflection_method_with_doc_keys); @@ -67,9 +57,6 @@ public function testGetDocKeysFlag() $this->assertTrue($result['flag']); } - /** - * @covers ::getDocKeys() - */ public function testGetDocKeysWithoutAnyKeys() { $result = DocBlockParser::getDocKeys($this->reflection_method_without_doc_keys); diff --git a/tests/JK/RestServer/Tests/DummyTest.php b/tests/DummyTest.php similarity index 64% rename from tests/JK/RestServer/Tests/DummyTest.php rename to tests/DummyTest.php index 8876308..b58bd16 100644 --- a/tests/JK/RestServer/Tests/DummyTest.php +++ b/tests/DummyTest.php @@ -1,11 +1,11 @@ assertTrue(true); diff --git a/tests/JK/RestServer/Tests/Fixtures/Controller/TestApiController.php b/tests/Fixtures/Controller/TestApiController.php similarity index 93% rename from tests/JK/RestServer/Tests/Fixtures/Controller/TestApiController.php rename to tests/Fixtures/Controller/TestApiController.php index a14cc70..1270635 100644 --- a/tests/JK/RestServer/Tests/Fixtures/Controller/TestApiController.php +++ b/tests/Fixtures/Controller/TestApiController.php @@ -1,6 +1,6 @@ $param1, 'param2' => $param2); + return ['param1' => $param1, 'param2' => $param2]; } /** @@ -25,7 +25,7 @@ public function unorderd($param1 = 'default_value_1', $param2 = 'default_value_2 */ public function methodWithoutDefaultParamets($param1) { - return array('param1' => $param1); + return ['param1' => $param1]; } /** @@ -95,10 +95,10 @@ public function methodWithSeveralVerbsAndGetParamsTestPreflight() */ public function wrongParameterOrder($string, $first_id = 23, $second_id = 42) { - return array( + return [ 'string' => $string, 'first_id' => $first_id, - 'second_id' => $second_id - ); + 'second_id' => $second_id, + ]; } } diff --git a/tests/JK/RestServer/Tests/FormatTest.php b/tests/FormatTest.php similarity index 65% rename from tests/JK/RestServer/Tests/FormatTest.php rename to tests/FormatTest.php index 6afe1c1..d6d26f5 100644 --- a/tests/JK/RestServer/Tests/FormatTest.php +++ b/tests/FormatTest.php @@ -1,18 +1,17 @@ assertEquals(Format::JSON, $result); } - /** - * @covers JK\RestServer\Format::getMimeTypeFromFormatAbbreviation - */ public function testGetMimeTypeFromFormatNonExistentAbbreviation() { $result = Format::getMimeTypeFromFormatAbbreviation('non-existent'); @@ -30,9 +26,6 @@ public function testGetMimeTypeFromFormatNonExistentAbbreviation() $this->assertFalse($result); } - /** - * @covers JK\RestServer\Format::isMimeTypeSupported - */ public function testIsMimeTypeSupported() { $result = Format::isMimeTypeSupported('application/json'); @@ -40,9 +33,6 @@ public function testIsMimeTypeSupported() $this->assertTrue($result); } - /** - * @covers JK\RestServer\Format::isMimeTypeSupported - */ public function testIsMimeTypeNotSupported() { $result = Format::isMimeTypeSupported('non/existent'); diff --git a/tests/JK/RestServer/Tests/HeaderManagerTest.php b/tests/HeaderManagerTest.php similarity index 74% rename from tests/JK/RestServer/Tests/HeaderManagerTest.php rename to tests/HeaderManagerTest.php index dade498..a1073f9 100644 --- a/tests/JK/RestServer/Tests/HeaderManagerTest.php +++ b/tests/HeaderManagerTest.php @@ -1,39 +1,31 @@ sut = new HeaderManager(); } - /** - * @coversNothing - */ - public function tearDown() + protected function tearDown(): void { unset($this->sut); } - /** - * @covers ::addHeader() - */ public function testAddHeader() { $name = 'Content-Type'; @@ -45,9 +37,6 @@ public function testAddHeader() $this->assertEquals($value, $result); } - /** - * @covers ::getHeader() - */ public function testGetHeaderForAlreadyAddedHeader() { $name = 'Content-Type'; @@ -59,9 +48,6 @@ public function testGetHeaderForAlreadyAddedHeader() $this->assertEquals($value, $result); } - /** - * @covers ::getHeader() - */ public function testGetHeaderNonExistingHeader() { $result = $this->sut->getHeader('non-existing'); @@ -69,24 +55,18 @@ public function testGetHeaderNonExistingHeader() $this->assertNull($result); } - /** - * @covers ::addHeaders() - */ public function testAddHeaders() { - $headers = array( + $headers = [ 'Header1' => 'Value1', - 'Header2' => 'Value2' - ); + 'Header2' => 'Value2', + ]; $this->sut->addHeaders($headers); $this->assertEquals($this->sut->getHeader('Header1'), $headers['Header1']); $this->assertEquals($this->sut->getHeader('Header2'), $headers['Header2']); } - /** - * @covers ::setStatusHeader() - */ public function testSetStatusHeader() { $this->sut->setStatusHeader('404 Not Found', 'HTTP/2'); @@ -94,9 +74,6 @@ public function testSetStatusHeader() $this->assertEquals('HTTP/2 404 Not Found', $this->sut->getStatusHeader()); } - /** - * @covers ::setStatusHeader() - */ public function testSetStatusHeaderWithoutProtocol() { $this->sut->setStatusHeader('404 Not Found'); @@ -104,19 +81,11 @@ public function testSetStatusHeaderWithoutProtocol() $this->assertEquals('HTTP/1.1 404 Not Found', $this->sut->getStatusHeader()); } - /** - * @covers ::__construct() - * @covers ::getStatusHeader() - */ public function testGetStatusHeaderDefaultValue() { $this->assertEquals('HTTP/1.1 200 OK', $this->sut->getStatusHeader()); } - /** - * @covers ::__construct() - * @covers ::setStatusHeader() - */ public function testSetStatusHeaderDefaultValueViaServerProtocol() { $_SERVER['SERVER_PROTOCOL'] = 'HTTP/2'; @@ -125,9 +94,6 @@ public function testSetStatusHeaderDefaultValueViaServerProtocol() $this->assertEquals('HTTP/2 200 OK', $header_manager->getStatusHeader()); } - /** - * @covers ::headerExists() - */ public function testHeaderExists() { $name = 'Content-Type'; @@ -139,9 +105,6 @@ public function testHeaderExists() $this->assertTrue($result); } - /** - * @covers ::removeHeader() - */ public function testRemoveHeader() { $name = 'Content-Type'; @@ -155,10 +118,7 @@ public function testRemoveHeader() $this->assertFalse($this->sut->headerExists($name)); } - /** - * @runInSeparateProcess - * @covers ::sendAllHeaders() - */ + #[RunInSeparateProcess] public function testSendAllHeaders() { if (!extension_loaded('xdebug')) { @@ -167,14 +127,12 @@ public function testSendAllHeaders() $this->sut->addHeader('Content-Type', 'application/json'); - $this->sut->setStatusHeader('404 Not Found'); $this->sut->sendAllHeaders(); // BC: http_response_code() only exists in PHP 5.4+ - if (function_exists('http_response_code')) - { + if (function_exists('http_response_code')) { $this->assertEquals(404, http_response_code()); } diff --git a/tests/JK/RestServer/Tests/HttpMethodsTest.php b/tests/HttpMethodsTest.php similarity index 55% rename from tests/JK/RestServer/Tests/HttpMethodsTest.php rename to tests/HttpMethodsTest.php index 86150ad..b46ba82 100644 --- a/tests/JK/RestServer/Tests/HttpMethodsTest.php +++ b/tests/HttpMethodsTest.php @@ -1,24 +1,22 @@ assertContains($http_method_expected, $result, - 'HTTP method ' . $http_method_expected . ' is not present in getAllMethods()'); + $this->assertContains( + $http_method_expected, + $result, + 'HTTP method ' . $http_method_expected . ' is not present in getAllMethods()', + ); } } - /** - * @covers ::getMethodsWhereRequestBodyIsAllowed() - */ public function testGetMethodsWhereRequestBodyIsAllowed() { $result = HttpMethods::getMethodsWhereRequestBodyIsAllowed(); - $http_methods_expected = array( + $http_methods_expected = [ HttpMethods::POST, - HttpMethods::PUT - ); + HttpMethods::PUT, + ]; foreach ($http_methods_expected as $http_method_expected) { - $this->assertContains($http_method_expected, $result, - 'HTTP method ' . $http_method_expected . ' is not present in getAllMethods()'); + $this->assertContains( + $http_method_expected, + $result, + 'HTTP method ' . $http_method_expected . ' is not present in getAllMethods()', + ); } } } diff --git a/tests/JK/RestServer/Tests/HttpStatusCodesTest.php b/tests/HttpStatusCodesTest.php similarity index 51% rename from tests/JK/RestServer/Tests/HttpStatusCodesTest.php rename to tests/HttpStatusCodesTest.php index 37f6399..e8519f9 100644 --- a/tests/JK/RestServer/Tests/HttpStatusCodesTest.php +++ b/tests/HttpStatusCodesTest.php @@ -1,29 +1,25 @@ expectException(\Exception::class); + $this->expectExceptionMessage('HttpStatusCodes class can not be instantiatiated.'); + new HttpStatusCodes(); } - /** - * @covers ::getDescription() - */ public function testGetDescription() { $result = HttpStatusCodes::getDescription(404); @@ -31,9 +27,6 @@ public function testGetDescription() $this->assertEquals('Not Found', $result); } - /** - * @covers ::getDescription() - */ public function testGetDescriptionForUnknownCode() { $result = HttpStatusCodes::getDescription(-1); diff --git a/tests/JK/RestServer/Tests/LanguageTest.php b/tests/LanguageTest.php similarity index 80% rename from tests/JK/RestServer/Tests/LanguageTest.php rename to tests/LanguageTest.php index 1dc4713..1946149 100644 --- a/tests/JK/RestServer/Tests/LanguageTest.php +++ b/tests/LanguageTest.php @@ -1,19 +1,18 @@ getPreferedLanguage(); - $this->assertInternalType('string', $result); + $this->assertIsString($result); $this->assertEquals('de', $result); } public function testGetPreferedLanguageWithAnyMatches() { - $supported_languages = array(); + $supported_languages = []; $default_langauge = 'fr'; $accepted_languages_string = 'de'; $language = new Language($supported_languages, $default_langauge, $accepted_languages_string); $result = $language->getPreferedLanguage(); - $this->assertInternalType('string', $result); + $this->assertIsString($result); $this->assertEquals($default_langauge, $result); } public function testGetDefaultLanguage() { - $supported_languages = array(); + $supported_languages = []; $default_langauge = 'de'; $accepted_languages_string = ''; $language = new Language($supported_languages, $default_langauge, $accepted_languages_string); $result = $language->getDefaultLanguage(); - $this->assertInternalType('string', $result); + $this->assertIsString($result); $this->assertEquals($default_langauge, $result); } public function testGetSupportedLanguages() { - $supported_languages = array('de-de', 'de', 'en'); + $supported_languages = ['de-de', 'de', 'en']; $default_langauge = 'de'; $accepted_languages_string = ''; $language = new Language($supported_languages, $default_langauge, $accepted_languages_string); $result = $language->getSupportedLangauges(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); for ($i = 0; $i < count($supported_languages); $i++) { $expected_language = $supported_languages[$i]; $actual_language = $result[$i]; @@ -74,14 +73,14 @@ public function testGetSupportedLanguages() public function testGetClientAcceptedLanguages() { - $supported_languages = array(); + $supported_languages = []; $default_langauge = 'de'; $accepted_languages_string = 'fr,en'; $language = new Language($supported_languages, $default_langauge, $accepted_languages_string); $result = $language->getClientAcceptedLanguages(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(2, $result); $this->assertArrayHasKey('en', $result); $this->assertArrayHasKey('fr', $result); @@ -89,14 +88,14 @@ public function testGetClientAcceptedLanguages() public function testGetClientAcceptedLanguagesWithEmptyString() { - $supported_languages = array(); + $supported_languages = []; $default_langauge = 'de'; $accepted_languages_string = null; $language = new Language($supported_languages, $default_langauge, $accepted_languages_string); $result = $language->getClientAcceptedLanguages(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(0, $result); } @@ -106,7 +105,7 @@ public function testNegotiatedLanguages() $result = $language->getNegotiatedLangauges(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(2, $result); $this->assertCount(2, $result[0]); $this->assertEquals('de', $result[0][0]); diff --git a/tests/JK/RestServer/Tests/RestExceptionTest.php b/tests/RestExceptionTest.php similarity index 67% rename from tests/JK/RestServer/Tests/RestExceptionTest.php rename to tests/RestExceptionTest.php index 7e1a3a0..a737aef 100644 --- a/tests/JK/RestServer/Tests/RestExceptionTest.php +++ b/tests/RestExceptionTest.php @@ -1,19 +1,22 @@ expectException(RestException::class); + $this->expectExceptionMessage('Something went wrong'); + throw new RestException(400, 'Something went wrong'); } @@ -23,8 +26,7 @@ public function testRestExceptionHasACode() $message = 'Something went wrong'; try { throw new RestException($code, $message); - } - catch (RestException $e) { + } catch (RestException $e) { $this->assertEquals($code, $e->getCode()); $this->assertEquals($message, $e->getMessage()); return; diff --git a/tests/JK/RestServer/Tests/RestServerTest.php b/tests/RestServerTest.php similarity index 72% rename from tests/JK/RestServer/Tests/RestServerTest.php rename to tests/RestServerTest.php index ddcc0ff..82e546c 100644 --- a/tests/JK/RestServer/Tests/RestServerTest.php +++ b/tests/RestServerTest.php @@ -1,8 +1,12 @@ sut = new RestServer(); -// $this->sut->setDefaultFormat(Format::PLAIN); + // $this->sut->setDefaultFormat(Format::PLAIN); // @codeCoverageIgnoreEnd unset($_SERVER['HTTP_ACCEPT']); @@ -33,14 +33,15 @@ public function setUp() unset($_SERVER['CONTENT_TYPE']); } - public function tearDown() + protected function tearDown(): void { + // Destructing the server in production mode persists the URL map to disk. Remove it, so + // a (possibly empty) map from one test doesn't leak into the routing of another test. unset($this->sut); + gc_collect_cycles(); + @unlink(__DIR__ . DIRECTORY_SEPARATOR . 'urlMap.cache'); } - /** - * @covers ::__construct - */ public function testConstructor() { $result = new RestServer(); @@ -49,9 +50,6 @@ public function testConstructor() $this->assertEquals(Mode::PRODUCTION, $result->mode); } - /** - * @covers ::__construct - */ public function testConstructorInDebugMode() { $result = new RestServer(Mode::DEBUG); @@ -60,9 +58,6 @@ public function testConstructorInDebugMode() $this->assertEquals(Mode::DEBUG, $result->mode); } - /** - * @covers ::__construct - */ public function testConstructorInProductionMode() { $result = new RestServer(Mode::PRODUCTION); @@ -71,9 +66,6 @@ public function testConstructorInProductionMode() $this->assertEquals(Mode::PRODUCTION, $result->mode); } - /** - * @covers ::__construct - */ public function testConstructorInNonExistentMode() { $result = new RestServer('non-existent'); @@ -82,21 +74,18 @@ public function testConstructorInNonExistentMode() $this->assertEquals(Mode::PRODUCTION, $result->mode); } - public function requestUriProvider() + public static function requestUriProvider(): array { - return array( - array('/controller/action.format', Format::JSON), - array('/controller/action', Format::JSON), - array('/controller/action.html', Format::HTML), - array('/controller/action.json', Format::JSON), - array('/controller/action.xml', Format::XML) - ); + return [ + ['/controller/action.format', Format::JSON], + ['/controller/action', Format::JSON], + ['/controller/action.html', Format::HTML], + ['/controller/action.json', Format::JSON], + ['/controller/action.xml', Format::XML], + ]; } - /** - * @dataProvider requestUriProvider - * @covers ::getFormat - */ + #[DataProvider('requestUriProvider')] public function testGetFormat($request_uri, $format) { $_SERVER['REQUEST_URI'] = $request_uri; @@ -105,11 +94,7 @@ public function testGetFormat($request_uri, $format) $this->assertEquals($format, $result); } - /** - * @regression - * @dataProvider keyValueBodyProvider - * @covers ::getData - */ + #[DataProvider('keyValueBodyProvider')] public function testGetDataWithEmptyContentType($array_input_data) { $mock = $this->mockGetRawHttpRequestBody(json_encode($array_input_data)); @@ -118,7 +103,7 @@ public function testGetDataWithEmptyContentType($array_input_data) try { $result = $mock->getData(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(count($array_input_data), $result); foreach ($array_input_data as $key => $value) { $this->assertArrayHasKey($key, $result); @@ -131,34 +116,38 @@ public function testGetDataWithEmptyContentType($array_input_data) /** * @param string $text_input_data - * @return \Mockery\MockInterface|\JK\RestServer\RestServer + * @return RestServer Server returning $text_input_data as raw HTTP request body */ protected function mockGetRawHttpRequestBody($text_input_data) { - $mock = \Mockery::mock('JK\RestServer\RestServer[getRawHttpRequestBody]'); - $mock->shouldReceive('getRawHttpRequestBody')->withNoArgs()->andReturn($text_input_data); + return new class ($text_input_data) extends RestServer { + public function __construct(private string $raw_body) + { + parent::__construct(); + } - return $mock; + public function getRawHttpRequestBody() + { + return $this->raw_body; + } + }; } - public function httpHeaderAcceptProvider() + public static function httpHeaderAcceptProvider(): array { - return array( - array('application/json', Format::JSON), - array('application/json;q=1,application/xml;q=.5', Format::JSON), - array('application/json,application/xml;q=.5', Format::JSON), - array('application/json,application/xml', Format::JSON), - array('application/json-p', Format::JSONP), - array('text/html', Format::HTML), - array('text/plain', Format::PLAIN), - array('application/xml', Format::XML) - ); + return [ + ['application/json', Format::JSON], + ['application/json;q=1,application/xml;q=.5', Format::JSON], + ['application/json,application/xml;q=.5', Format::JSON], + ['application/json,application/xml', Format::JSON], + ['application/json-p', Format::JSONP], + ['text/html', Format::HTML], + ['text/plain', Format::PLAIN], + ['application/xml', Format::XML], + ]; } - /** - * @dataProvider httpHeaderAcceptProvider - * @covers ::getFormat - */ + #[DataProvider('httpHeaderAcceptProvider')] public function testGetFormatViaHttpAcceptHeader($http_accept, $format) { $_SERVER['REQUEST_URI'] = '/controller/action'; @@ -169,9 +158,6 @@ public function testGetFormatViaHttpAcceptHeader($http_accept, $format) $this->assertEquals($format, $result); } - /** - * @covers ::getFormat - */ public function testGetFormatViaUrl() { $_SERVER['REQUEST_URI'] = '/controller.text/action.json?key=/value.xml'; @@ -181,9 +167,6 @@ public function testGetFormatViaUrl() $this->assertEquals(Format::JSON, $result); } - /** - * @covers ::getFormat - */ public function testGetFormatViaWrongUrl() { // We can't have a '?' in the middle of an URL @@ -194,31 +177,28 @@ public function testGetFormatViaWrongUrl() $this->assertEquals(Format::JSON, $result); } - public function keyValueBodyProvider() + public static function keyValueBodyProvider(): array { - return array( - array(array()), - array(array('key1' => 'value1&specialchars=1')), - array( - array( + return [ + [[]], + [['key1' => 'value1&specialchars=1']], + [ + [ 'key1' => 'value1&specialchars=1', 'key2' => 'value2', - ) - ) - ); + ], + ], + ]; } - /** - * @dataProvider keyValueBodyProvider - * @covers ::getData - */ + #[DataProvider('keyValueBodyProvider')] public function testGetDataAsWwwFormUrlencoded(array $array_input_data) { $mock = $this->prepareGetDataForWwwFormUrlencodedCall($array_input_data); $result = $mock->getData(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(count($array_input_data), $result); foreach ($array_input_data as $key => $value) { $this->assertArrayHasKey($key, $result); @@ -228,7 +208,7 @@ public function testGetDataAsWwwFormUrlencoded(array $array_input_data) /** * @param $array_input_data - * @return RestServer|\Mockery\MockInterface + * @return RestServer */ protected function prepareGetDataForWwwFormUrlencodedCall($array_input_data) { @@ -249,7 +229,7 @@ protected static function convertInputDataArrayToText(array $input_data_array) return urlencode($value); }, $input_data_array); - $tmp = array(); + $tmp = []; foreach ($input_data_array as $key => $value) { array_push($tmp, $key . '=' . $value); } @@ -258,10 +238,7 @@ protected static function convertInputDataArrayToText(array $input_data_array) return $text_input_data; } - /** - * @dataProvider keyValueBodyProvider - * @covers ::getData - */ + #[DataProvider('keyValueBodyProvider')] public function testGetDataAsJsonWithoutContentType(array $array_input_data) { $mock = $this->mockGetRawHttpRequestBody(json_encode($array_input_data)); @@ -269,7 +246,7 @@ public function testGetDataAsJsonWithoutContentType(array $array_input_data) $result = $mock->getData(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(count($array_input_data), $result); foreach ($array_input_data as $key => $value) { $this->assertArrayHasKey($key, $result); @@ -277,23 +254,18 @@ public function testGetDataAsJsonWithoutContentType(array $array_input_data) } } - /** - * @expectedException \JK\RestServer\RestException - * @expectedExceptionMessage Content-Type "not/supported" not supported - * @expectedExceptionCode 500 - * @covers ::getData - */ public function testGetDataAsJsonWithUnsupportedContentType() { + $this->expectException(RestException::class); + $this->expectExceptionMessage('Content-Type "not/supported" not supported'); + $this->expectExceptionCode(500); + $_SERVER['CONTENT_TYPE'] = 'not/supported'; $this->sut->getData(); } - /** - * @dataProvider keyValueBodyProvider - * @covers ::getData - */ + #[DataProvider('keyValueBodyProvider')] public function testGetDataAsJsonWithContentType(array $array_input_data) { $mock = $this->mockGetRawHttpRequestBody(json_encode($array_input_data)); @@ -302,7 +274,7 @@ public function testGetDataAsJsonWithContentType(array $array_input_data) $result = $mock->getData(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(count($array_input_data), $result); foreach ($array_input_data as $key => $value) { $this->assertArrayHasKey($key, $result); @@ -310,9 +282,6 @@ public function testGetDataAsJsonWithContentType(array $array_input_data) } } - /** - * @covers ::getPath - */ public function testGetPath() { $_SERVER['REQUEST_URI'] = '/controller/action.json/'; @@ -323,21 +292,20 @@ public function testGetPath() $this->assertEquals('controller/action', $result); } - public function requestMethodProvider() + public static function requestMethodProvider(): array { - return array( - array('PUT'), - array('GET'), - array('DELETE'), - array('PUSH') - ); + return [ + ['PUT'], + ['GET'], + ['DELETE'], + ['PUSH'], + ]; } /** - * @dataProvider requestMethodProvider * @param $request_method - * @covers ::getMethod */ + #[DataProvider('requestMethodProvider')] public function testGetMethod($request_method) { $_SERVER['REQUEST_METHOD'] = $request_method; @@ -348,14 +316,12 @@ public function testGetMethod($request_method) } /** - * @group bug004 - * @group regression - * @group integration - * @group no-travis * @throws \Exception - * @runInSeparateProcess - * @coversNothing */ + #[Group('bug004')] + #[Group('regression')] + #[Group('integration')] + #[RunInSeparateProcess] public function testUrlDefaultParameters() { $this->sut->addClass(new \JK\RestServer\Tests\Fixtures\Controller\TestApiController(), 'test'); @@ -369,21 +335,19 @@ public function testUrlDefaultParameters() $result = ob_get_contents(); ob_end_clean(); - $expected = array( + $expected = [ 'param1' => 'default_value_1', - 'param2' => 'default_value_2' - ); + 'param2' => 'default_value_2', + ]; $this->assertJsonStringEqualsJsonString(json_encode($expected), $result); } /** - * @group integration - * @group no-travis * @throws \Exception - * @runInSeparateProcess - * @coversNothing */ + #[Group('integration')] + #[RunInSeparateProcess] public function testUrlParameters() { $this->sut->addClass(new \JK\RestServer\Tests\Fixtures\Controller\TestApiController(), 'test'); @@ -397,21 +361,17 @@ public function testUrlParameters() $result = ob_get_contents(); ob_end_clean(); - $expected = array( + $expected = [ 'param1' => 'value_1', - 'param2' => 'value_2' - ); + 'param2' => 'value_2', + ]; $this->assertJsonStringEqualsJsonString(json_encode($expected), $result); } - /** - * @group regression - * @group integration - * @group no-travis - * @runInSeparateProcess - * @coversNothing - */ + #[Group('regression')] + #[Group('integration')] + #[RunInSeparateProcess] public function testAMethodWithoutDefaultParameters() { $this->sut->addClass(new \JK\RestServer\Tests\Fixtures\Controller\TestApiController(), 'test'); @@ -425,28 +385,23 @@ public function testAMethodWithoutDefaultParameters() $result = ob_get_contents(); ob_end_clean(); - $expected = array( + $expected = [ 'param1' => 'value_1', - ); + ]; $this->assertJsonStringEqualsJsonString(json_encode($expected), $result); } - - /** - * @group regression - * @group integration - * @group no-travis - * @runInSeparateProcess - * @coversNothing - */ + #[Group('regression')] + #[Group('integration')] + #[RunInSeparateProcess] public function testMethodParameterOrderingPart1() { - $expected = array( + $expected = [ 'string' => 'myString', 'first_id' => 23, // default value of the method - 'second_id' => 42 // default value of the method - ); + 'second_id' => 42, // default value of the method + ]; $this->sut->addClass(new \JK\RestServer\Tests\Fixtures\Controller\TestApiController(), 'test'); $_SERVER['REQUEST_URI'] = '/test/string/' . $expected['string']; @@ -462,20 +417,16 @@ public function testMethodParameterOrderingPart1() $this->assertJsonStringEqualsJsonString(json_encode($expected), $result); } - /** - * @group regression - * @group integration - * @group no-travis - * @runInSeparateProcess - * @coversNothing - */ + #[Group('regression')] + #[Group('integration')] + #[RunInSeparateProcess] public function testMethodParameterOrderingPart2() { - $expected = array( + $expected = [ 'string' => 'myString', - 'first_id' => 4, - 'second_id' => 42 // default value of the method - ); + 'first_id' => '4', // URL parameters are passed as strings + 'second_id' => 42, // default value of the method + ]; $this->sut->addClass(new \JK\RestServer\Tests\Fixtures\Controller\TestApiController(), 'test'); $_SERVER['REQUEST_URI'] = '/test/string/' . $expected['string'] . '/first/' . $expected['first_id']; @@ -491,20 +442,16 @@ public function testMethodParameterOrderingPart2() $this->assertJsonStringEqualsJsonString(json_encode($expected), $result); } - /** - * @group regression - * @group integration - * @group no-travis - * @runInSeparateProcess - * @coversNothing - */ + #[Group('regression')] + #[Group('integration')] + #[RunInSeparateProcess] public function testMethodParameterOrderingPart3() { - $expected = array( + $expected = [ 'string' => 'myString', - 'first_id' => 4, - 'second_id' => 5 - ); + 'first_id' => '4', // URL parameters are passed as strings + 'second_id' => '5', // URL parameters are passed as strings + ]; $this->sut->addClass(new \JK\RestServer\Tests\Fixtures\Controller\TestApiController(), 'test'); $_SERVER['REQUEST_URI'] = '/test/string/' . $expected['string'] . '/first/' . $expected['first_id'] . '/second/' . $expected['second_id']; @@ -520,9 +467,6 @@ public function testMethodParameterOrderingPart3() $this->assertJsonStringEqualsJsonString(json_encode($expected), $result); } - /** - * @covers ::setStatus() - */ public function testSetStatus() { unset($_SERVER['SERVER_PROTOCOL']); @@ -535,15 +479,12 @@ public function testSetStatus() $this->assertEquals('HTTP/2 404 Not Found', $result); } - /** - * @covers ::sendData() - * @runInSeparateProcess - */ + #[RunInSeparateProcess] public function testSendDataDefaultsToJson() { - $data = array( - 'key1' => 'value1' - ); + $data = [ + 'key1' => 'value1', + ]; ob_start(); $this->sut->sendData($data); @@ -559,15 +500,12 @@ public function testSendDataDefaultsToJson() $this->assertJsonStringEqualsJsonString(json_encode($data), $result); } - /** - * @covers ::sendData() - * @runInSeparateProcess - */ + #[RunInSeparateProcess] public function testSendDataJsonP() { - $data = array( - 'key1' => 'value1' - ); + $data = [ + 'key1' => 'value1', + ]; $this->sut->format = Format::JSONP; $_GET['callback'] = 'callback'; @@ -586,30 +524,25 @@ public function testSendDataJsonP() $this->assertEquals('callback({"key1":"value1"})', $result); } - /** - * @covers ::sendData() - * @runInSeparateProcess - * @expectedException \JK\RestServer\RestException - * @expectedExceptionMessage No callback given. - * @expectedExceptionCode 400 - */ + #[RunInSeparateProcess] public function testSendDataJsonPWithoutCallback() { + $this->expectException(RestException::class); + $this->expectExceptionMessage('No callback given.'); + $this->expectExceptionCode(400); + $this->sut->format = Format::JSONP; unset($_GET['callback']); - $this->sut->sendData(array()); + $this->sut->sendData([]); } - /** - * @covers ::sendData() - * @runInSeparateProcess - */ + #[RunInSeparateProcess] public function testSendDataXml() { - $data = array( - 'key1' => 'value1' - ); + $data = [ + 'key1' => 'value1', + ]; $this->sut->format = Format::XML; @@ -626,13 +559,10 @@ public function testSendDataXml() // Assert body $this->assertXmlStringEqualsXmlString( 'value1', - $result + $result, ); } - /** - * @covers ::setRoot() - */ public function testSetRootToEmpty() { $result = $this->sut->setRoot(null); @@ -640,17 +570,13 @@ public function testSetRootToEmpty() $this->assertNull($result); } - /** - * @group regression - * @group integration - * @group no-travis - * @runInSeparateProcess - * @covers ::injectLanguageIntoMethodParameters() - */ + #[Group('regression')] + #[Group('integration')] + #[RunInSeparateProcess] public function testMethodWithLanguageObjectAndData() { $this->sut->addClass(new \JK\RestServer\Tests\Fixtures\Controller\TestApiController(), 'test'); - $this->sut->setSupportedLanguages(array('en', 'de')); + $this->sut->setSupportedLanguages(['en', 'de']); $this->sut->setDefaultLanguage('en'); $_SERVER['REQUEST_URI'] = '/test/method_with_language_object_and_data'; @@ -669,21 +595,15 @@ public function testMethodWithLanguageObjectAndData() } /** - * @group integration - * @group no-travis * @throws \Exception - * @runInSeparateProcess - * @covers ::handle() - * @covers ::handleCorsPreflightRequest() - * @covers ::setCorsMaxAge() - * @covers ::setCorsAllowedOrigin() - * @covers ::setCorsAllowedHeaders() */ + #[Group('integration')] + #[RunInSeparateProcess] public function testCorsPreflightRequest() { $cors_max_age = 15; - $cors_allowed_origin = array('http://example.tld'); - $cors_allowed_headers = array('content-type'); + $cors_allowed_origin = ['http://example.tld']; + $cors_allowed_headers = ['content-type']; $this->sut->addClass(new \JK\RestServer\Tests\Fixtures\Controller\TestApiController(), 'test'); $this->sut->setCorsMaxAge($cors_max_age); @@ -699,7 +619,6 @@ public function testCorsPreflightRequest() $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip, deflate, sdch'; $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4'; - ob_start(); $this->sut->handle(); ob_end_clean(); @@ -707,12 +626,14 @@ public function testCorsPreflightRequest() $hm = $this->sut->header_manager; $this->assertEquals(implode(', ', $cors_allowed_origin), $hm->getHeader('Access-Control-Allow-Origin')); - $this->assertTrue(is_int($hm->getHeader('Access-Control-Max-Age')), - 'Access-Control-Max-Age CORS header should be in seconds'); + $this->assertTrue( + is_int($hm->getHeader('Access-Control-Max-Age')), + 'Access-Control-Max-Age CORS header should be in seconds', + ); $this->assertEquals($cors_max_age, $hm->getHeader('Access-Control-Max-Age')); $methods = explode(',', $hm->getHeader('Access-Control-Allow-Methods')); - foreach (array('GET', 'OPTIONS', 'POST', 'DELETE') as $method) { + foreach (['GET', 'OPTIONS', 'POST', 'DELETE'] as $method) { $this->assertContains($method, $methods, 'Access-Control-Allow-Methods should contain: ' . $method); } @@ -722,10 +643,6 @@ public function testCorsPreflightRequest() } } - /** - * @covers ::addCorsAllowedHeader() - * @covers ::getCorsAllowedHeaders() - */ public function testaddCorsAllowedHeader() { $this->sut->addCorsAllowedHeader('my-test-header'); @@ -736,22 +653,16 @@ public function testaddCorsAllowedHeader() } /** - * @group regression - * @group integration - * @group no-travis * @throws \Exception - * @runInSeparateProcess - * @covers ::handle() - * @covers ::handleCorsPreflightRequest() - * @covers ::setCorsMaxAge() - * @covers ::setCorsAllowedOrigin() - * @covers ::setCorsAllowedHeaders() */ + #[Group('regression')] + #[Group('integration')] + #[RunInSeparateProcess] public function testCorsPreflightRequestWithUrlParam() { $cors_max_age = 15; - $cors_allowed_origin = array('http://example.tld'); - $cors_allowed_headers = array('content-type'); + $cors_allowed_origin = ['http://example.tld']; + $cors_allowed_headers = ['content-type']; $this->sut->addClass(new \JK\RestServer\Tests\Fixtures\Controller\TestApiController(), 'test'); $this->sut->setCorsMaxAge($cors_max_age); @@ -767,7 +678,6 @@ public function testCorsPreflightRequestWithUrlParam() $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip, deflate, sdch'; $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4'; - ob_start(); $this->sut->handle(); ob_end_clean(); @@ -775,12 +685,14 @@ public function testCorsPreflightRequestWithUrlParam() $hm = $this->sut->header_manager; $this->assertEquals(implode(', ', $cors_allowed_origin), $hm->getHeader('Access-Control-Allow-Origin')); - $this->assertTrue(is_int($hm->getHeader('Access-Control-Max-Age')), - 'Access-Control-Max-Age CORS header should be in seconds'); + $this->assertTrue( + is_int($hm->getHeader('Access-Control-Max-Age')), + 'Access-Control-Max-Age CORS header should be in seconds', + ); $this->assertEquals($cors_max_age, $hm->getHeader('Access-Control-Max-Age')); $methods = explode(',', $hm->getHeader('Access-Control-Allow-Methods')); - foreach (array('DELETE', 'OPTIONS') as $method) { + foreach (['DELETE', 'OPTIONS'] as $method) { $this->assertContains($method, $methods, 'Access-Control-Allow-Methods should contain: ' . $method); } diff --git a/tests/JK/RestServer/Tests/UtilitiesTest.php b/tests/UtilitiesTest.php similarity index 79% rename from tests/JK/RestServer/Tests/UtilitiesTest.php rename to tests/UtilitiesTest.php index 7c9823e..c033a45 100644 --- a/tests/JK/RestServer/Tests/UtilitiesTest.php +++ b/tests/UtilitiesTest.php @@ -1,33 +1,31 @@ assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('de', $result); $this->assertArrayHasKey('de_de', $result); @@ -45,18 +43,16 @@ public function testSortByPriority() } } - /** - * @group regression - */ + #[Group('regression')] public function testSortByPriorityWithEqualValuesAndReverseLexigraphicalOrder() { $accept_str = 'a,x'; $result = Utilities::sortByPriority($accept_str); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); - $results = array(); + $results = []; foreach ($result as $type => $quality) { $results[] = $type; } @@ -64,7 +60,6 @@ public function testSortByPriorityWithEqualValuesAndReverseLexigraphicalOrder() $this->assertEquals('a', $results[0], 'First element should be a, but is: ' . $results[0]); $this->assertEquals('x', $results[1], 'Last element should be x, but is: ' . $results[1]); - } public function testSortByPriorityWithOnlyOneElementWithoutQuality() @@ -73,7 +68,7 @@ public function testSortByPriorityWithOnlyOneElementWithoutQuality() $result = Utilities::sortByPriority($accept_language_str); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('de', $result); $this->assertEquals(1, $result['de']); } @@ -84,7 +79,7 @@ public function testSortByPriorityWithOnlyOneElementWithQuality() $result = Utilities::sortByPriority($accept_language_str); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('de', $result); $this->assertEquals(0.75, $result['de']); } @@ -95,7 +90,7 @@ public function testSortByPriorityWithTwoElementsWithoutQuality() $result = Utilities::sortByPriority($str); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('de', $result); $this->assertArrayHasKey('en', $result); $this->assertEquals(1, $result['de']); @@ -108,7 +103,7 @@ public function testSortByPriorityWithoutElements() $result = Utilities::sortByPriority($str); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(0, $result, 'An empty header value should lead to an empty result array'); } @@ -118,7 +113,7 @@ public function testSortByPriorityWithAsterisc() $result = Utilities::sortByPriority($str); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('*', $result); $this->assertEquals(1, $result['*']); } @@ -129,7 +124,7 @@ public function testSortByPriorityWithAsteriscAndOtherValues() $result = Utilities::sortByPriority($str); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('de', $result); $this->assertArrayHasKey('*', $result); $this->assertEquals(1, $result['de']); @@ -142,7 +137,7 @@ public function testSortByPriorityWithChromeAcceptLanguageString() $result = Utilities::sortByPriority($str); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('de-de', $result); $this->assertArrayHasKey('de', $result); $this->assertArrayHasKey('en-us', $result); @@ -155,43 +150,43 @@ public function testSortByPriorityWithChromeAcceptLanguageString() public function testSimpleArrayToObject() { - $array = array( - 'key1' => 'value1' - ); + $array = [ + 'key1' => 'value1', + ]; $object = Utilities::arrayToObject($array); - $this->assertObjectHasAttribute('key1', $object); + $this->assertObjectHasProperty('key1', $object); $this->assertEquals('value1', $object->key1); } public function testTwoElementArrayToObject() { - $array = array( + $array = [ 'key1' => 'value1', - 'key2' => 'value2' - ); + 'key2' => 'value2', + ]; $object = Utilities::arrayToObject($array); - $this->assertObjectHasAttribute('key1', $object); + $this->assertObjectHasProperty('key1', $object); $this->assertEquals('value1', $object->key1); - $this->assertObjectHasAttribute('key2', $object); + $this->assertObjectHasProperty('key2', $object); $this->assertEquals('value2', $object->key2); } public function testNestedArrayToObject() { - $array = array( - 'key1' => array( - 'key2' => 'value' - ) - ); + $array = [ + 'key1' => [ + 'key2' => 'value', + ], + ]; $object = Utilities::arrayToObject($array); - $this->assertObjectHasAttribute('key1', $object); - $this->assertObjectHasAttribute('key2', $object->key1); + $this->assertObjectHasProperty('key1', $object); + $this->assertObjectHasProperty('key2', $object->key1); $this->assertEquals('value', $object->key1->key2); } @@ -235,7 +230,7 @@ public function testNestedObjectToArray() public function testArrayToXmlWithEmptyArray() { - $array = array(); + $array = []; $xml = Utilities::arrayToXml($array); @@ -244,19 +239,19 @@ public function testArrayToXmlWithEmptyArray() protected function parseXmlString($xml) { - $tmp = ''."\n"; - $tmp .= "".$xml.''; + $tmp = '' . "\n"; + $tmp .= "" . $xml . ''; return simplexml_load_string($tmp); } public function testArrayToXmlWithStringArray() { - $array = array('one', 'two'); + $array = ['one', 'two']; $xml = Utilities::arrayToXml($array); $obj = $this->parseXmlString($xml); - $this->assertObjectHasAttribute('item', $obj); + $this->assertObjectHasProperty('item', $obj); $this->assertEquals(2, count($obj->item)); // can't use assertCount here, since it's not an array $this->assertEquals($array[0], $obj->item[0]); $this->assertEquals($array[1], $obj->item[1]); @@ -264,19 +259,19 @@ public function testArrayToXmlWithStringArray() public function testArrayToXmlWithNestedArray() { - $array = array( + $array = [ 'key1' => 'value1', - 'key2' => array( - 'key3' => 'value2' - ) - ); + 'key2' => [ + 'key3' => 'value2', + ], + ]; $xml = Utilities::arrayToXml($array); $obj = $this->parseXmlString($xml); - $this->assertObjectHasAttribute('key1', $obj); - $this->assertObjectHasAttribute('key2', $obj); - $this->assertObjectHasAttribute('key3', $obj->key2); + $this->assertObjectHasProperty('key1', $obj); + $this->assertObjectHasProperty('key2', $obj); + $this->assertObjectHasProperty('key3', $obj->key2); $this->assertEquals($array['key1'], $obj->key1); $this->assertEquals($array['key2']['key3'], $obj->key2->key3); @@ -305,7 +300,7 @@ public function testGetPositionsOfParameterWithTypeHint() $test_class = new TestClass(); $result = Utilities::getPositionsOfParameterWithTypeHint($test_class, 'method', 'stdClass'); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('param2', $result); $this->assertEquals(1, $result['param2']); }