PHPackages                             rnd-cosoft/api-tools-content-negotiation - 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. rnd-cosoft/api-tools-content-negotiation

ActiveLibrary

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

Laminas Module providing content-negotiation features

1.9.1(1y ago)01.5k↓100%1BSD-3-ClausePHPPHP ~8.1.0 || ~8.2.0 || ~8.3.0

Since Dec 31Pushed 1y agoCompare

[ Source](https://github.com/rnd-cosoft/api-tools-content-negotiation)[ Packagist](https://packagist.org/packages/rnd-cosoft/api-tools-content-negotiation)[ Docs](https://api-tools.getlaminas.org)[ RSS](/packages/rnd-cosoft-api-tools-content-negotiation/feed)WikiDiscussions 1.9.x Synced today

READMEChangelog (2)Dependencies (17)Versions (41)Used By (0)

Laminas Content Negotiation
===========================

[](#laminas-content-negotiation)

[![Build Status](https://github.com/laminas-api-tools/api-tools-content-negotiation/actions/workflows/continuous-integration.yml/badge.svg)](https://github.com/laminas-api-tools/api-tools-content-negotiation/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)

`api-tools-content-negotiation` is a module for automating content negotiation tasks within a Laminas Framework application.

The following features are provided

- Mapping `Accept` header media types to specific view model types, and automatically casting controller results to those view model types.
- Defining `Accept` header media type whitelists; requests with `Accept` media types that fall outside the whitelist will be immediately rejected with a `406 Not Acceptable` response.
- Defining `Content-Type` header media type whitelists; requests sending content bodies with `Content-Type` media types that fall outside the whitelist will be immediately rejected with a `415 Unsupported Media Type` response.

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-negotiation
```

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

```
"require": {
    "laminas-api-tools/api-tools-content-negotiation": "^1.2"
}
```

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\ContentNegotiation',
    ],
    /* ... */
];
```

> ### laminas-component-installer
>
> [](#laminas-component-installer)
>
> If you use [laminas-component-installer](https://github.com/laminas/laminas-component-installer), that plugin will install api-tools-content-negotiation as a module for you.

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

[](#configuration)

### User Configuration

[](#user-configuration)

The top-level configuration key for user configuration of this module is `api-tools-content-negotiation`.

#### Key: `controllers`

[](#key-controllers)

The `controllers` key is utilized for mapping a content negotiation strategy to a particular controller service name (from the top-level `controllers` section). The value portion of the controller array can either be a *named selector* (see `selectors` below), or a selector definition.

A selector definition consists of an array with the key of the array being the name of a view model, and the value of it being an indexed array of media types that, when matched, will select that view model.

Example:

```
'controllers' => [
    // Named selector:
    'Application\Controller\HelloWorld1' => 'Json',

    // Selector definition:
    'Application\Controller\HelloWorld2' => [
        'Laminas\ApiTools\ContentNegotiation\JsonModel' => [
            'application/json',
            'application/*+json',
        ],
    ],
],
```

#### Key: `selectors`

[](#key-selectors)

The `selectors` key is utilized to create named selector definitions for reuse between many different controllers. The key part of the selectors array will be a name used to correlate the selector definition (which uses the format described in the [controllers](#key-controllers) key).

Example:

```
'selectors' => [
    'Json' => [
        'Laminas\ApiTools\ContentNegotiation\JsonModel' => [
            'application/json',
            'application/*+json',
        ],
    ],
],
```

A selector can contain multiple view models, each associated with different media types, allowing you to provide multiple representations. As an example, the following selector would allow a given controller to return either JSON or HTML output:

```
'selectors' => [
    'HTML-Json' => [
        'Laminas\ApiTools\ContentNegotiation\JsonModel' => [
            'application/json',
            'application/*+json',
        ],
        'Laminas\ApiTools\ContentNegotiation\ViewModel' => [
            'text/html',
        ],
    ],
],
```

#### Key: `accept_whitelist`

[](#key-accept_whitelist)

The `accept_whitelist` key is utilized to instruct the content negotiation module which media types are acceptable for a given controller service name. When a controller service name is configured in this key, along with an indexed array of matching media types, only media types that match the `Accept` header of a given request will be allowed to be dispatched. Unmatched media types will receive a `406 Cannot honor Accept type specified` response.

The value of each controller service name key can either be a string or an array of strings.

Example:

```
'accept_whitelist' => [
    'Application\\Controller\\HelloApiController' => [
        'application/vnd.application-hello+json',
        'application/hal+json',
        'application/json',
    ],
],
```

#### Key: `content_type_whitelist`

[](#key-content_type_whitelist)

The `content_type_whitelist` key is utilized to instruct the content negotiation module which media types are valid for the `Content-Type` of a request. When a controller service name is configured in this key, along with an indexed array of matching media types, only media types that match the `Content-Type` header of a given request will be allowed to be dispatched. Unmatched media types will receive a `415 Invalid content-type specified` response.

The value of each controller service name key can either be a string or an array of strings.

Example:

```
'content_type_whitelist' => [
    'Application\\Controller\\HelloWorldController' => [
        'application/vnd.application-hello-world+json',
        'application/json',
    ],
],
```

#### Key: `x_http_method_override_enabled`

[](#key-x_http_method_override_enabled)

- Since 1.3.0

This boolean flag determines whether or not the `HttpMethodOverrideListener`will be enabled by default.

#### Key: `http_override_methods`

[](#key-http_override_methods)

- Since 1.3.0

The `http_override_methods` key is utilized to provide the `HttpMethodOverrideListener` with a map of allowed override methods for a given HTTP method, as specified via the `X-HTTP-Method-Override` header. Essentially, the values are:

```
'Incoming HTTP request method' => $arrayOfAllowedOverrideMethods,
```

As an example, if you want to allow the `X-HTTP-Method-Override` header to allow overriding HTTP `GET` requests with an alternate method, you might define this as follows:

```
'x_http_method_override_enabled' => true,
'http_override_methods' => [
    'GET' => [
        'HEAD',
        'POST',
        'PUT',
        'DELETE',
        'PATCH',
    ],
];
```

Then, to make a request, you could do the following:

```
GET /foo HTTP/1.1
Host: example.com
X-HTTP-Method-Override: PATCH

some=content&more=content
```

The above would then be interpreted as a `PATCH` request. If the same request were made via HTTP `POST`, or if a `GET` request were made with an override value of `OPTIONS`, the listener would raise a problem, as, in the former case, no maps are defined for `POST`, and, in the latter, `OPTIONS` is not in the map for `GET`.

### System Configuration

[](#system-configuration)

The following configuration is provided in `config/module.config.php` to enable the module to function:

```
'filters' => [
    'aliases'   => [
        'Laminas\Filter\File\RenameUpload' => 'filerenameupload',
    ],
    'factories' => [
        'filerenameupload' => Factory\RenameUploadFilterFactory::class,
    ],
],

'validators' => [
    'aliases'   => [
        'Laminas\Validator\File\UploadFile' => 'fileuploadfile',
    ],
    'factories' => [
        'fileuploadfile' => Factory\UploadFileValidatorFactory::class,
    ],
],

'service_manager' => [
    'factories' => [
        ContentTypeListener::class        => InvokableFactory::class,
        AcceptListener::class             => Factory\AcceptListenerFactory::class,
        AcceptFilterListener::class       => Factory\AcceptFilterListenerFactory::class,
        ContentTypeFilterListener::class  => Factory\ContentTypeFilterListenerFactory::class,
        ContentNegotiationOptions::class  => Factory\ContentNegotiationOptionsFactory::class,
        HttpMethodOverrideListener::class => Factory\HttpMethodOverrideListenerFactory::class,
    ],
],

'controller_plugins' => [
    'aliases' => [
        'routeParam'  => ControllerPlugin\RouteParam::class,
        'queryParam'  => ControllerPlugin\QueryParam::class,
        'bodyParam'   => ControllerPlugin\BodyParam::class,
        'routeParams' => ControllerPlugin\RouteParams::class,
        'queryParams' => ControllerPlugin\QueryParams::class,
        'bodyParams'  => ControllerPlugin\BodyParams::class,
    ],
    'factories' => [
        ControllerPlugin\RouteParam::class  => InvokableFactory::class,
        ControllerPlugin\QueryParam::class  => InvokableFactory::class,
        ControllerPlugin\BodyParam::class   => InvokableFactory::class,
        ControllerPlugin\RouteParams::class => InvokableFactory::class,
        ControllerPlugin\QueryParams::class => InvokableFactory::class,
        ControllerPlugin\BodyParams::class  => InvokableFactory::class,
    ],
],
```

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

[](#laminas-events)

### Listeners

[](#listeners)

#### Laminas\\ApiTools\\ContentNegotiation\\AcceptListener

[](#laminasapitoolscontentnegotiationacceptlistener)

This listener is attached to the `MvcEvent::EVENT_DISPATCH` event with priority `-10`. It is responsible for performing the actual selection and casting of a controller's view model based on the content negotiation configuration.

#### Laminas\\ApiTools\\ContentNegotiation\\ContentTypeListener

[](#laminasapitoolscontentnegotiationcontenttypelistener)

This listener is attached to the `MvcEvent::EVENT_ROUTE` event with a priority of `-625`. It is responsible for examining the `Content-Type` header in order to determine how the content body should be deserialized. Values are then persisted inside of a `ParameterDataContainer` which is stored in the `LaminasContentNegotiationParameterData` key of the `MvcEvent` object.

#### Laminas\\ApiTools\\ContentNegotiation\\AcceptFilterListener

[](#laminasapitoolscontentnegotiationacceptfilterlistener)

This listener is attached to the `MvcEvent::EVENT_ROUTE` event with a priority of `-625`. It is responsible for ensuring the controller selected by routing is configured to respond to the specific media type in the current request's `Accept` header. If it cannot, it will short-circuit the MVC dispatch process by returning a `406 Cannot honor Accept type specified` response.

#### Laminas\\ApiTools\\ContentNegotiation\\ContentTypeFilterListener

[](#laminasapitoolscontentnegotiationcontenttypefilterlistener)

This listener is attached to the `MvcEvent::EVENT_ROUTE` event with a priority of `-625`. It is responsible for ensuring the route matched controller can accept content in the request body specified by the media type in the current request's `Content-Type` header. If it cannot, it will short-circuit the MVC dispatch process by returning a `415 Invalid content-type specified` response.

#### Laminas\\ApiTools\\ContentNegotiation\\HttpMethodOverrideListener

[](#laminasapitoolscontentnegotiationhttpmethodoverridelistener)

- Since 1.3.0

This listener is attached to the `MvcEvent::EVENT_ROUTE` event with a priority of `-40`, but only if the `x_http_method_override_enabled` configuration flag was toggle on. It is responsible for checking if an `X-HTTP-Method-Override`header is present, and, if so, if it contains a value in the set allowed for the current HTTP request method invoked. If so, it resets the HTTP request method to the header value.

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

[](#laminas-services)

### Controller Plugins

[](#controller-plugins)

#### Laminas\\ApiTools\\ContentNegotiation\\ControllerPlugin\\RouteParam (a.k.a "routeParam")

[](#laminasapitoolscontentnegotiationcontrollerpluginrouteparam-aka-routeparam)

A controller plugin (`Laminas\Mvc\Controller\AbstractActionController` callable) that will return a single parameter with a particular name from the route match.

```
use Laminas\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return $this->routeParam('id', 'someDefaultValue');
    }
}
```

#### Laminas\\ApiTools\\ContentNegotiation\\ControllerPlugin\\QueryParam (a.k.a "queryParam")

[](#laminasapitoolscontentnegotiationcontrollerpluginqueryparam-aka-queryparam)

A controller plugin (`Laminas\Mvc\Controller\AbstractActionController` callable) that will return a single parameter from the current request query string.

```
use Laminas\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return $this->queryParam('foo', 'someDefaultValue');
    }
}
```

#### Laminas\\ApiTools\\ContentNegotiation\\ControllerPlugin\\BodyParam (a.k.a "bodyParam")

[](#laminasapitoolscontentnegotiationcontrollerpluginbodyparam-aka-bodyparam)

A controller plugin (`Laminas\Mvc\Controller\AbstractActionController` callable) that will return a single parameter from the content-negotiated content body.

```
use Laminas\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return $this->bodyParam('foo', 'someDefaultValue');
    }
}
```

#### Laminas\\ApiTools\\ContentNegotiation\\ControllerPlugin\\RouteParams (a.k.a "routeParams")

[](#laminasapitoolscontentnegotiationcontrollerpluginrouteparams-aka-routeparams)

A controller plugin (`Laminas\Mvc\Controller\AbstractActionController` callable) that will return a all the route parameters.

```
use Laminas\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return $this->routeParams()
    }
}
```

#### Laminas\\ApiTools\\ContentNegotiation\\ControllerPlugin\\QueryParams (a.k.a "queryParams")

[](#laminasapitoolscontentnegotiationcontrollerpluginqueryparams-aka-queryparams)

A controller plugin (`Laminas\Mvc\Controller\AbstractActionController` callable) that will return a all the query parameters.

```
use Laminas\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return $this->queryParams()
    }
}
```

#### Laminas\\ApiTools\\ContentNegotiation\\ControllerPlugin\\BodyParams (a.k.a "bodyParams")

[](#laminasapitoolscontentnegotiationcontrollerpluginbodyparams-aka-bodyparams)

A controller plugin (`Laminas\Mvc\Controller\AbstractActionController` callable) that will return a all the content-negotiated body parameters.

```
use Laminas\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return $this->bodyParams()
    }
}
```

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance32

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity83

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 80.8% 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 ~40 days

Recently: every ~76 days

Total

41

Last Release

682d ago

Major Versions

0.9.0 → 1.0.02019-12-31

0.9.1 → 1.0.0beta12019-12-31

PHP version history (10 changes)0.7.0PHP &gt;=5.3.3

0.8.0PHP &gt;=5.4.8

0.9.0PHP &gt;=5.3.23

1.1.0PHP &gt;=5.5

1.1.2PHP ^5.5

1.2.0PHP ^5.6 || ^7.0

1.5.0PHP ^7.3 || ~8.0.0

1.7.0PHP ^7.3 || ~8.0.0 || ~8.1.0

1.8.0PHP ~8.0.0 || ~8.1.0 || ~8.2.0

1.9.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 (358 commits)")[![michalbundyra](https://avatars.githubusercontent.com/u/7423207?v=4)](https://github.com/michalbundyra "michalbundyra (25 commits)")[![ralphschindler](https://avatars.githubusercontent.com/u/76674?v=4)](https://github.com/ralphschindler "ralphschindler (15 commits)")[![func0der](https://avatars.githubusercontent.com/u/529819?v=4)](https://github.com/func0der "func0der (7 commits)")[![snapshotpl](https://avatars.githubusercontent.com/u/312655?v=4)](https://github.com/snapshotpl "snapshotpl (4 commits)")[![rnd-cosoft](https://avatars.githubusercontent.com/u/57006314?v=4)](https://github.com/rnd-cosoft "rnd-cosoft (4 commits)")[![Wilt](https://avatars.githubusercontent.com/u/2419627?v=4)](https://github.com/Wilt "Wilt (3 commits)")[![neeckeloo](https://avatars.githubusercontent.com/u/1768645?v=4)](https://github.com/neeckeloo "neeckeloo (3 commits)")[![geerteltink](https://avatars.githubusercontent.com/u/9497586?v=4)](https://github.com/geerteltink "geerteltink (3 commits)")[![MichaelGooden](https://avatars.githubusercontent.com/u/1275012?v=4)](https://github.com/MichaelGooden "MichaelGooden (3 commits)")[![ezimuel](https://avatars.githubusercontent.com/u/475967?v=4)](https://github.com/ezimuel "ezimuel (2 commits)")[![boesing](https://avatars.githubusercontent.com/u/2189546?v=4)](https://github.com/boesing "boesing (2 commits)")[![samsonasik](https://avatars.githubusercontent.com/u/459648?v=4)](https://github.com/samsonasik "samsonasik (1 commits)")[![TomHAnderson](https://avatars.githubusercontent.com/u/493920?v=4)](https://github.com/TomHAnderson "TomHAnderson (1 commits)")[![matiasfuster](https://avatars.githubusercontent.com/u/10004100?v=4)](https://github.com/matiasfuster "matiasfuster (1 commits)")[![bakura10](https://avatars.githubusercontent.com/u/1198915?v=4)](https://github.com/bakura10 "bakura10 (1 commits)")[![boteeka](https://avatars.githubusercontent.com/u/877397?v=4)](https://github.com/boteeka "boteeka (1 commits)")[![ddubau](https://avatars.githubusercontent.com/u/75494?v=4)](https://github.com/ddubau "ddubau (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)")

---

Tags

laminasmodulecontent negotiationapi-tools

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[laminas-api-tools/api-tools-admin

Laminas API Tools Admin module

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

PHPackages © 2026

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