From dbd99ccdea30060d352f79f256f07a28143611b5 Mon Sep 17 00:00:00 2001 From: Jerome Bakker Date: Tue, 16 Feb 2021 10:49:36 +0100 Subject: [PATCH] chore(response): ensure string output in responses --- engine/classes/Elgg/Http/ResponseFactory.php | 11 +++++-- .../Elgg/Http/ResponseFactoryUnitTest.php | 30 ++++++++++++++++++- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/engine/classes/Elgg/Http/ResponseFactory.php b/engine/classes/Elgg/Http/ResponseFactory.php index c7ebe1f435a..22d57c49d9a 100644 --- a/engine/classes/Elgg/Http/ResponseFactory.php +++ b/engine/classes/Elgg/Http/ResponseFactory.php @@ -675,12 +675,19 @@ public function normalize($content = '') { */ public function stringify($content = '') { $content = $this->normalize($content); - if (empty($content) || (is_object($content) && is_callable([$content, '__toString']))) { + + if (is_object($content) && is_callable([$content, '__toString'])) { return (string) $content; } + if (is_scalar($content)) { - return $content; + return (string) $content; } + + if (empty($content)) { + return ''; + } + return json_encode($content, ELGG_JSON_ENCODING); } diff --git a/engine/tests/phpunit/unit/Elgg/Http/ResponseFactoryUnitTest.php b/engine/tests/phpunit/unit/Elgg/Http/ResponseFactoryUnitTest.php index 0323fe0da42..d27dbb77b84 100644 --- a/engine/tests/phpunit/unit/Elgg/Http/ResponseFactoryUnitTest.php +++ b/engine/tests/phpunit/unit/Elgg/Http/ResponseFactoryUnitTest.php @@ -387,7 +387,7 @@ public function testCanParseContext($path, $expected) { $this->assertEquals($expected, $service->parseContext()); } - function requestContextDataProvider() { + public function requestContextDataProvider() { return [ ['ajax/view/foo/bar/', 'view:foo/bar'], ['ajax/form/foo/bar/baz/', 'form:foo/bar/baz'], @@ -400,4 +400,32 @@ function requestContextDataProvider() { ]; } + /** + * @dataProvider stringifyProvider + */ + public function testStringify($input, $expected_output) { + $this->createService(); + + $this->assertEquals($expected_output, $this->response_factory->stringify($input)); + } + + public function stringifyProvider() { + $std = new \stdClass(); + $std->foo = 'bar'; + + return [ + ['foo', 'foo'], + [['foo'], '["foo"]'], + ['', ''], + [[], ''], + [false, ''], + [true, '1'], + [0, '0'], + [0.0, '0'], + [0.1, '0.1'], + [null, ''], + [new \stdClass(), '{}'], + [$std, '{"foo":"bar"}'], + ]; + } }