PHPackages                             mpscl/graphql-php-validation-toolkit - 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. [API Development](/categories/api)
4. /
5. mpscl/graphql-php-validation-toolkit

ActiveLibrary[API Development](/categories/api)

mpscl/graphql-php-validation-toolkit
====================================

Do validation on fields and args for graphql queries and mutations, and dynamically generate user error types

v0.3.0(6y ago)02MITPHPPHP ^7.1

Since Feb 3Pushed 5y agoCompare

[ Source](https://github.com/mpscl/graphql-php-validation-toolkit)[ Packagist](https://packagist.org/packages/mpscl/graphql-php-validation-toolkit)[ Docs](https://github.com/shmax/graphql-php-validation-toolkit)[ RSS](/packages/mpscl-graphql-php-validation-toolkit/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (8)Versions (9)Used By (0)

graphql-php-validation-toolkit
==============================

[](#graphql-php-validation-toolkit)

[![Build Status](https://camo.githubusercontent.com/ec489fb229e84d456d4cd53d684ee7caf8e06265f849eb28a9f6b2be5c7c7e90/68747470733a2f2f7472617669732d63692e6f72672f73686d61782f6772617068716c2d7068702d76616c69646174696f6e2d746f6f6c6b69742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/shmax/graphql-php-validation-toolkit)[![Code Coverage](https://camo.githubusercontent.com/e62f9e4694c313abcd5695c51283e09f5931cbcd4d79778541a8b3ef4e137f21/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f73686d61782f6772617068716c2d7068702d76616c69646174696f6e2d746f6f6c6b69742f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/shmax/graphql-php-validation-toolkit/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/efb08a4333f3a7a62b6d1d132fa6cc7dd4462cc0b2ad6894b3a86b6aa5bbdde4/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f73686d61782f6772617068716c2d7068702d76616c69646174696f6e2d746f6f6c6b69742f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/shmax/graphql-php-validation-toolkit/?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/af8d13d6be552d833b77ad5d25357920f2aad79ab192e0f9cc75997e6d694ffd/68747470733a2f2f706f7365722e707567782e6f72672f73686d61782f6772617068716c2d7068702d76616c69646174696f6e2d746f6f6c6b69742f762f737461626c65)](https://packagist.org/packages/shmax/graphql-php-validation-toolkit)[![License](https://camo.githubusercontent.com/0fc9bdffe74cf96df6b7d110dcd79d45f783c87e47791b9022410c3b235d04f6/68747470733a2f2f706f7365722e707567782e6f72672f73686d61782f6772617068716c2d7068702d76616c69646174696f6e2d746f6f6c6b69742f6c6963656e7365)](https://packagist.org/packages/shmax/graphql-php-validation-toolkit)

GraphQL is great when it comes to validating types and checking syntax, but isn't much help when it comes to providing additional validation on user input. The authors of GraphQL have generally opined that the correct response to bad user input is not to throw an exception, but rather to return any validation feedback along with the result.

As Lee Byron explains [here](https://github.com/facebook/graphql/issues/117#issuecomment-170180628):

> ...allow for data for a user-facing report in the payload of your mutation. It's often the case that mutation payloads include a "didSucceed" field and a "userError" field. If your UI requires rich information about potential errors, then you should include this information in your payload as well.

That's where this small library comes in.

`graphql-php-validation-toolkit` extends the built-in definitions provided by the wonderful [graphql-php](https://github.com/webonyx/graphql-php) library with a new `ValidatedFieldDefinition` class. Simply instantiate one of these in place of the usual field config, add `validate` callback properties to your `args` definitions, and the `type` of your field will be replaced by a new, dynamically-generated `ResultType` with queryable error fields for each of your args. It's a recursive process, so your `args` can have `InputObjectType` types with subfields and `validate` callbacks of their own. Your originally-defined `type` gets moved to the `result` field of the generated type.

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

[](#installation)

Via composer:

```
composer require shmax/graphql-php-validation-toolkit

```

Documentation
-------------

[](#documentation)

- [Basic Usage](#basic-usage)
- [The Validate Callback](#the-validate-callback)
- [Custom Error Codes](#custom-error-codes)
- [Managing Created Types](#managing-created-types)
- [Examples](#examples)

### Basic Usage

[](#basic-usage)

In a nutshell, replace your usual vanilla field definition with an instance of `ValidatedFieldDefinition`, and add `validate` callbacks to one or more of the `args` configs. Let's say you want to make a mutation called `updateBook`:

```
//...
'updateBook' => new ValidatedFieldDefinition([
   'name' => 'updateBook',
   'type' => Types::book(),
   'args' => [
       'bookId' => [
           'type' => Type::id(),
           'validate' => function ($bookId) {
               global $books;
               if (!Book::find($bookId) {
                   return 0;
               }

               return [1, 'Unknown book!'];
           },
       ],
   ],
   'resolve' => static function ($value, $args) : bool {
       return Book::find($args['bookId']);
   },
],
```

In the sample above, the `book` type property of your field definition will be replaced by a new dynamically-generated type called `UpdateBookResultType`.

The type generation process is recursive, traveling down through any nested `InputObjectType` or `ListOf` types and checking their `fields` for more `validate` callbacks. Every field definition--including the very top one--that has a `validate` callback will be represented by a custom, generated type with the following queryable fields:

FieldTypeDescription`code``int` | `ErrorCode`This will resolve to `0` for a valid field, otherwise `1`. If `errorCodes` were provided, then this will be a custom generated Enum type.`msg``string`A plain, natural language description of the error.`suberrors``_Suberrors`A `suberrors` field will be added to a generated field of type `InputObjectType` if any of the following are true: 1. It is the root node
2. The field has a `validate` method
3. The `InputObjectType` is wrapped in a `ListOfType`

The top-level `ResultType` will have a few additional fields:

FieldTypeDescription`valid``bool`Resolves to `true` if all `args` and nested `fields` pass validation, `false` if not.`result``mixed`This is the original `type` you provided when declaring your field. Eg, If you specified `type` to be a `Book`, then the type of `result` will be `Book`.You can then simply query for these fields along with `result`:

```
mutation {
    updateAuthor(
        authorId: 1
  ) {
    valid
    result {
        id
        name
    }
    code
    msg
    suberrors {
        authorId {
            code
            msg
        }
    }
  }
}
```

### The Validate Callback

[](#the-validate-callback)

Any field definition can have a `validate` callback. The first argument passed to the `validate` callback will be the value to validate. If the value is valid, return `0`, otherwise `1`.

```
//...
'updateAuthor' => new ValidatedFieldDefinition([
  'type' => Types::author(),
  'args' => [
    'authorId' => [
      'validate' => function(string $authorId) {
        if(Author::find($authorId)) {
          return 0;
        }
        return 1;
      }
    ]
  ]
])
```

If you want to return an error message, return an array with the message in the second bucket:

```
//...
'updateAuthor' => new ValidatedFieldDefinition([
  'type' => Types::author(),
  'args' => [
    'authorId' => [
      'validate' => function(string $authorId) {
        if(Author::find($authorId)) {
          return 0;
        }
        return [1, "We can't find that author"];
      }
    ]
  ]
])
```

Generated `ListOf` error types also have a `path` field that you can query so you can know the exact address in the multidimensional array of each item that failed validation:

```
//...
'setPhoneNumbers' => new ValidatedFieldDefinition([
  'type' => Types::bool(),
  'args' => [
    'phoneNumbers' => [
      'type' => Type::listOf(Type::string()),
      'validate' => function(string $phoneNumber) {
        $res = preg_match('/^[0-9\-]+$/', $phoneNumber) === 1;
        if (!$res) {
          return [1, 'That does not seem to be a valid phone number'];
        }
        return 0;
      }
    ]
  ]
])
```

### Custom Error Codes

[](#custom-error-codes)

If you would like to use custom error codes, add an `errorCodes` property at the same level as your `validate` callback:

```
//...
'updateAuthor' => [
  'type' => Types::author(),
  'errorCodes' => [
    'authorNotFound`
  ],
  'validate' => function(string $authorId) {
    if(Author::find($authorId)) {
      return 1;
    }
    return ['authorNotFound', "We can't find that author"];
  }
]
```

### Managing Created Types

[](#managing-created-types)

This library will create new types as needed. If you are using some kind of type manager to store and retrieve types, you can integrate it by providing a `typeSetter` callback:

```
new ValidatedFieldDefinition([
    'typeSetter' => static function ($type) {
        Types::set($type);
    },
]);
```

Examples
--------

[](#examples)

The best way to understand how all this works is to experiment with it. There are a series of increasingly complex one-page samples in the `/examples` folder. Each is accompanied by its own `README.md`, with instructions for running the code. Run each sample, and be sure to inspect the dynamically-generated types in [ChromeiQL](https://chrome.google.com/webstore/detail/chromeiql/fkkiamalmpiidkljmicmjfbieiclmeij?hl=en).

1. [basic-scalar-validation](./examples/01-basic-scalar-validation)
2. [custom-error-types](./examples/02-custom-error-codes)
3. [input-object-validation](./examples/03-input-object-validation)
4. [list-of-validation](./examples/04-list-of-validation)

Contribute
----------

[](#contribute)

Contributions are welcome. Please refer to [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity2

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 95.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 ~50 days

Recently: every ~60 days

Total

6

Last Release

2409d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1383822?v=4)[mpascale](/maintainers/mpascale)[@mpascale](https://github.com/mpascale)

---

Top Contributors

[![shmax](https://avatars.githubusercontent.com/u/773172?v=4)](https://github.com/shmax "shmax (22 commits)")[![mpscl](https://avatars.githubusercontent.com/u/5705919?v=4)](https://github.com/mpscl "mpscl (1 commits)")

---

Tags

phpmutationvalidationgraphqluser errors

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mpscl-graphql-php-validation-toolkit/health.svg)

```
[![Health](https://phpackages.com/badges/mpscl-graphql-php-validation-toolkit/health.svg)](https://phpackages.com/packages/mpscl-graphql-php-validation-toolkit)
```

PHPackages © 2026

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