PHPackages                             heliostat/safe-json - 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. heliostat/safe-json

ActiveLibrary

heliostat/safe-json
===================

Safe and strict JSON parsing via declarative schema classes

00PHP

Since Jul 16Pushed 10mo agoCompare

[ Source](https://github.com/Heliostat9/SafeJson)[ Packagist](https://packagist.org/packages/heliostat/safe-json)[ RSS](/packages/heliostat-safe-json/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

SafeJson
========

[](#safejson)

**Безопасный и строгий парсинг JSON в PHP через декларативные схемы.**

- ✅ Простые в написании схемы как классы
- ✅ Безопасная типизация
- ✅ Значения по умолчанию и `required`
- ✅ Вложенные схемы
- ✅ Генерация строго типизированных DTO

---

🔧 Установка
-----------

[](#-установка)

```
composer require heliostat/safe-json
```

Для разработки:

```
composer require --dev phpunit/phpunit friendsofphp/php-cs-fixer phpstan/phpstan captainhook/captainhook
vendor/bin/captainhook install
```

---

🚀 Быстрый старт
---------------

[](#-быстрый-старт)

### 1. Определите DTO

[](#1-определите-dto)

```
class User
{
    public function __construct(
        public int $id,
        public string $email,
        public string $name,
        public bool $is_active,
        public Settings $settings
    ) {}
}

class Settings
{
    public function __construct(
        public bool $notifications
    ) {}
}
```

---

### 2. Создайте схемы

[](#2-создайте-схемы)

```
use SafeJson\JsonSchema;

class UserSchema extends JsonSchema
{
    public function rules(): array
    {
        return [
            'id' => self::int()->required(),
            'email' => self::string()->required(),
            'name' => self::string()->default('Anonymous'),
            'is_active' => self::bool()->default(false),
            'settings' => self::object(SettingsSchema::class)->required(),
        ];
    }

    public function cast(): User
    {
        return new User(
            $this->id,
            $this->email,
            $this->name,
            $this->is_active,
            $this->settings->cast()
        );
    }
}

class SettingsSchema extends JsonSchema
{
    public function rules(): array
    {
        return [
            'notifications' => self::bool()->default(true),
        ];
    }

    public function cast(): Settings
    {
        return new Settings($this->notifications);
    }
}
```

---

### 3. Использование

[](#3-использование)

```
$json = settings->notifications ? 'yes' : 'no'; // no
```

---

⚙️ Возможности
--------------

[](#️-возможности)

- `int()`, `string()`, `bool()`, `object(Schema::class)`
- `->required()`, `->default(...)`
- Поддержка вложенных объектов
- Генерация безопасных DTO через `cast()`

---

🧪 Команды разработчика
----------------------

[](#-команды-разработчика)

```
composer fix        # Линтер
composer stan       # Статическая проверка
composer test       # Юнит-тесты
composer hook:run   # Pre-commit hook
```

---

🪝 CaptainHook
-------------

[](#-captainhook)

Пример `.captainhook.json` для pre-commit:

```
{
  "pre-commit": {
    "enabled": true,
    "actions": [
      { "action": "composer fix" },
      { "action": "composer stan" },
      { "action": "composer test" }
    ]
  }
}
```

---

📦 Планы на будущее
------------------

[](#-планы-на-будущее)

- `float()`, `arrayOf(...)`, `enum([...])`
- `min`, `max`, `regex` правила
- Генерация схем или DTO из JSON
- Автогенерация документации

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance40

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity14

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/934d8d9a58fecd8183109ef557286a9965468ad02c46f8bb2a9c7f46d6c5edec?d=identicon)[Heliostat9](/maintainers/Heliostat9)

---

Top Contributors

[![Heliostat9](https://avatars.githubusercontent.com/u/50440329?v=4)](https://github.com/Heliostat9 "Heliostat9 (3 commits)")

### Embed Badge

![Health badge](/badges/heliostat-safe-json/health.svg)

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

PHPackages © 2026

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