PHPackages                             senadir/zod-php-to-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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. senadir/zod-php-to-schema

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

senadir/zod-php-to-schema
=========================

Convert Zod-like PHP objects to JSON Schema definitions

151↓88.9%PHP

Since Feb 5Pushed 1y ago1 watchersCompare

[ Source](https://github.com/senadir/zod-php-to-schema)[ Packagist](https://packagist.org/packages/senadir/zod-php-to-schema)[ RSS](/packages/senadir-zod-php-to-schema/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependenciesVersions (1)Used By (0)

Zod PHP to JSON Schema
======================

[](#zod-php-to-json-schema)

Convert Zod-like PHP schema definitions to JSON Schema. This package provides a fluent API for defining schemas in PHP and converting them to JSON Schema format.

Installation
------------

[](#installation)

```
composer require nadir/zod-php-to-schema
```

Usage
-----

[](#usage)

```
use Zod2Schema\Zod2Schema\Z;
use Zod2Schema\Zod2Schema\Schema;

// By default, fields are not required
$userSchema = Z::object([
    'name' => Z::string()->min(2),
    'age' => Z::number()->min(0)->max(120),
    'email' => Z::string()->email(),
    'tags' => Z::array(Z::string())
])->to_json_schema();

echo json_encode($userSchema, JSON_PRETTY_PRINT);
```

Which will output:

```
{
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            "minLength": 2
        },
        "age": {
            "type": "number",
            "minimum": 0,
            "maximum": 120
        },
        "email": {
            "type": "string",
            "format": "email"
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    }
}
```

You can also enable required fields globally:

```
use Zod2Schema\Zod2Schema\Z;
use Zod2Schema\Zod2Schema\Schema;

// Enable required fields globally
Schema::set_require_all_fields(true);

// Now all fields will be required by default, but you can mark specific fields as optional
$userSchemaWithOptional = Z::object([
    'name' => Z::string()->min(2),           // required
    'age' => Z::number()->optional(),        // optional
    'email' => Z::string()->email(),         // required
    'tags' => Z::array(Z::string())->optional() // optional
])->to_json_schema();

echo json_encode($userSchemaWithOptional, JSON_PRETTY_PRINT);
```

Which will output:

```
{
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            "minLength": 2
        },
        "age": {
            "type": "number",
            "minimum": 0,
            "maximum": 120
        },
        "email": {
            "type": "string",
            "format": "email"
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    },
    "required": ["name", "email"]
}
```

You can also define a union type:

```
// Define a union type
$statusSchema = Z::union([
    Z::literal('active'),
    Z::literal('inactive'),
    Z::literal('pending')
])->to_json_schema();

echo json_encode($statusSchema, JSON_PRETTY_PRINT);
```

Which will output:

```
{
    "anyOf": [
        {
            "type": "string",
            "const": "active"
        },
        {
            "type": "string",
            "const": "inactive"
        },
        {
            "type": "string",
            "const": "pending"
        }
    ]
}
```

Required Fields
---------------

[](#required-fields)

By default, fields are not marked as required in the generated JSON Schema. You can enable required fields globally using:

```
Schema::set_require_all_fields(true);
```

When enabled:

- All fields are required by default
- Use `optional()` to mark specific fields as optional
- This applies to nested objects as well
- The setting can be toggled on/off as needed

Example with optional fields:

```
Schema::set_require_all_fields(true);

$schema = Z::object([
    'id' => Z::number(),          // required
    'name' => Z::string(),        // required
    'nickname' => Z::string()->optional(), // optional
    'contact' => Z::object([
        'email' => Z::string()->email(),   // required
        'phone' => Z::string()->optional() // optional
    ])
])->to_json_schema();
```

Available Schema Types
----------------------

[](#available-schema-types)

- `Z::string()` - String schema with various string-specific validations
- `Z::number()` - Number schema with numeric validations
- `Z::boolean()` - Boolean schema
- `Z::array()` - Array schema with item type definitions
- `Z::object()` - Object schema with property definitions
- `Z::literal()` - Literal value schema
- `Z::union()` - Union type schema

### String Schema Methods

[](#string-schema-methods)

- `min(int $length)` - Minimum string length
- `max(int $length)` - Maximum string length
- `email()` - Email format validation
- `url()` - URL format validation
- `regex(string $pattern)` - Regular expression pattern
- `optional()` - Mark the field as optional

### Number Schema Methods

[](#number-schema-methods)

- `min(float $min)` - Minimum value
- `max(float $max)` - Maximum value
- `int()` - Integer validation
- `positive()` - Positive number validation
- `negative()` - Negative number validation
- `optional()` - Mark the field as optional

### Array Schema Methods

[](#array-schema-methods)

- `min(int $length)` - Minimum array length
- `max(int $length)` - Maximum array length
- `nonempty()` - Array must not be empty
- `optional()` - Mark the field as optional

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance31

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity16

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/9da547cf74479facffd2e3845e8b74ccc69334648c7d9a89f290ee39c84aae36?d=identicon)[senadir](/maintainers/senadir)

---

Top Contributors

[![senadir](https://avatars.githubusercontent.com/u/6165348?v=4)](https://github.com/senadir "senadir (7 commits)")

### Embed Badge

![Health badge](/badges/senadir-zod-php-to-schema/health.svg)

```
[![Health](https://phpackages.com/badges/senadir-zod-php-to-schema/health.svg)](https://phpackages.com/packages/senadir-zod-php-to-schema)
```

###  Alternatives

[mck89/peast

Peast is PHP library that generates AST for JavaScript code

19037.7M41](/packages/mck89-peast)[karriere/json-decoder

JsonDecoder implementation that allows you to convert your JSON data into PHP class objects

140439.4k12](/packages/karriere-json-decoder)[sauladam/shipment-tracker

Parses tracking information for several carriers, like UPS, USPS, DHL and GLS by simply scraping the data. No need for any kind of API access.

9642.0k](/packages/sauladam-shipment-tracker)[jstewmc/rtf

Read and write Rich Text Format (RTF) documents with PHP

46143.1k6](/packages/jstewmc-rtf)[json-mapper/laravel-package

The JsonMapper package for Laravel

25188.9k3](/packages/json-mapper-laravel-package)[moonshine/layouts-field

Field for repeating groups of fields for MoonShine

107.9k](/packages/moonshine-layouts-field)

PHPackages © 2026

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