From 301cc3832a6ce606e4a8f5f1d61ddb195b67e342 Mon Sep 17 00:00:00 2001 From: jkohl Date: Sun, 1 Nov 2026 11:38:46 +0100 Subject: [PATCH 1/5] Switch to PSR-4 layout and migrate test suite to PHPUnit 12 - Require PHP ^8.3 (8.2 reaches end of life on 2026-12-31) - Autoload via PSR-4 (src/, tests/ as autoload-dev) instead of PSR-0 - Replace PHPUnit 4 + Mockery with PHPUnit 12; drop abandoned dev dependencies (fabpot/php-cs-fixer, codeclimate/php-test-reporter) and redundant PHP_CodeSniffer - Convert docblock annotations to attributes, use static data providers, expectException*() and current assertion names - Clean up the URL map cache in RestServerTest::tearDown(); a cache left behind by unit tests made the integration tests route against an empty map, which is why they were excluded from CI ("no-travis") - URL parameters are strings; fix expectations that only passed because of PHPUnit 4's loose JSON comparison --- .codeclimate.yml | 11 - .gitignore | 3 + .scrutinizer.yml | 41 --- .travis.yml | 29 -- composer.json | 29 +- phpunit.xml | 34 +-- sami_config.php | 28 -- src/{JK/RestServer => }/DocBlockParser.php | 0 src/{JK/RestServer => }/Format.php | 0 src/{JK/RestServer => }/HeaderManager.php | 0 src/{JK/RestServer => }/HttpMethods.php | 0 src/{JK/RestServer => }/HttpStatusCodes.php | 0 .../InputDataTransformationMode.php | 0 src/{JK/RestServer => }/Language.php | 0 src/{JK/RestServer => }/Mode.php | 0 src/{JK/RestServer => }/RestException.php | 0 src/{JK/RestServer => }/RestServer.php | 0 src/{JK/RestServer => }/Utilities.php | 0 tests/Bootstrap.php | 15 +- .../Tests => }/DocBlockParserTest.php | 27 +- tests/{JK/RestServer/Tests => }/DummyTest.php | 4 +- .../Fixtures/Controller/TestApiController.php | 0 .../{JK/RestServer/Tests => }/FormatTest.php | 19 +- .../Tests => }/HeaderManagerTest.php | 59 +--- .../RestServer/Tests => }/HttpMethodsTest.php | 16 +- .../Tests => }/HttpStatusCodesTest.php | 24 +- .../RestServer/Tests => }/LanguageTest.php | 22 +- .../Tests => }/RestExceptionTest.php | 11 +- .../RestServer/Tests => }/RestServerTest.php | 254 ++++++------------ .../RestServer/Tests => }/UtilitiesTest.php | 52 ++-- 30 files changed, 197 insertions(+), 481 deletions(-) delete mode 100644 .codeclimate.yml delete mode 100644 .scrutinizer.yml delete mode 100644 .travis.yml delete mode 100644 sami_config.php rename src/{JK/RestServer => }/DocBlockParser.php (100%) rename src/{JK/RestServer => }/Format.php (100%) rename src/{JK/RestServer => }/HeaderManager.php (100%) rename src/{JK/RestServer => }/HttpMethods.php (100%) rename src/{JK/RestServer => }/HttpStatusCodes.php (100%) rename src/{JK/RestServer => }/InputDataTransformationMode.php (100%) rename src/{JK/RestServer => }/Language.php (100%) rename src/{JK/RestServer => }/Mode.php (100%) rename src/{JK/RestServer => }/RestException.php (100%) rename src/{JK/RestServer => }/RestServer.php (100%) rename src/{JK/RestServer => }/Utilities.php (100%) rename tests/{JK/RestServer/Tests => }/DocBlockParserTest.php (80%) rename tests/{JK/RestServer/Tests => }/DummyTest.php (64%) rename tests/{JK/RestServer/Tests => }/Fixtures/Controller/TestApiController.php (100%) rename tests/{JK/RestServer/Tests => }/FormatTest.php (65%) rename tests/{JK/RestServer/Tests => }/HeaderManagerTest.php (77%) rename tests/{JK/RestServer/Tests => }/HttpMethodsTest.php (78%) rename tests/{JK/RestServer/Tests => }/HttpStatusCodesTest.php (51%) rename tests/{JK/RestServer/Tests => }/LanguageTest.php (87%) rename tests/{JK/RestServer/Tests => }/RestExceptionTest.php (71%) rename tests/{JK/RestServer/Tests => }/RestServerTest.php (82%) rename tests/{JK/RestServer/Tests => }/UtilitiesTest.php (86%) 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/.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/.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/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 100% rename from src/JK/RestServer/DocBlockParser.php rename to src/DocBlockParser.php diff --git a/src/JK/RestServer/Format.php b/src/Format.php similarity index 100% rename from src/JK/RestServer/Format.php rename to src/Format.php diff --git a/src/JK/RestServer/HeaderManager.php b/src/HeaderManager.php similarity index 100% rename from src/JK/RestServer/HeaderManager.php rename to src/HeaderManager.php diff --git a/src/JK/RestServer/HttpMethods.php b/src/HttpMethods.php similarity index 100% rename from src/JK/RestServer/HttpMethods.php rename to src/HttpMethods.php diff --git a/src/JK/RestServer/HttpStatusCodes.php b/src/HttpStatusCodes.php similarity index 100% rename from src/JK/RestServer/HttpStatusCodes.php rename to src/HttpStatusCodes.php diff --git a/src/JK/RestServer/InputDataTransformationMode.php b/src/InputDataTransformationMode.php similarity index 100% rename from src/JK/RestServer/InputDataTransformationMode.php rename to src/InputDataTransformationMode.php diff --git a/src/JK/RestServer/Language.php b/src/Language.php similarity index 100% rename from src/JK/RestServer/Language.php rename to src/Language.php diff --git a/src/JK/RestServer/Mode.php b/src/Mode.php similarity index 100% rename from src/JK/RestServer/Mode.php rename to src/Mode.php diff --git a/src/JK/RestServer/RestException.php b/src/RestException.php similarity index 100% rename from src/JK/RestServer/RestException.php rename to src/RestException.php diff --git a/src/JK/RestServer/RestServer.php b/src/RestServer.php similarity index 100% rename from src/JK/RestServer/RestServer.php rename to src/RestServer.php diff --git a/src/JK/RestServer/Utilities.php b/src/Utilities.php similarity index 100% rename from src/JK/RestServer/Utilities.php rename to src/Utilities.php 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..35f1e95 100644 --- a/tests/JK/RestServer/Tests/DummyTest.php +++ b/tests/DummyTest.php @@ -1,9 +1,9 @@ assertEquals(Format::JSON, $result); } - /** - * @covers JK\RestServer\Format::getMimeTypeFromFormatAbbreviation - */ public function testGetMimeTypeFromFormatNonExistentAbbreviation() { $result = Format::getMimeTypeFromFormatAbbreviation('non-existent'); @@ -30,9 +25,6 @@ public function testGetMimeTypeFromFormatNonExistentAbbreviation() $this->assertFalse($result); } - /** - * @covers JK\RestServer\Format::isMimeTypeSupported - */ public function testIsMimeTypeSupported() { $result = Format::isMimeTypeSupported('application/json'); @@ -40,9 +32,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 77% rename from tests/JK/RestServer/Tests/HeaderManagerTest.php rename to tests/HeaderManagerTest.php index dade498..3f8195e 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,9 +55,6 @@ public function testGetHeaderNonExistingHeader() $this->assertNull($result); } - /** - * @covers ::addHeaders() - */ public function testAddHeaders() { $headers = array( @@ -84,9 +67,6 @@ public function testAddHeaders() $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,7 +127,6 @@ public function testSendAllHeaders() $this->sut->addHeader('Content-Type', 'application/json'); - $this->sut->setStatusHeader('404 Not Found'); $this->sut->sendAllHeaders(); diff --git a/tests/JK/RestServer/Tests/HttpMethodsTest.php b/tests/HttpMethodsTest.php similarity index 78% rename from tests/JK/RestServer/Tests/HttpMethodsTest.php rename to tests/HttpMethodsTest.php index 86150ad..9d3818e 100644 --- a/tests/JK/RestServer/Tests/HttpMethodsTest.php +++ b/tests/HttpMethodsTest.php @@ -1,19 +1,16 @@ expectException(\Exception::class); + $this->expectExceptionMessage('HttpStatusCodes class can not be instantiatiated.'); + new HttpStatusCodes(); } - /** - * @covers ::getDescription() - */ public function testGetDescription() { $result = HttpStatusCodes::getDescription(404); @@ -31,9 +26,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 87% rename from tests/JK/RestServer/Tests/LanguageTest.php rename to tests/LanguageTest.php index 1dc4713..d2dffe8 100644 --- a/tests/JK/RestServer/Tests/LanguageTest.php +++ b/tests/LanguageTest.php @@ -1,16 +1,16 @@ getPreferedLanguage(); - $this->assertInternalType('string', $result); + $this->assertIsString($result); $this->assertEquals('de', $result); } @@ -38,7 +38,7 @@ public function testGetPreferedLanguageWithAnyMatches() $result = $language->getPreferedLanguage(); - $this->assertInternalType('string', $result); + $this->assertIsString($result); $this->assertEquals($default_langauge, $result); } @@ -51,7 +51,7 @@ public function testGetDefaultLanguage() $result = $language->getDefaultLanguage(); - $this->assertInternalType('string', $result); + $this->assertIsString($result); $this->assertEquals($default_langauge, $result); } @@ -64,7 +64,7 @@ public function testGetSupportedLanguages() $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]; @@ -81,7 +81,7 @@ public function testGetClientAcceptedLanguages() $result = $language->getClientAcceptedLanguages(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(2, $result); $this->assertArrayHasKey('en', $result); $this->assertArrayHasKey('fr', $result); @@ -96,7 +96,7 @@ public function testGetClientAcceptedLanguagesWithEmptyString() $result = $language->getClientAcceptedLanguages(); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(0, $result); } @@ -106,7 +106,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 71% rename from tests/JK/RestServer/Tests/RestExceptionTest.php rename to tests/RestExceptionTest.php index 7e1a3a0..8776e4c 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'); } diff --git a/tests/JK/RestServer/Tests/RestServerTest.php b/tests/RestServerTest.php similarity index 82% rename from tests/JK/RestServer/Tests/RestServerTest.php rename to tests/RestServerTest.php index ddcc0ff..083482c 100644 --- a/tests/JK/RestServer/Tests/RestServerTest.php +++ b/tests/RestServerTest.php @@ -1,8 +1,12 @@ sut = new RestServer(); @@ -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,7 +74,7 @@ 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), @@ -93,10 +85,7 @@ public function requestUriProvider() ); } - /** - * @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,17 +116,24 @@ 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), @@ -155,10 +147,7 @@ public function httpHeaderAcceptProvider() ); } - /** - * @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,7 +177,7 @@ public function testGetFormatViaWrongUrl() $this->assertEquals(Format::JSON, $result); } - public function keyValueBodyProvider() + public static function keyValueBodyProvider(): array { return array( array(array()), @@ -208,17 +191,14 @@ public function keyValueBodyProvider() ); } - /** - * @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) { @@ -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,7 +292,7 @@ public function testGetPath() $this->assertEquals('controller/action', $result); } - public function requestMethodProvider() + public static function requestMethodProvider(): array { return array( array('PUT'), @@ -334,10 +303,9 @@ public function requestMethodProvider() } /** - * @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'); @@ -378,12 +344,10 @@ public function testUrlDefaultParameters() } /** - * @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'); @@ -405,13 +369,9 @@ public function testUrlParameters() $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'); @@ -432,14 +392,9 @@ public function testAMethodWithoutDefaultParameters() $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( @@ -462,18 +417,14 @@ 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( 'string' => 'myString', - 'first_id' => 4, + 'first_id' => '4', // URL parameters are passed as strings 'second_id' => 42 // default value of the method ); @@ -491,19 +442,15 @@ 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( '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'); @@ -520,9 +467,6 @@ public function testMethodParameterOrderingPart3() $this->assertJsonStringEqualsJsonString(json_encode($expected), $result); } - /** - * @covers ::setStatus() - */ public function testSetStatus() { unset($_SERVER['SERVER_PROTOCOL']); @@ -535,10 +479,7 @@ public function testSetStatus() $this->assertEquals('HTTP/2 404 Not Found', $result); } - /** - * @covers ::sendData() - * @runInSeparateProcess - */ + #[RunInSeparateProcess] public function testSendDataDefaultsToJson() { $data = array( @@ -559,10 +500,7 @@ public function testSendDataDefaultsToJson() $this->assertJsonStringEqualsJsonString(json_encode($data), $result); } - /** - * @covers ::sendData() - * @runInSeparateProcess - */ + #[RunInSeparateProcess] public function testSendDataJsonP() { $data = array( @@ -586,25 +524,20 @@ 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()); } - /** - * @covers ::sendData() - * @runInSeparateProcess - */ + #[RunInSeparateProcess] public function testSendDataXml() { $data = array( @@ -630,9 +563,6 @@ public function testSendDataXml() ); } - /** - * @covers ::setRoot() - */ public function testSetRootToEmpty() { $result = $this->sut->setRoot(null); @@ -640,13 +570,9 @@ 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'); @@ -669,16 +595,10 @@ 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; @@ -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(); @@ -722,10 +641,6 @@ public function testCorsPreflightRequest() } } - /** - * @covers ::addCorsAllowedHeader() - * @covers ::getCorsAllowedHeaders() - */ public function testaddCorsAllowedHeader() { $this->sut->addCorsAllowedHeader('my-test-header'); @@ -736,17 +651,11 @@ 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; @@ -767,7 +676,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(); diff --git a/tests/JK/RestServer/Tests/UtilitiesTest.php b/tests/UtilitiesTest.php similarity index 86% rename from tests/JK/RestServer/Tests/UtilitiesTest.php rename to tests/UtilitiesTest.php index 7c9823e..74b740a 100644 --- a/tests/JK/RestServer/Tests/UtilitiesTest.php +++ b/tests/UtilitiesTest.php @@ -1,8 +1,10 @@ assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('de', $result); $this->assertArrayHasKey('de_de', $result); @@ -45,16 +46,14 @@ 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(); foreach ($result as $type => $quality) { @@ -64,7 +63,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 +71,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 +82,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 +93,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 +106,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 +116,7 @@ public function testSortByPriorityWithAsterisc() $result = Utilities::sortByPriority($str); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertArrayHasKey('*', $result); $this->assertEquals(1, $result['*']); } @@ -129,7 +127,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 +140,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); @@ -161,7 +159,7 @@ public function testSimpleArrayToObject() $object = Utilities::arrayToObject($array); - $this->assertObjectHasAttribute('key1', $object); + $this->assertObjectHasProperty('key1', $object); $this->assertEquals('value1', $object->key1); } @@ -174,9 +172,9 @@ public function testTwoElementArrayToObject() $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); } @@ -190,8 +188,8 @@ public function testNestedArrayToObject() $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); } @@ -256,7 +254,7 @@ public function testArrayToXmlWithStringArray() $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]); @@ -274,9 +272,9 @@ public function testArrayToXmlWithNestedArray() $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 +303,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']); } From 9814379e06e15ba732bd88d8d1bd59d42416765f Mon Sep 17 00:00:00 2001 From: jkohl Date: Sun, 1 Nov 2026 11:38:46 +0100 Subject: [PATCH 2/5] Replace Travis CI, Scrutinizer and Code Climate with GitHub Actions - CI workflow testing PHP 8.3, 8.4 and 8.5 (plus lowest dependencies) and checking coding style with php-cs-fixer (PER-CS) - Remove the discontinued Sami documentation config - Dependabot: weekly updates, also for GitHub Actions - README: replace dead badges, drop AMF/Flash mention, add dev section --- .gitattributes | 6 ++--- .github/dependabot.yml | 16 +++++++----- .github/workflows/ci.yml | 54 ++++++++++++++++++++++++++++++++++++++++ .php-cs-fixer.dist.php | 10 ++++++++ README.md | 21 ++++++++++------ 5 files changed, 90 insertions(+), 17 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .php-cs-fixer.dist.php diff --git a/.gitattributes b/.gitattributes index 93ae856..83364a4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,8 +1,8 @@ +/.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 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/.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/README.md b/README.md index 4cccfdc..8d4da67 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,21 @@ # 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. Supports AMF data if the Zend Framework is present for Flash clients. +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. 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. + +## 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 +``` From ec049c8404c0eb7f7d470f6781429133857bc6c8 Mon Sep 17 00:00:00 2001 From: jkohl Date: Sun, 1 Nov 2026 11:39:04 +0100 Subject: [PATCH 3/5] Apply PER-CS coding style Automated run of php-cs-fixer, no functional changes. --- src/DocBlockParser.php | 6 +- src/Format.php | 15 +- src/HeaderManager.php | 5 +- src/HttpMethods.php | 25 +-- src/HttpStatusCodes.php | 76 ++++----- src/InputDataTransformationMode.php | 10 +- src/Language.php | 7 +- src/Mode.php | 5 +- src/RestException.php | 1 - src/RestServer.php | 82 +++++----- src/Utilities.php | 15 +- tests/DummyTest.php | 2 +- .../Fixtures/Controller/TestApiController.php | 12 +- tests/FormatTest.php | 1 + tests/HeaderManagerTest.php | 9 +- tests/HttpMethodsTest.php | 27 ++-- tests/HttpStatusCodesTest.php | 1 + tests/LanguageTest.php | 13 +- tests/RestExceptionTest.php | 3 +- tests/RestServerTest.php | 148 +++++++++--------- tests/UtilitiesTest.php | 47 +++--- 21 files changed, 260 insertions(+), 250 deletions(-) diff --git a/src/DocBlockParser.php b/src/DocBlockParser.php index 2c09c80..3b4c9e7 100644 --- a/src/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/Format.php b/src/Format.php index 4e912d7..58d7a20 100644 --- a/src/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/HeaderManager.php b/src/HeaderManager.php index 376d50a..ce1b732 100644 --- a/src/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 index 9b5f0d2..bb99907 100644 --- a/src/InputDataTransformationMode.php +++ b/src/InputDataTransformationMode.php @@ -1,12 +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/Mode.php b/src/Mode.php index 170ccd6..79ec5a5 100644 --- a/src/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/Utilities.php b/src/Utilities.php index ba35b18..f7332aa 100644 --- a/src/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/DummyTest.php b/tests/DummyTest.php index 35f1e95..b58bd16 100644 --- a/tests/DummyTest.php +++ b/tests/DummyTest.php @@ -3,9 +3,9 @@ namespace JK\RestServer\Tests; use PHPUnit\Framework\TestCase; + class DummyTest extends TestCase { - public function testTrue() { $this->assertTrue(true); diff --git a/tests/Fixtures/Controller/TestApiController.php b/tests/Fixtures/Controller/TestApiController.php index a14cc70..1270635 100644 --- a/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/FormatTest.php b/tests/FormatTest.php index 0c15754..d6d26f5 100644 --- a/tests/FormatTest.php +++ b/tests/FormatTest.php @@ -1,4 +1,5 @@ 'Value1', - 'Header2' => 'Value2' - ); + 'Header2' => 'Value2', + ]; $this->sut->addHeaders($headers); $this->assertEquals($this->sut->getHeader('Header1'), $headers['Header1']); @@ -132,8 +132,7 @@ public function testSendAllHeaders() $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/HttpMethodsTest.php b/tests/HttpMethodsTest.php index 9d3818e..b46ba82 100644 --- a/tests/HttpMethodsTest.php +++ b/tests/HttpMethodsTest.php @@ -1,4 +1,5 @@ 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()', + ); } } @@ -36,14 +40,17 @@ 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/HttpStatusCodesTest.php b/tests/HttpStatusCodesTest.php index bd6d129..e8519f9 100644 --- a/tests/HttpStatusCodesTest.php +++ b/tests/HttpStatusCodesTest.php @@ -1,4 +1,5 @@ assertEquals($code, $e->getCode()); $this->assertEquals($message, $e->getMessage()); return; diff --git a/tests/RestServerTest.php b/tests/RestServerTest.php index 083482c..82e546c 100644 --- a/tests/RestServerTest.php +++ b/tests/RestServerTest.php @@ -25,7 +25,7 @@ protected function setUp(): void { // @codeCoverageIgnoreStart $this->sut = new RestServer(); -// $this->sut->setDefaultFormat(Format::PLAIN); + // $this->sut->setDefaultFormat(Format::PLAIN); // @codeCoverageIgnoreEnd unset($_SERVER['HTTP_ACCEPT']); @@ -76,13 +76,13 @@ public function testConstructorInNonExistentMode() 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')] @@ -135,16 +135,16 @@ public function getRawHttpRequestBody() 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')] @@ -179,16 +179,16 @@ public function testGetFormatViaWrongUrl() 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')] @@ -229,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); } @@ -294,12 +294,12 @@ public function testGetPath() public static function requestMethodProvider(): array { - return array( - array('PUT'), - array('GET'), - array('DELETE'), - array('PUSH') - ); + return [ + ['PUT'], + ['GET'], + ['DELETE'], + ['PUSH'], + ]; } /** @@ -335,10 +335,10 @@ 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); } @@ -361,10 +361,10 @@ 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); } @@ -385,9 +385,9 @@ public function testAMethodWithoutDefaultParameters() $result = ob_get_contents(); ob_end_clean(); - $expected = array( + $expected = [ 'param1' => 'value_1', - ); + ]; $this->assertJsonStringEqualsJsonString(json_encode($expected), $result); } @@ -397,11 +397,11 @@ public function testAMethodWithoutDefaultParameters() #[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']; @@ -422,11 +422,11 @@ public function testMethodParameterOrderingPart1() #[RunInSeparateProcess] public function testMethodParameterOrderingPart2() { - $expected = array( + $expected = [ 'string' => 'myString', 'first_id' => '4', // URL parameters are passed as strings - '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'] . '/first/' . $expected['first_id']; @@ -447,11 +447,11 @@ public function testMethodParameterOrderingPart2() #[RunInSeparateProcess] public function testMethodParameterOrderingPart3() { - $expected = array( + $expected = [ 'string' => 'myString', 'first_id' => '4', // URL parameters are passed as strings - 'second_id' => '5' // 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']; @@ -482,9 +482,9 @@ public function testSetStatus() #[RunInSeparateProcess] public function testSendDataDefaultsToJson() { - $data = array( - 'key1' => 'value1' - ); + $data = [ + 'key1' => 'value1', + ]; ob_start(); $this->sut->sendData($data); @@ -503,9 +503,9 @@ public function testSendDataDefaultsToJson() #[RunInSeparateProcess] public function testSendDataJsonP() { - $data = array( - 'key1' => 'value1' - ); + $data = [ + 'key1' => 'value1', + ]; $this->sut->format = Format::JSONP; $_GET['callback'] = 'callback'; @@ -534,15 +534,15 @@ public function testSendDataJsonPWithoutCallback() $this->sut->format = Format::JSONP; unset($_GET['callback']); - $this->sut->sendData(array()); + $this->sut->sendData([]); } #[RunInSeparateProcess] public function testSendDataXml() { - $data = array( - 'key1' => 'value1' - ); + $data = [ + 'key1' => 'value1', + ]; $this->sut->format = Format::XML; @@ -559,7 +559,7 @@ public function testSendDataXml() // Assert body $this->assertXmlStringEqualsXmlString( 'value1', - $result + $result, ); } @@ -576,7 +576,7 @@ public function testSetRootToEmpty() 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'; @@ -602,8 +602,8 @@ public function testMethodWithLanguageObjectAndData() 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); @@ -626,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); } @@ -659,8 +661,8 @@ public function testaddCorsAllowedHeader() 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); @@ -683,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/UtilitiesTest.php b/tests/UtilitiesTest.php index 74b740a..c033a45 100644 --- a/tests/UtilitiesTest.php +++ b/tests/UtilitiesTest.php @@ -10,9 +10,7 @@ class TestClass { - public function method($param1, stdClass $param2) - { - } + public function method($param1, stdClass $param2) {} } /** @@ -21,7 +19,6 @@ public function method($param1, stdClass $param2) #[CoversClass(Utilities::class)] class UtilitiesTest extends TestCase { - public function testSortByPriority() { $accept_language_str = 'de_DE;q=0.75,de;q=.6,en;q=.2'; @@ -55,7 +52,7 @@ public function testSortByPriorityWithEqualValuesAndReverseLexigraphicalOrder() $this->assertIsArray($result); - $results = array(); + $results = []; foreach ($result as $type => $quality) { $results[] = $type; } @@ -153,9 +150,9 @@ public function testSortByPriorityWithChromeAcceptLanguageString() public function testSimpleArrayToObject() { - $array = array( - 'key1' => 'value1' - ); + $array = [ + 'key1' => 'value1', + ]; $object = Utilities::arrayToObject($array); @@ -165,10 +162,10 @@ public function testSimpleArrayToObject() public function testTwoElementArrayToObject() { - $array = array( + $array = [ 'key1' => 'value1', - 'key2' => 'value2' - ); + 'key2' => 'value2', + ]; $object = Utilities::arrayToObject($array); @@ -180,11 +177,11 @@ public function testTwoElementArrayToObject() public function testNestedArrayToObject() { - $array = array( - 'key1' => array( - 'key2' => 'value' - ) - ); + $array = [ + 'key1' => [ + 'key2' => 'value', + ], + ]; $object = Utilities::arrayToObject($array); @@ -233,7 +230,7 @@ public function testNestedObjectToArray() public function testArrayToXmlWithEmptyArray() { - $array = array(); + $array = []; $xml = Utilities::arrayToXml($array); @@ -242,14 +239,14 @@ 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); @@ -262,12 +259,12 @@ 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); From 9f23e586396b5727cec5033b641ebac9fed21b97 Mon Sep 17 00:00:00 2001 From: jkohl Date: Sun, 1 Nov 2026 11:39:04 +0100 Subject: [PATCH 4/5] Ignore coding style commit in git blame --- .git-blame-ignore-revs | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .git-blame-ignore-revs 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 From 3bfb0cb8556508b9684177849b116301f2b25436 Mon Sep 17 00:00:00 2001 From: jkohl Date: Sun, 1 Nov 2026 14:38:01 +0100 Subject: [PATCH 5/5] Exclude tests from Codacy analysis and wrap README prose Code metrics rules (method count, complexity, superglobal access) do not fit test classes. The former Scrutinizer and Code Climate configs excluded tests/ as well. --- .codacy.yml | 3 +++ .gitattributes | 1 + README.md | 11 +++++++++-- 3 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 .codacy.yml 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/.gitattributes b/.gitattributes index 83364a4..66e6d58 100644 --- a/.gitattributes +++ b/.gitattributes @@ -6,3 +6,4 @@ /.php-cs-fixer.dist.php export-ignore /phpunit.xml export-ignore /README.md export-ignore +/.codacy.yml export-ignore diff --git a/README.md b/README.md index 8d4da67..a5b0ce1 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,16 @@ [![Total Downloads](https://poser.pugx.org/jk/restserver/downloads.svg)](https://packagist.org/packages/jk/restserver) [![Documentation Status](https://readthedocs.org/projects/restserver/badge/?version=develop)](https://readthedocs.org/projects/restserver/?badge=develop) -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. -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. +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. + +[classification]: https://algermissen.io/classification_of_http_apis.html ## Development