PHPackages                             rnd-cosoft/api-tools-content-validation - 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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. rnd-cosoft/api-tools-content-validation

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

rnd-cosoft/api-tools-content-validation
=======================================

Laminas module providing incoming content validation

1.13.1(2y ago)01.4k12BSD-3-ClausePHPPHP ~8.1.0 || ~8.2.0 || ~8.3.0

Since Dec 31Pushed 2y agoCompare

[ Source](https://github.com/rnd-cosoft/api-tools-content-validation)[ Packagist](https://packagist.org/packages/rnd-cosoft/api-tools-content-validation)[ Docs](https://api-tools.getlaminas.org)[ RSS](/packages/rnd-cosoft-api-tools-content-validation/feed)WikiDiscussions 1.13.x Synced 1mo ago

READMEChangelog (2)Dependencies (17)Versions (39)Used By (2)

Laminas Content Validation
==========================

[](#laminas-content-validation)

[![Build Status](https://github.com/laminas-api-tools/api-tools-content-validation/actions/workflows/continuous-integration.yml/badge.svg)](https://github.com/laminas-api-tools/api-tools-content-validation/actions/workflows/continuous-integration.yml)

> ## 🇷🇺 Русским гражданам
>
> [](#-русским-гражданам)
>
> Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.
>
> У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.
>
> Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"
>
> ## 🇺🇸 To Citizens of Russia
>
> [](#-to-citizens-of-russia)
>
> We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.
>
> One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.
>
> You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

Introduction
------------

[](#introduction)

Laminas module for automating validation of incoming input.

Allows the following:

- Defining named input filters.
- Mapping named input filters to named controller services.
- Returning an `ApiProblemResponse` with validation error messages on invalid input.

Requirements
------------

[](#requirements)

Please see the [composer.json](composer.json) file.

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

[](#installation)

Run the following `composer` command:

```
$ composer require laminas-api-tools/api-tools-content-validation
```

Alternately, manually add the following to your `composer.json`, in the `require` section:

```
"require": {
    "laminas-api-tools/api-tools-content-validation": "^1.4"
}
```

And then run `composer update` to ensure the module is installed.

Finally, add the module name to your project's `config/application.config.php` under the `modules`key:

```
return [
    /* ... */
    'modules' => [
        /* ... */
        'Laminas\ApiTools\ContentValidation',
    ],
    /* ... */
];
```

Configuration
-------------

[](#configuration)

### User Configuration

[](#user-configuration)

This module utilizes two user level configuration keys `api-tools-content-validation` and also `input_filter_specs` (named such that this functionality can be moved into Laminas in the future).

#### Service Name key

[](#service-name-key)

The `api-tools-content-validation` key is a mapping between controller service names as the key, and the value being an array of mappings that determine which HTTP method to respond to and what input filter to map to for the given request. The keys for the mapping can either be an HTTP method that accepts a request body (i.e., `POST`, `PUT`, `PATCH`, or `DELETE`), or it can be the word `input_filter`. The value assigned for the `input_filter` key will be used in the case that no input filter is configured for the current HTTP request method.

Example where there is a default as well as a POST filter:

```
'api-tools-content-validation' => [
    'Application\Controller\HelloWorld' => [
        'input_filter' => 'Application\Controller\HelloWorld\Validator',
        'POST' => 'Application\Controller\HelloWorld\CreationValidator',
    ],
],
```

In the above example, the `Application\Controller\HelloWorld\Validator` service will be selected for `PATCH`, `PUT`, or `DELETE` requests, while the `Application\Controller\HelloWorld\CreationValidator`will be selected for `POST` requests.

Starting in version 1.1.0, two additional keys can be defined to affect application validation behavior:

- `use_raw_data`: if NOT present, raw data is ALWAYS injected into the "BodyParams" container (defined by api-tools-content-negotiation). If this key is present and a boolean false, then the validated, filtered data from the input filter will be used instead.
- `allows_only_fields_in_filter`: if present, and `use_raw_data` is boolean false, the value of this flag will define whether or not additional fields present in the payload will be merged with the filtered data.
- `remove_empty_data`: Should we remove empty data from received data?

    - If no `remove_empty_data` flag is present, do nothing - use data as is
    - If `remove_empty_data` flag is present AND is boolean true, then remove empty data from current data array
    - Does not remove empty data if keys matched received data

> ### Validating GET requests
>
> [](#validating-get-requests)
>
> - **Since 1.3.0.**
>
> Starting in 1.3.0, you may also specify `GET` as an HTTP method, mapping it to an input filter in order to validate your query parameters. Configuration is exactly as described in the above section.
>
> This feature is only available when manually configuring your API; it is not exposed in the Admin UI.

> ### Validating collection requests
>
> [](#validating-collection-requests)
>
> - **Since 1.5.0**
>
> Starting in 1.5.0, you may specify any of:
>
> - `POST_COLLECTION`
> - `PUT_COLLECTION`
> - `PATCH_COLLECTION`
>
> as keys. These will then be used specifically with the given HTTP method, but only on requests matching the collection endpoint.

> ### Validating DELETE requests
>
> [](#validating-delete-requests)
>
> - **Since 1.6.0**
>
> Starting in 1.6.0, you may specify each of the following keys for input filters:
>
> - `DELETE`
> - `DELETE_COLLECTION`
>
> The input filter associated with the key will be used to validate data sent in the request body.

#### input\_filter\_spec

[](#input_filter_spec)

`input_filter_spec` is for configuration-driven creation of input filters. The keys for this array will be a unique name, but more often based off the service name it is mapped to under the `api-tools-content-validation` key. The values will be an input filter configuration array, as is described in the Laminas manual [section on input filters](http://laminas.readthedocs.org/en/latest/modules/laminas.input-filter.intro.html).

Example:

```
'input_filter_specs' => [
    'Application\Controller\HelloWorldGet' => [
        0 => [
            'name' => 'name',
            'required' => true,
            'filters' => [
                0 => [
                    'name' => 'Laminas\Filter\StringTrim',
                    'options' => [],
                ],
            ],
            'validators' => [],
            'description' => 'Hello to name',
            'allow_empty' => false,
            'continue_if_empty' => false,
        ],
    ],
```

### System Configuration

[](#system-configuration)

The following configuration is defined by the module in order to function within a Laminas application.

```
namespace Laminas\ApiTools\ContentValidation;

use Laminas\InputFiler\InputFilterAbstractServiceFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;

return [
    'controller_plugins' => [
        'aliases' => [
            'getinputfilter' => InputFilter\InputFilterPlugin::class,
            'getInputfilter' => InputFilter\InputFilterPlugin::class,
            'getInputFilter' => InputFilter\InputFilterPlugin::class,
        ],
        'factories' => [
            InputFilter\InputFilterPlugin::class => InvokableFactory::class,
        ],
    ],
    'input_filters' => [
        'abstract_factories' => [
            InputFilterAbstractServiceFactory::class,
        ],
    ],
    'service_manager' => [
        'factories' => [
            ContentValidationListener::class => ContentValidationListenerFactory::class,
        ],
    ],
    'validators' => [
        'factories' => [
            'Laminas\ApiTools\ContentValidation\Validator\DbRecordExists' => Validator\Db\RecordExistsFactory::class,
            'Laminas\ApiTools\ContentValidation\Validator\DbNoRecordExists' => Validator\Db\NoRecordExistsFactory::class,
        ],
    ],
];
```

Laminas Events
--------------

[](#laminas-events)

### Listeners

[](#listeners)

#### Laminas\\ApiTools\\ContentValidation\\ContentValidationListener

[](#laminasapitoolscontentvalidationcontentvalidationlistener)

This listener is attached to the `MvcEvent::EVENT_ROUTE` event at priority `-650`. Its purpose is to utilize the `api-tools-content-validation` configuration in order to determine if the current request's selected controller service name has a configured input filter. If it does, it will traverse the mappings from the configuration file to create the appropriate input filter (from configuration or the Laminas input filter plugin manager) in order to validate the incoming data. This particular listener utilizes the data from the `api-tools-content-negotiation` data container in order to get the deserialized content body parameters.

### Events

[](#events)

#### Laminas\\ApiTools\\ContentValidation\\ContentValidationListener::EVENT\_BEFORE\_VALIDATE

[](#laminasapitoolscontentvalidationcontentvalidationlistenerevent_before_validate)

This event is emitted by `Laminas\ApiTools\ContentValidation\ContentValidationListener::onRoute()`(described above) in between aggregating data to validate and determining the input filter, and the actual validation of data. Its purpose is to allow users:

- the ability to manipulate input filters.
- to modify the data set to validate (available since 1.4.0).

As an example, you might want to validate an identifier provided via the URI, and matched during routing. You may do this as follows:

```
$events->listen(ContentValidationListener::EVENT_BEFORE_VALIDATE, function ($e) {
    if ($e->getController() !== MyRestController::class) {
        return;
    }

    $matches = $e->getRouteMatch();
    $data = $e->getParam('Laminas\ApiTools\ContentValidation\ParameterData') ?: [];
    $data['id'] = $matches->getParam('id');
    $e->setParam('Laminas\ApiTools\ContentValidation\ParameterData', $data);
});
```

Laminas Services
----------------

[](#laminas-services)

### Controller Plugins

[](#controller-plugins)

#### Laminas\\ApiTools\\ContentValidation\\InputFilter\\InputFilterPlugin (aka getInputFilter)

[](#laminasapitoolscontentvalidationinputfilterinputfilterplugin-aka-getinputfilter)

This plugin is available to Laminas controllers. When invoked (`$this->getInputFilter()` or `$this->plugin('getinputfilter')->__invoke()`), it returns whatever is in the MVC event parameter `Laminas\ApiTools\ContentValidation\InputFilter`, returning null for any value that is not an implementation of `Laminas\InputFilter\InputFilter`.

### Service

[](#service)

#### Laminas\\InputFilter\\InputFilterAbstractServiceFactory

[](#laminasinputfilterinputfilterabstractservicefactory)

This abstract factory is responsible for creating and returning an appropriate input filter given a name and the configuration from the top-level key `input_filter_specs`. It is registered with `Laminas\InputFilter\InputFilterPluginManager`.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community23

Small or concentrated contributor base

Maturity84

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 68.9% 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 ~42 days

Recently: every ~76 days

Total

39

Last Release

737d ago

Major Versions

0.9.1 → 1.0.02019-12-31

PHP version history (8 changes)0.8.0PHP &gt;=5.4.8

0.9.0PHP &gt;=5.3.23

1.2.0PHP &gt;=5.5

1.3.1PHP ^5.6 || ^7.0

1.9.x-devPHP ^7.3 || ~8.0.0

1.10.x-devPHP ^7.3 || ~8.0.0 || ~8.1.0

1.12.0PHP ~8.0.0 || ~8.1.0 || ~8.2.0

1.13.0PHP ~8.1.0 || ~8.2.0 || ~8.3.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1388877?v=4)[Kristijonas Lučinskas](/maintainers/kristijonas)[@Kristijonas](https://github.com/Kristijonas)

---

Top Contributors

[![weierophinney](https://avatars.githubusercontent.com/u/25943?v=4)](https://github.com/weierophinney "weierophinney (284 commits)")[![michalbundyra](https://avatars.githubusercontent.com/u/7423207?v=4)](https://github.com/michalbundyra "michalbundyra (44 commits)")[![jguittard](https://avatars.githubusercontent.com/u/5320213?v=4)](https://github.com/jguittard "jguittard (25 commits)")[![rkeet-salesupply](https://avatars.githubusercontent.com/u/37324639?v=4)](https://github.com/rkeet-salesupply "rkeet-salesupply (10 commits)")[![ruzann](https://avatars.githubusercontent.com/u/40264956?v=4)](https://github.com/ruzann "ruzann (9 commits)")[![Ocramius](https://avatars.githubusercontent.com/u/154256?v=4)](https://github.com/Ocramius "Ocramius (6 commits)")[![snapshotpl](https://avatars.githubusercontent.com/u/312655?v=4)](https://github.com/snapshotpl "snapshotpl (5 commits)")[![steverhoades](https://avatars.githubusercontent.com/u/1146668?v=4)](https://github.com/steverhoades "steverhoades (4 commits)")[![akrabat](https://avatars.githubusercontent.com/u/33135?v=4)](https://github.com/akrabat "akrabat (4 commits)")[![geerteltink](https://avatars.githubusercontent.com/u/9497586?v=4)](https://github.com/geerteltink "geerteltink (3 commits)")[![rnd-cosoft](https://avatars.githubusercontent.com/u/57006314?v=4)](https://github.com/rnd-cosoft "rnd-cosoft (3 commits)")[![rkeet](https://avatars.githubusercontent.com/u/3327864?v=4)](https://github.com/rkeet "rkeet (3 commits)")[![boesing](https://avatars.githubusercontent.com/u/2189546?v=4)](https://github.com/boesing "boesing (2 commits)")[![neeckeloo](https://avatars.githubusercontent.com/u/1768645?v=4)](https://github.com/neeckeloo "neeckeloo (1 commits)")[![AdilHoumadi](https://avatars.githubusercontent.com/u/462805?v=4)](https://github.com/AdilHoumadi "AdilHoumadi (1 commits)")[![alexdenvir](https://avatars.githubusercontent.com/u/1412074?v=4)](https://github.com/alexdenvir "alexdenvir (1 commits)")[![BreiteSeite](https://avatars.githubusercontent.com/u/2171105?v=4)](https://github.com/BreiteSeite "BreiteSeite (1 commits)")[![ekosogin](https://avatars.githubusercontent.com/u/13533292?v=4)](https://github.com/ekosogin "ekosogin (1 commits)")[![kersysgediminas](https://avatars.githubusercontent.com/u/51697762?v=4)](https://github.com/kersysgediminas "kersysgediminas (1 commits)")[![adamculp](https://avatars.githubusercontent.com/u/284451?v=4)](https://github.com/adamculp "adamculp (1 commits)")

---

Tags

laminasvalidationmoduleapi-tools

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/rnd-cosoft-api-tools-content-validation/health.svg)

```
[![Health](https://phpackages.com/badges/rnd-cosoft-api-tools-content-validation/health.svg)](https://phpackages.com/packages/rnd-cosoft-api-tools-content-validation)
```

###  Alternatives

[magento/community-edition

Magento 2 (Open Source)

12.1k52.1k10](/packages/magento-community-edition)[wheelpros/fitment-platform-api

Magento 2 (Open Source)

12.1k1.2k](/packages/wheelpros-fitment-platform-api)[laminas-api-tools/api-tools-admin

Laminas API Tools Admin module

13794.3k5](/packages/laminas-api-tools-api-tools-admin)

PHPackages © 2026

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