JSON Rule provides a simple, rule-based JSON validation implementation for the Aegisora ecosystem.
It is built on top of aegisora/rule-contract and follows its strict validation architecture, ensuring consistent and predictable behavior across applications.
This rule is useful for validating webhook payloads, API request bodies, configuration strings, message queue messages, and any other string that must contain well-formed JSON.
- Features
- Installation
- Core Concept
- Basic Usage
- Valid vs Invalid
- Validation Result
- Guardian Usage
- Real-World Examples
- Factory Methods
- Architecture
- License
- Contributing
- Support
- πΉ Lightweight and dependency-free except
aegisora/rule-contract - πΉ Validates whether a string contains well-formed JSON
- πΉ Backed by native
json_decode()andjson_last_error() - πΉ Accepts any valid JSON value (objects, arrays, strings, numbers, booleans,
null) - πΉ Rejects non-string input as an invalid context
- πΉ Fully compatible with Aegisora validation pipeline
- πΉ Strict
ContextβResultvalidation flow - πΉ No raw booleans β only structured results
- πΉ Safe execution via base
Ruleabstraction - πΉ Simple factory API (create)
- πΉ Ready to use out of the box
composer require aegisora/json-ruleThis package implements a single validation rule:
- accepts a string value via
Context - checks whether the value is well-formed JSON
- returns a standardized
Result
Under the hood it wraps the common boilerplate:
json_decode($value);
if (json_last_error() !== JSON_ERROR_NONE) {
// value is not valid JSON
}into a reusable rule that reports its outcome through a Result object instead of a raw boolean.
use Aegisora\RuleContract\Models\Context;
use Aegisora\Rules\JsonRule;
$result = JsonRule::create()->validate(Context::create('{"name": "Aegisora"}'));
if ($result->isValid()) {
// value is valid JSON
} else {
// value is not valid JSON
}The rule passes for any well-formed JSON value and fails for malformed input. Validation relies on the native JSON parser, so only strictly well-formed JSON is accepted.
$rule = JsonRule::create();
$rule->validate(Context::create('{}')); // valid
$rule->validate(Context::create('[]')); // valid
$rule->validate(Context::create('[1, 2, "foo", null]'));// valid
$rule->validate(Context::create('"Hello"')); // valid
$rule->validate(Context::create('100')); // valid
$rule->validate(Context::create('-5.67')); // valid
$rule->validate(Context::create('true')); // valid
$rule->validate(Context::create('false')); // valid
$rule->validate(Context::create('null')); // valid$rule = JsonRule::create();
$rule->validate(Context::create('')); // invalid β empty string
$rule->validate(Context::create("{'key': 'value'}")); // invalid β single quotes
$rule->validate(Context::create('{key: "value"}')); // invalid β unquoted key
$rule->validate(Context::create('{"a": 1, "b": 2,}')); // invalid β trailing comma
$rule->validate(Context::create('[1, 2, 3,]')); // invalid β trailing comma
$rule->validate(Context::create('TRUE')); // invalid β wrong caseIf the value is valid JSON, the rule returns a valid result.
$result->isValid(); // true
If the value is not valid JSON, the rule returns an invalid result.
$result->isValid(); // false
$result->getFailedRuleCode(); // json_ruleIf the context value is not a string, the rule throws:
Aegisora\RuleContract\Exceptions\InvalidRuleContextException
This rule can be used together with aegisora/guardian to build fluent validation pipelines.
use Aegisora\Guardian\Guardian;
use Aegisora\Rules\JsonRule;
use App\Exceptions\InvalidPayloadException;
$guardian = new Guardian();
$guardian
->that($rawPayload)
->must(JsonRule::create(), new InvalidPayloadException())
->validate();If the value is not valid JSON, Guardian throws the provided domain exception.
JSON Rule is useful for validating string payloads before they are decoded or persisted.
Examples
Webhook:
validate incoming payload body is well-formed JSON
API Gateway:
reject requests whose body is not valid JSON
Configuration:
ensure a JSON config string can be parsed
Message Queue:
validate message payloads before processing
JsonRule::create();
- no arguments β creates a new rule instance
JsonRule::create()->validate($context);
$contextβContextwrapping the string value to validate
This package relies on aegisora/rule-contract.
Flow:
validate()is calledContextis passed in- The string value is extracted from context (non-strings raise
InvalidRuleContextException) - The value is decoded with
json_decode() json_last_error()is checkedResultis returned β valid on success, invalid with thejson_rulecode on failure
All logic is safely handled by Rule contract.
This package is open-source and licensed under the MIT License. See the LICENSE for details.
Contributions are welcome and greatly appreciated! See the CONTRIBUTING for details.
If you find this project useful, please consider giving it a star on GitHub!
It helps the project grow and motivates further development.