An original bounded preferences parser
The following PHP 8.x example accepts a small JSON object and returns only approved fields. It is a helper, not a complete import endpoint. The caller must enforce authentication, authorization, request/body limits and an appropriate response on validation failure.
<?php
function parseImportedPreferences(string $body): array
{
if ($body === '' || strlen($body) > 8192) {
throw new InvalidArgumentException('Invalid preferences size.');
}
$decoded = json_decode($body, false, 16, JSON_THROW_ON_ERROR);
if (!$decoded instanceof stdClass) {
throw new InvalidArgumentException('Preferences must be an object.');
}
$fields = get_object_vars($decoded);
if (array_diff(array_keys($fields), ['theme', 'pageSize']) !== []) {
throw new InvalidArgumentException('Unknown preference field.');
}
$theme = $fields['theme'] ?? 'system';
$pageSize = $fields['pageSize'] ?? 20;
if (!is_string($theme)
|| !in_array($theme, ['light', 'dark', 'system'], true)) {
throw new InvalidArgumentException('Invalid theme.');
}
if (!is_int($pageSize)
|| !in_array($pageSize, [20, 50, 100], true)) {
throw new InvalidArgumentException('Invalid page size.');
}
return ['theme' => $theme, 'pageSize' => $pageSize];
}
The json_decode reference documents depth, decoding behavior and JSON_THROW_ON_ERROR. Handle JsonException and validation exceptions at the HTTP boundary with controlled messages. Do not expose an internal stack trace to the visitor.
This contract deliberately treats null like an omitted value because the null-coalescing defaults do so. If the product needs to reject null, distinguish field presence with array_key_exists() and add a corresponding test. Security reviews improve when such behavior is explicit rather than accidental.
From the community
Join the conversation.