PHPackages                             foamzou/easy-json-schema - 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. foamzou/easy-json-schema

ActiveLibrary

foamzou/easy-json-schema
========================

1.0(6y ago)2681PHP

Since Jul 23Pushed 6y ago1 watchersCompare

[ Source](https://github.com/foamzou/easy-json-schema)[ Packagist](https://packagist.org/packages/foamzou/easy-json-schema)[ RSS](/packages/foamzou-easy-json-schema/feed)WikiDiscussions master Synced 2mo ago

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

English | [简体中文](./README.zh-CN.md)

Easy Json Schema
================

[](#easy-json-schema)

> Of course, I recommend you use protobuf.

- Use php object to define Json-Schema easily (support draft-07 and draft-06)
- Use [opis/json-schema](https://github.com/opis/json-schema) as validator

Advantage
---------

[](#advantage)

- Easy to define，avoid complex json-schema
- More readability
- Easier to maintain

Install
-------

[](#install)

`composer require "foamzou/easy-json-schema"`

Usage
-----

[](#usage)

```
use Foamzou\EasyJsonSchema\Manager\Validator;
use Foamzou\EasyJsonSchema\Manager\Parser;
use Foamzou\EasyJsonSchema\Type\{
    Str, Integer
};

// define a schema
$schema = new Obj([
              'name' => (new Integer)->min(2)->max(5),
              'age' => (new Str)->max(120),
          ]);

$data = [
    'name' => 'foam',
    'age' => 18,
];

// generate json-schema
$jsonSchema = Parser::run($schema);

// check is valid with data，errorMessage will return while valid failed
$bool = Validator::getInstance()->isValid($jsonSchema, $data, $errorMessage);

```

Define Schema
-------------

[](#define-schema)

Here's a comparison with json-schema. You can see that the definition of using php objects is simpler, more readable, and easier to maintain.

Easy-Json-Schema

```
new Obj([
    'name'  => (new Integer)->min(2)->max(5),
    'age'   => (new Str)->min(16)->max(120),
    'skill' => (new Arr)->items((new Obj([
        'name'  => (new Str())->min(1)->max(64),
        'value' => (new Num())->min(0)->max(100)->multipleOf(0.25),
    ]))->requiredAll()->additionalProp(false)),
]);

```

Json-Schema

```
{
    "type": "object",
    "properties": {
        "name": {
            "type": "integer",
            "minimum": 2,
            "maximum": 5
        },
        "age": {
            "type": "string",
            "minLength": 16,
            "maxLength": 120
        },
        "skill": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "minLength": 1,
                        "maxLength": 64
                    },
                    "value": {
                        "type": "number",
                        "minimum": 0,
                        "maximum": 100,
                        "multipleOf": 0.25
                    }
                },
                "required": [
                    "name",
                    "value"
                ],
                "additionalProperties": false
            }
        }
    }
}

```

### Data type

[](#data-type)

```
use Foamzou\EasyJsonSchema\Type\{
    Str, Integer, Num, Obj, Boolean, Arr, Nul
};

```

#### String

[](#string)

`(new Str)->min(1)->max(23)->pattern('/regex/')->contentEncoding()->contentMediaType()`

#### Number

[](#number)

```
(new Num)->min(1)->max(20); // >=1 and exMin(1)->exMax(20)->multipleOf(5);// >1 and min(1)->max(20); // >=1 and exMin(1)->exMax(20)->multipleOf(5);// >1 and items(new obj([
    'name'  => new Integer,
    'age'   => new Str,
]))->min('Array length minimum')
    ->max('Array length minimum')
    ->uniq('bool: Whether the element is required to be unique')
    ->additionalItems('extra element')
    ->contains('contains elements');

```

#### Object

[](#object)

```
(new Obj([
    'name' => new Str,
    'age' => new Integer,
    'childObj' => new Obj([ // can be nested
        'newName' => new Str,
        'newAge' => new Integer,
    ])
]))->required(['name', 'age']);

```

### keyword

[](#keyword)

#### Enum

[](#enum)

```
new Enum([1, 2, 3]);

```

#### Constant

[](#constant)

```
new Constant('mustBeMe');

```

#### AnyOf, OneOf, AllOf

[](#anyof-oneof-allof)

```
// new objects
new OneOf([
    new Integer,
    new Str,
]);

// call method
(new Arr())->items(new Integer)->oneOf([
    [
        "items"=> [
            "exclusiveMinimum"=> 0
        ]
    ],
    [
        "items"=> [
            "exclusiveMaximum"=> 0
        ]
    ],
    [
        "items"=> [
            "const"=> 0
        ]
    ]
]);

```

#### not

[](#not)

```
new Not(new Str)

```

#### if.then.else

[](#ifthenelse)

```
// new objects
(new Kif(new Integer()))
    ->then(["minLength" => 3])
    ->else(["const" => 0]);

// call method
(new Obj)->if([
    'properties' => [
        'gender' => new Constant('female')
    ]
])->then([
    'properties' => [
        'gender'    => new Constant('female'),
        'age'       => (new Integer)->min(16),
    ]
])->else([
    'properties' => [
        'gender'    => new Constant('male'),
        'age'       => (new Integer)->min(18),
    ]
]);

```

#### Reuse Schema

[](#reuse-schema)

When a schema need to reuse the other schema, you can use `require`

```
new Obj([
       'name' => (new Str()),
       'location' => require __DIR__ . '/Location.php',
 ]);

```

#### Common Method

[](#common-method)

All objects have a `desc` method to describes the object

```
(new Obj([
    'name' => (new Str)->desc('username'),
    'age' => (new Integer)->desc('user age'),
]))->desc('I am a request object');

```

The object which base `Type` has `default` method to set default value

```
(new Str)->default('jay');

```

Compiling EasyJsonSchema to Json Schema
---------------------------------------

[](#compiling-easyjsonschema-to-json-schema)

```
use Foamzou\EasyJsonSchema\Manager\Parser;

$schema = (new Obj([
              'name' => (new Str)->desc('username'),
              'age' => (new Integer)->desc('user age'),
          ]))->desc('I am a request object');

$jsonSchema = Parser::run($schema);

```

Check data and get error information
------------------------------------

[](#check-data-and-get-error-information)

If data does not match the schema, `isValid` will return false, otherwise it will be true

```
use Foamzou\EasyJsonSchema\Manager\Validator;

$validator = Validator::getInstance();
$isValid = $validator->isValid($jsonSchema, json_encode($data), $errMessage, $errList);

```

$errMessage and $errList has value while `isValid` return false

$errMessage is a semantically string, $errList is an array of items with Opis\\JsonSchema\\ValidationError

You can use $errList to build the error message you want when $errMessage does not you hope

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

2482d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/dbb269ffc982f81c8e07df46e3ce25b59a8565e2202908f4bd4f654772f40bf2?d=identicon)[foamzou](/maintainers/foamzou)

---

Top Contributors

[![foamzou](https://avatars.githubusercontent.com/u/9295077?v=4)](https://github.com/foamzou "foamzou (2 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/foamzou-easy-json-schema/health.svg)

```
[![Health](https://phpackages.com/badges/foamzou-easy-json-schema/health.svg)](https://phpackages.com/packages/foamzou-easy-json-schema)
```

###  Alternatives

[hotmeteor/spectator

Testing helpers for your OpenAPI spec

3021.4M1](/packages/hotmeteor-spectator)[mcp/sdk

Model Context Protocol SDK for Client and Server applications in PHP

1.4k423.9k30](/packages/mcp-sdk)[paragonie/csp-builder

Easily add and update Content-Security-Policy headers for your project

5412.8M18](/packages/paragonie-csp-builder)[akeneo/pim-community-dev

Akeneo PIM, the future of catalog management is open!

1.0k614.1k79](/packages/akeneo-pim-community-dev)[ramsey/conventional-commits

A PHP library for creating and validating commit messages according to the Conventional Commits specification. Includes a CaptainHook action!

1931.2M120](/packages/ramsey-conventional-commits)[php-mcp/server

PHP SDK for building Model Context Protocol (MCP) servers - Create MCP tools, resources, and prompts

828280.5k25](/packages/php-mcp-server)

PHPackages © 2026

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