PHPackages                             facile-it/php-codec - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. facile-it/php-codec

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

facile-it/php-codec
===================

A partial porting of io-ts in PHP

0.0.4(8mo ago)106.7k4[6 issues](https://github.com/facile-it/php-codec/issues)[7 PRs](https://github.com/facile-it/php-codec/pulls)MITPHPPHP ^7.4 | ^8.0CI passing

Since Apr 27Pushed 8mo ago3 watchersCompare

[ Source](https://github.com/facile-it/php-codec)[ Packagist](https://packagist.org/packages/facile-it/php-codec)[ RSS](/packages/facile-it-php-codec/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (4)Dependencies (7)Versions (13)Used By (0)

PHP-codec
=========

[](#php-codec)

PHP-codec is a partial porting of [io-ts](https://github.com/gcanti/io-ts) in PHP.

[![Minimum PHP Version](https://camo.githubusercontent.com/0e9ac047546796cfdbe1423d1f4d91c8f37d2fbb11614a7900bb7686aaa5401f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230372e342d3838393242462e737667)](https://php.net/)

[![CI](https://github.com/facile-it/php-codec/actions/workflows/ci.yaml/badge.svg?branch=master&event=push)](https://github.com/facile-it/php-codec/actions/workflows/ci.yaml)[![Static analysis](https://github.com/facile-it/php-codec/actions/workflows/static-analysis.yaml/badge.svg?branch=master&event=push)](https://github.com/facile-it/php-codec/actions/workflows/static-analysis.yaml)[![codecov](https://camo.githubusercontent.com/cd71a9b09143882af343cd4bffc5aa07bc48d73be2f0880cc45ae434c22c32b0/68747470733a2f2f636f6465636f762e696f2f67682f666163696c652d69742f7068702d636f6465632f6272616e63682f6d61737465722f67726170682f62616467652e7376673f746f6b656e3d4850344f464545505936)](https://codecov.io/gh/facile-it/php-codec) [![Join the chat at https://gitter.im/php-codec/community](https://camo.githubusercontent.com/8f013c824c3159852846c3ee7c00fdf089824b270f4e20101a5c4ab6e08ef5aa/68747470733a2f2f6261646765732e6769747465722e696d2f7068702d636f6465632f636f6d6d756e6974792e737667)](https://gitter.im/php-codec/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Install it now. It only requires PHP &gt;= 7.4.

```
composer require facile-it/php-codec

```

Disclaimer
==========

[](#disclaimer)

This project is under active development: it's unstable and still poorly documented. The API is likely to change several times, and it won't be ready for production soon.

The project follows [semantic versioning](https://semver.org/).

Introduction
============

[](#introduction)

This project is a partial porting of the fantastic [io-ts](https://github.com/gcanti/io-ts) library for Typescript. Everything rounds about the concept of decoder, encoder and codec.

Decoders are capable of transform values from one type to another one. This transformation may fail.

```
use Facile\PhpCodec\Validation\Validation;

/**
 * @psalm-template I
 * @psalm-template A
 */
interface Decoder {
     /**
     * @psalm-param I $i
     * @psalm-return Validation
     */
    public function decode($i): Validation;

    /** ... */
}
```

Encoders do a similar transformation but between types such that it cannot fail.

```
/**
 * @psalm-template A
 * @psalm-template O
 */
interface Encoder
{
    /**
     * @psalm-param A $a
     * @psalm-return O
     */
    public function encode($a);
}
```

Codecs are a combination of a decoder and an encoder, putting together their features.

I recommend reading the [The Idea](https://github.com/gcanti/io-ts/blob/master/index.md#the-idea) section from the documentation of io-ts. It starts with a beautiful description of what codecs are.

> A value of type `Type` (called "codec") is the run time representation of the static type `A`.

Getting started
===============

[](#getting-started)

```
composer require facile-it/php-codec

```

Decoders
--------

[](#decoders)

Decoders are objects with decoding capabilities. A decoder of type `Decoder` takes an input of type `I` and builds a result of type `Validation`.

The class `Facile\PhpCodec\Decoders` provides factory methods for built-in decoders and combinators.

### How to use decoders

[](#how-to-use-decoders)

```
use Facile\PhpCodec\Decoders;
use Facile\PhpCodec\Decoder;
use Facile\PhpCodec\Validation\Validation;
use Facile\PhpCodec\Validation\ValidationFailures;
use Facile\PhpCodec\Validation\ValidationSuccess;

/** @var Decoder $decoder */
$decoder = Decoders::intFromString();

/** @var Validation $v1 */
$v1 = $decoder->decode('123');
// Since '123' is a numeric string which represents an integer,
// then we can expect the decoding to be successful.
// Hence, $v1 will be an instance of ValidationSuccess

if($v1 instanceof ValidationSuccess) {
    var_dump($v1->getValue());
}

/** @var Validation $v2 */
$v2 = $decoder->decode('hello');
// Similarly, since 'hello' is not a numeric string, we expect
// the decoding fail. $v2 will be an instance of ValidationError

if($v2 instanceof ValidationFailures) {
    var_dump($v2->getErrors());
}
```

### Dealing with the validation result

[](#dealing-with-the-validation-result)

We can use `Validation::fold` to destruct the validation result while providing a valid result in any case.

```
use Facile\PhpCodec\Decoders;
use Facile\PhpCodec\Decoder;
use Facile\PhpCodec\Validation\Validation;

/** @var Decoder $decoder */
$decoder = Decoders::intFromString();

Validation::fold(
    function (\Facile\PhpCodec\Validation\ValidationFailures $failures): int {
        // I may not care about the error.
        // Here I want to give a default value when the deconding fails.
        return 0;
    },
    function (\Facile\PhpCodec\Validation\ValidationSuccess $success): int {
        return $success->getValue();
    },
    $decoder->decode($input)
);
```

You can use the path reporter to build well-formatted error messages for failures.

```
use Facile\PhpCodec\Decoders;

$decoder = Decoders::intFromString();
$v = $decoder->decode('hello');
$msgs = \Facile\PhpCodec\Reporters::path()->report($v);

var_dump($msgs);
/* This will print
array(1) {
  [0] =>
  string(49) "Invalid value "hello" supplied to : IntFromString"
}
*/
```

Examples
--------

[](#examples)

Take a look to the [examples](https://github.com/facile-it/php-codec/tree/master/tests/examples) folder.

Reporters
=========

[](#reporters)

Reporters do create reports from `Validation` objects. Generally speaking, reporters are objects that implement the `Reporter` interface, given `T` the type of the report that the generate.

One interesting group of reporters is the validation error reporters group. They implements `Reporter`. Thus, given a `Validation` object, they generate a list of error messages for each validation error.

PHP-Codec comes with two error reporters:

- PathReporter, which is a pretty straightforward porting of io-ts' [PathReporter](https://github.com/gcanti/io-ts/blob/master/index.md#error-reporters).
- SimplePathReporter, which is a simplified (read: shorter messages) version of the PathReporter.

```
$d = Decoders::arrayProps([
  'a' => Decoders::arrayProps([
    'a1' => Decoders::int(),
    'a2' => Decoders::string(),
  ]),
  'b' => Decoders::arrayProps(['b1' => Decoders::bool()])
]);
$v = $d->decode(['a'=> ['a1' => 'str', 'a2' => 1], 'b' => 2]);

$x = \Facile\PhpCodec\Reporters::path()->report($v);
// $x will be
// ['Invalid value "str" supplied to : {a: {a1: int, a2: string}, b: {b1: bool}}/a: {a1: int, a2: string}/a1: int',
//  'Invalid value 1 supplied to : {a: {a1: int, a2: string}, b: {b1: bool}}/a: {a1: int, a2: string}/a2: string',
//  'Invalid value undefined supplied to : {a: {a1: int, a2: string}, b: {b1: bool}}/b: {b1: bool}/b1: bool']

$y = \Facile\PhpCodec\Reporters::simplePath()->report($v);
// $y will be
// ['/a/a1: Invalid value "str" supplied to decoder "int"',
//  '/a/a2: Invalid value 1 supplied to decoder "string"',
//  '/b/b1: Invalid value undefined supplied to decoder "bool"']
```

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance49

Moderate activity, may be stable

Popularity29

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

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

Every ~534 days

Total

4

Last Release

246d ago

PHP version history (2 changes)0.0.1PHP ^7.2 | ^8.0

0.0.4PHP ^7.4 | ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/907e0b1752610a3cf00ef5d5a1535b02a911647e36a1bea93cc282eeaea6ced5?d=identicon)[ilario-pierbattista](/maintainers/ilario-pierbattista)

---

Top Contributors

[![ilario-pierbattista](https://avatars.githubusercontent.com/u/987038?v=4)](https://github.com/ilario-pierbattista "ilario-pierbattista (46 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (19 commits)")[![emnlmn](https://avatars.githubusercontent.com/u/32902406?v=4)](https://github.com/emnlmn "emnlmn (2 commits)")[![Jean85](https://avatars.githubusercontent.com/u/6729988?v=4)](https://github.com/Jean85 "Jean85 (2 commits)")[![gitter-badger](https://avatars.githubusercontent.com/u/8518239?v=4)](https://github.com/gitter-badger "gitter-badger (1 commits)")

---

Tags

decoderio-tsphp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm, Rector

Type Coverage Yes

### Embed Badge

![Health badge](/badges/facile-it-php-codec/health.svg)

```
[![Health](https://phpackages.com/badges/facile-it-php-codec/health.svg)](https://phpackages.com/packages/facile-it-php-codec)
```

###  Alternatives

[phinq/phinq

A library for querying data and performing statistical operations in an logical, object-oriented fashion.

108.8k](/packages/phinq-phinq)

PHPackages © 2026

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