Skip to content

Commit

Permalink
Merge pull request #13402 from jeabakker/response
Browse files Browse the repository at this point in the history
chore(response): ensure string output in responses
  • Loading branch information
jdalsem committed Feb 16, 2021
2 parents c90a56d + dbd99cc commit 216e72f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
11 changes: 9 additions & 2 deletions engine/classes/Elgg/Http/ResponseFactory.php
Expand Up @@ -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);
}

Expand Down
30 changes: 29 additions & 1 deletion engine/tests/phpunit/unit/Elgg/Http/ResponseFactoryUnitTest.php
Expand Up @@ -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'],
Expand All @@ -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"}'],
];
}
}

0 comments on commit 216e72f

Please sign in to comment.