Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 113 additions & 22 deletions Tests/JsonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,62 @@
use Joomla\Filter\InputFilter;
use Joomla\Input\Json;
use Joomla\Test\TestHelper;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;

/**
* Replaces the php:// stream wrapper so that php://input returns a given body.
*/
class PhpInputStream
{
public static string $body = '';

public $context;

private int $position = 0;

public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool
{
return $path === 'php://input';
}

public function stream_read(int $count): string
{
$chunk = substr(self::$body, $this->position, $count);
$this->position += \strlen($chunk);

return $chunk;
}

public function stream_eof(): bool
{
return $this->position >= \strlen(self::$body);
}

public function stream_stat(): array
{
return [];
}

/**
* Creates a Json input with the given request body.
*/
public static function createJson(string $body): Json
{
self::$body = $body;

stream_wrapper_unregister('php');
stream_wrapper_register('php', self::class);

try {
return new Json();
} finally {
stream_wrapper_restore('php');
}
}
}

/**
* Test class for \Joomla\Input\Json.
*/
Expand Down Expand Up @@ -48,36 +102,73 @@ public function test__constructDependencyInjection()
$this->assertSame($mockFilter, TestHelper::getValue($instance, 'filter'));
}

/**
* @testdox Tests the constructor when reading data from the $GLOBALS
*
* @covers Joomla\Input\Json
* @uses Joomla\Input\Input
*
* @backupGlobals enabled
*/
public function test__constructReadingFromGlobals()
#[TestDox('Tests the constructor when reading data from the request body')]
public function test__constructReadingFromRequestBody()
{
$GLOBALS['HTTP_RAW_POST_DATA'] = '{"a":1,"b":2}';

$instance = new Json();
$instance = PhpInputStream::createJson('{"a":1,"b":2}');

$this->assertSame(['a' => 1, 'b' => 2], TestHelper::getValue($instance, 'data'));
$this->assertInstanceOf(InputFilter::class, TestHelper::getValue($instance, 'filter'), 'The Input object should create an InputFilter if one is not provided');
$this->assertFalse($instance->hasError());
$this->assertNull($instance->getError());
}

/**
* @testdox Tests the constructor when reading data from the $GLOBALS
*
* @covers Joomla\Input\Json
* @uses Joomla\Input\Input
*
* @backupGlobals enabled
*/
public function testgetRaw()
#[TestDox('HTTP_RAW_POST_DATA is not read')]
public function test__constructIgnoresRawPostData()
{
$GLOBALS['HTTP_RAW_POST_DATA'] = '{"a":1,"b":2}';

$this->assertSame($GLOBALS['HTTP_RAW_POST_DATA'], (new Json())->getRaw());
try {
$instance = PhpInputStream::createJson('');
} finally {
unset($GLOBALS['HTTP_RAW_POST_DATA']);
}

$this->assertSame([], TestHelper::getValue($instance, 'data'));
$this->assertSame('', $instance->getRaw());
}

public static function emptyBodiesProvider(): array
{
return [
'empty' => [''],
'whitespace' => [" \n "],
];
}

#[DataProvider('emptyBodiesProvider')]
#[TestDox('An empty request body is not an error')]
public function testEmptyBodyIsNoError(string $body)
{
$instance = PhpInputStream::createJson($body);

$this->assertSame([], TestHelper::getValue($instance, 'data'));
$this->assertFalse($instance->hasError());
}

public static function invalidBodiesProvider(): array
{
return [
'syntax error' => ['{"a":', 'Syntax error'],
'scalar' => ['42', 'The request body is not a JSON object or array'],
'null' => ['null', 'The request body is not a JSON object or array'],
];
}

#[DataProvider('invalidBodiesProvider')]
#[TestDox('A request body that cannot be decoded is reported')]
public function testInvalidBodyIsReported(string $body, string $message)
{
$instance = PhpInputStream::createJson($body);

$this->assertSame([], TestHelper::getValue($instance, 'data'));
$this->assertTrue($instance->hasError());
$this->assertSame($message, $instance->getError());
}

#[TestDox('Tests getting the raw request body')]
public function testgetRaw()
{
$this->assertSame('{"a":1,"b":2}', PhpInputStream::createJson('{"a":1,"b":2}')->getRaw());
}
}
21 changes: 18 additions & 3 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,24 @@ $json->getString('title');
$json->getRaw(); // the undecoded body
```

The body is read and decoded on construction regardless of the request's `Content-Type`. A body
that is not valid JSON yields an empty input rather than an error, so an API cannot distinguish
"malformed JSON" from "no fields sent" — check `getRaw()` if that matters.
The body is read and decoded on construction. A body that cannot be decoded yields an empty input;
`hasError()` tells it apart from an empty body, and `getError()` returns the reason:

```php
$json = new Json();

if ($json->hasError()) {
// e.g. 'Syntax error', or 'The request body is not a JSON object or array' for `42`
// answer with 400 Bad Request and $json->getError()
}
```

An empty (or whitespace-only) body is not an error. A valid JSON scalar such as `42` or `null` is,
because it has no fields to read.

The body is decoded **regardless of the request's `Content-Type`**. A cross-site form can send a
`text/plain` "simple" request whose body is JSON without a CORS preflight, so for endpoints
authenticated by cookies, check that `Content-Type` is `application/json` before acting on the data.

## Not part of this package

Expand Down
78 changes: 67 additions & 11 deletions src/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ class Json extends Input
*/
private $raw;

/**
* The error message if the request body could not be decoded.
*
* @var string|null
* @since __DEPLOY_VERSION__
*/
private ?string $error = null;

/**
* Constructor.
*
Expand All @@ -37,22 +45,70 @@ class Json extends Input
public function __construct($source = null, array $options = [])
{
if ($source === null) {
$this->raw = file_get_contents('php://input');
$this->raw = (string) file_get_contents('php://input');
$source = $this->decode($this->raw);
}

parent::__construct($source, $options);
}

/**
* Checks whether the request body could not be decoded.
*
* An empty body is not an error. A body that is not valid JSON, or that is valid JSON but not an object or an
* array, is.
*
* @return boolean
*
* @since __DEPLOY_VERSION__
*/
public function hasError(): bool
{
return $this->error !== null;
}

/**
* Gets the error message if the request body could not be decoded.
*
* @return string|null The error message, or null if there was no error.
*
* @since __DEPLOY_VERSION__
*/
public function getError(): ?string
{
return $this->error;
}

// This is a workaround for where php://input has already been read.
// See note under php://input on https://www.php.net/manual/en/wrappers.php.php
if (empty($this->raw) && isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
$this->raw = $GLOBALS['HTTP_RAW_POST_DATA'];
}
/**
* Decodes the request body and records any error.
*
* @param string $raw The request body.
*
* @return array The decoded data, an empty array on error.
*
* @since __DEPLOY_VERSION__
*/
private function decode(string $raw): array
{
if (trim($raw) === '') {
return [];
}

$source = json_decode($this->raw, true);
try {
$data = json_decode($raw, true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$this->error = $e->getMessage();

if (!\is_array($source)) {
$source = [];
}
return [];
}

parent::__construct($source, $options);
if (!\is_array($data)) {
$this->error = 'The request body is not a JSON object or array';

return [];
}

return $data;
}

/**
Expand Down
Loading