PHPackages                             aegisora/json-rule - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. aegisora/json-rule

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

aegisora/json-rule
==================

JSON Rule provides a simple, rule-based JSON validation implementation for the Aegisora ecosystem.

v1.0.0(today)01↑2900%MITPHPPHP &gt;=7.4

Since Aug 8Pushed todayCompare

[ Source](https://github.com/Aegisora/json-rule)[ Packagist](https://packagist.org/packages/aegisora/json-rule)[ Docs](https://github.com/Aegisora/json-rule)[ RSS](/packages/aegisora-json-rule/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (4)Versions (2)Used By (0)

Aegisora JSON Rule
==================

[](#aegisora-json-rule)

[![Latest Version](https://camo.githubusercontent.com/2e87e949f93a6268cb5909fbd13072b82f9c999cbc0cc1ac72b0db8ef9a83128/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f61656769736f72612f6a736f6e2d72756c653f7374796c653d666c61742d737175617265)](https://packagist.org/packages/aegisora/json-rule)[![Total Downloads](https://camo.githubusercontent.com/b64195b1af35b463927175181d0bb41453a6db597ab323d0adcf9f92315a58a9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f61656769736f72612f6a736f6e2d72756c653f7374796c653d666c61742d737175617265)](https://packagist.org/packages/aegisora/json-rule)[![Code Coverage Badge](./badge.svg)](./badge.svg)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![PHPStan Badge](https://camo.githubusercontent.com/83dd3d35cebed0eab9ee97ff1a5849c1344cda6a8ee9cac2cda20f5aa55b67bd/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230392d627269676874677265656e2e7376673f7374796c653d666c6174)](https://camo.githubusercontent.com/83dd3d35cebed0eab9ee97ff1a5849c1344cda6a8ee9cac2cda20f5aa55b67bd/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230392d627269676874677265656e2e7376673f7374796c653d666c6174)

JSON Rule provides a simple, rule-based JSON validation implementation for the Aegisora ecosystem.

It is built on top of [`aegisora/rule-contract`](https://github.com/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.

---

📑 Table of Contents
-------------------

[](#-table-of-contents)

- [Features](#-features)
- [Installation](#-installation)
- [Core Concept](#-core-concept)
- [Basic Usage](#-basic-usage)
- [Valid vs Invalid](#-valid-vs-invalid)
- [Validation Result](#-validation-result)
- [Guardian Usage](#-guardian-usage)
- [Real-World Examples](#-real-world-examples)
- [Factory Methods](#-factory-methods)
- [Architecture](#-architecture)
- [License](#-license)
- [Contributing](#-contributing)
- [Support](#-support)

---

✨ Features
----------

[](#-features)

- 🔹 Lightweight and dependency-free except `aegisora/rule-contract`
- 🔹 Validates whether a string contains well-formed JSON
- 🔹 Backed by native `json_decode()` and `json_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` → `Result` validation flow
- 🔹 No raw booleans — only structured results
- 🔹 Safe execution via base `Rule` abstraction
- 🔹 Simple factory API (create)
- 🔹 Ready to use out of the box

---

📦 Installation
--------------

[](#-installation)

```
composer require aegisora/json-rule
```

---

🚀 Core Concept
--------------

[](#-core-concept)

This 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.

---

🏗️ Basic Usage
--------------

[](#️-basic-usage)

```
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
}
```

---

✅ Valid vs Invalid
------------------

[](#-valid-vs-invalid)

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.

### Valid JSON

[](#valid-json)

```
$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
```

### Invalid JSON

[](#invalid-json)

```
$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 case
```

---

🧪 Validation Result
-------------------

[](#-validation-result)

If 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_rule
```

If the context value is not a string, the rule throws:

`Aegisora\RuleContract\Exceptions\InvalidRuleContextException`

---

🔗 Guardian Usage
----------------

[](#-guardian-usage)

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.

---

🧭 Real-World Examples
---------------------

[](#-real-world-examples)

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

```

---

🧩 Factory Methods
-----------------

[](#-factory-methods)

`JsonRule::create();`

- no arguments — creates a new rule instance

`JsonRule::create()->validate($context);`

- `$context` — `Context` wrapping the string value to validate

---

🏛️ Architecture
---------------

[](#️-architecture)

This package relies on [`aegisora/rule-contract`](https://github.com/Aegisora/rule-contract).

Flow:

1. `validate()` is called
2. `Context` is passed in
3. The string value is extracted from context (non-strings raise `InvalidRuleContextException`)
4. The value is decoded with `json_decode()`
5. `json_last_error()` is checked
6. `Result` is returned — valid on success, invalid with the `json_rule` code on failure

All logic is safely handled by Rule contract.

---

⚖️ License
----------

[](#️-license)

This package is open-source and licensed under the MIT License. See the [LICENSE](LICENSE) for details.

---

🌱 Contributing
--------------

[](#-contributing)

Contributions are welcome and greatly appreciated! See the [CONTRIBUTING](CONTRIBUTING.md) for details.

---

🌟 Support
---------

[](#-support)

If you find this project useful, please consider giving it a star on GitHub!

It helps the project grow and motivates further development.

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance100

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity33

Early-stage or recently created project

 Bus Factor1

Top contributor holds 80.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

0d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/81402dcd0a07ad550b7f80f5871e7c302770b29d4c73a52fc35ba697f702d56e?d=identicon)[arslanim](/maintainers/arslanim)

---

Top Contributors

[![arslanim](https://avatars.githubusercontent.com/u/22678154?v=4)](https://github.com/arslanim "arslanim (62 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (15 commits)")

---

Tags

aegisoraaegisora-ecosystemjsonjson-validationphprulesvalidationvalidatorphpjsonvalidatorvalidationrulejson-validationaegisoraaegisora-ecosystem

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/aegisora-json-rule/health.svg)

```
[![Health](https://phpackages.com/badges/aegisora-json-rule/health.svg)](https://phpackages.com/packages/aegisora-json-rule)
```

###  Alternatives

[codezero/laravel-unique-translation

Check if a translated value in a JSON column is unique in the database.

1901.1M8](/packages/codezero-laravel-unique-translation)[illuminatech/validation-composite

Allows uniting several validation rules into a single one for easy re-usage

180544.2k](/packages/illuminatech-validation-composite)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
