PHPackages                             chevere/parameter - 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. chevere/parameter

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

chevere/parameter
=================

Dynamic parameter-argument validation for PHP with rich type constraints, attributes, and schema introspection.

2.0.4(1mo ago)1023.7k—7.2%1[6 issues](https://github.com/chevere/parameter/issues)15Apache-2.0PHPPHP ^8.1CI passing

Since Jan 9Pushed 1mo agoCompare

[ Source](https://github.com/chevere/parameter)[ Packagist](https://packagist.org/packages/chevere/parameter)[ Docs](https://chevere.org)[ RSS](/packages/chevere-parameter/feed)WikiDiscussions 2.0 Synced 1mo ago

READMEChangelog (10)Dependencies (18)Versions (23)Used By (15)

Parameter
=========

[](#parameter)

[![Chevere](chevere.svg)](chevere.svg)

[![Build](https://camo.githubusercontent.com/593ed423ebc742440c1cbaed20ea97945ed706c73359ac92b8f1b65a2d16f0b6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636865766572652f706172616d657465722f746573742e796d6c3f6272616e63683d322e30267374796c653d666c61742d737175617265)](https://github.com/chevere/parameter/actions)[![Code size](https://camo.githubusercontent.com/33a8994efaa55ba9e9a4a8ec3527fc704d8a77b9a67d2fc42c845260374ab750/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f636f64652d73697a652f636865766572652f706172616d657465723f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/33a8994efaa55ba9e9a4a8ec3527fc704d8a77b9a67d2fc42c845260374ab750/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f636f64652d73697a652f636865766572652f706172616d657465723f7374796c653d666c61742d737175617265)[![Apache-2.0](https://camo.githubusercontent.com/4ef691a595a7a936f5ccc1e8fec66d1778ef1ca79f54f161a0a6baa0d29dc5cf/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f636865766572652f706172616d657465723f7374796c653d666c61742d737175617265)](LICENSE)[![PHPStan](https://camo.githubusercontent.com/6016298b28550819030c76e9327f62501596a31fd76406695bae2f3d2a1f26a4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230392d626c756576696f6c65743f7374796c653d666c61742d737175617265)](https://phpstan.org/)[![Mutation testing badge](https://camo.githubusercontent.com/5c9f4ff65eadeb2d3de07ee2475340bdb48d4885e900ff471a47fb8965449b52/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742d7371756172652675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d25324663686576657265253246706172616d65746572253246322e30)](https://dashboard.stryker-mutator.io/reports/github.com/chevere/parameter/2.0)

[![Quality Gate Status](https://camo.githubusercontent.com/20facea8a21a5e086a8ad8c7ed24e99e374836f05e17965cf4a6e2cd34edb067/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d636865766572655f706172616d65746572266d65747269633d616c6572745f737461747573)](https://sonarcloud.io/dashboard?id=chevere_parameter)[![Maintainability Rating](https://camo.githubusercontent.com/08bbed590db01a6bad292702710457e0ea58388dcc597fff6a4d4f43e69e5f75/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d636865766572655f706172616d65746572266d65747269633d7371616c655f726174696e67)](https://sonarcloud.io/dashboard?id=chevere_parameter)[![Reliability Rating](https://camo.githubusercontent.com/ca9a2b825a930797cf80bd140b88ec308b0f12996495f0902397caa3a3891165/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d636865766572655f706172616d65746572266d65747269633d72656c696162696c6974795f726174696e67)](https://sonarcloud.io/dashboard?id=chevere_parameter)[![Security Rating](https://camo.githubusercontent.com/a911096aff5b9fc20202b492c85e9750b6981a29d92eb43133c49d858faddf82/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d636865766572655f706172616d65746572266d65747269633d73656375726974795f726174696e67)](https://sonarcloud.io/dashboard?id=chevere_parameter)[![Coverage](https://camo.githubusercontent.com/a676bca474eaeac906e06f79533d9a8d1eb3395e3c9b96433114130b8f09c281/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d636865766572655f706172616d65746572266d65747269633d636f766572616765)](https://sonarcloud.io/dashboard?id=chevere_parameter)[![Technical Debt](https://camo.githubusercontent.com/04faf30439efe42b040359c2b9905d9af560b8cfdf9b4c64e79103e1043095ac/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d636865766572655f706172616d65746572266d65747269633d7371616c655f696e646578)](https://sonarcloud.io/dashboard?id=chevere_parameter)[![CodeFactor](https://camo.githubusercontent.com/9c01d1bc8cdcccd49b4f6e772b9b2d244e9f7cb9cfe2678f73aef9d804469a52/68747470733a2f2f7777772e636f6465666163746f722e696f2f7265706f7369746f72792f6769746875622f636865766572652f706172616d657465722f6261646765)](https://www.codefactor.io/repository/github/chevere/parameter)

Summary
-------

[](#summary)

**Chevere Parameter** is a library for building dynamic, validated parameters with type-safe rules and schema introspection. It enables you to define rich validation constraints for any PHP type, from simple scalars to deeply nested arrays, using either helper functions or attributes, eliminating boilerplate validation logic across your codebase.

- **[chevere/action](https://chevere.org/packages/action)**: Implements the action design pattern for encapsulating business logic, utilizing this package for comprehensive parameter validation.
- **[chevere/router](https://chevere.org/packages/router)**: Offers powerful routing with built-in parameter validation for handling HTTP requests and responses.
- **[chevere/sql2p](https://chevere.org/packages/sql2p)**: Transforms SQL queries into parameter definitions, enabling automated validation of database inputs and outputs.

Installing
----------

[](#installing)

Parameter is available through [Packagist](https://packagist.org/packages/chevere/parameter) and the repository source is at [chevere/parameter](https://github.com/chevere/parameter).

```
composer require chevere/parameter
```

Quick start
-----------

[](#quick-start)

### Validate a single value

[](#validate-a-single-value)

Create a parameter with rules and invoke it to validate. If validation fails, an exception is thrown.

```
use function Chevere\Parameter\int;

$id = int(min: 1);
$id(5);    // returns 5
$id(-1);   // throws InvalidArgumentException
```

### Validate multiple values

[](#validate-multiple-values)

Compose parameters to validate structured data in a single call.

```
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\int;
use function Chevere\Parameter\string;

$userSchema = arrayp(
    id: int(min: 1),
    name: string('/^[A-Z][a-z]+$/'),
);
$userSchema([
    'id' => 1,
    'name' => 'Rodolfo',
]);
```

### Validate function arguments with attributes

[](#validate-function-arguments-with-attributes)

Decorate functions with attributes and call `validated()` to enforce rules on both arguments and return values automatically.

```
use Chevere\Parameter\Attributes\_float;
use Chevere\Parameter\Attributes\_int;
use Chevere\Parameter\Attributes\_return;
use function Chevere\Parameter\validated;

#[_return(
    new _float(min: 0, max: 2400)
)]
function wageWeekWA(
    #[_int(min: 1628)]
    int $cents,
    #[_float(min: 0, max: 40)]
    float $hours,
): float {
    return $cents * $hours / 100;
}

$wage = validated('wageWeekWA', 1628, 40.0);
```

Why Parameter?
--------------

[](#why-parameter)

**Replace scattered validation with declarative rules.** Instead of writing `if`/`throw` blocks for every function, define constraints once using expressive helpers or attributes. Parameter turns validation into a first-class concern.

**Type safety beyond PHP's type system.** PHP enforces types, but not ranges, patterns, or allowed values. Parameter bridges that gap, an `int(min: 1, max: 100)` is more than `int`.

**Schema introspection.** Every parameter exposes its rules via `schema()`, enabling you to generate documentation, API contracts, or UI form definitions from the same source of truth.

```
use function Chevere\Parameter\int;

$param = int(min: 0, max: 255);
$param->schema();
// ['type' => 'int', 'min' => 0, 'max' => 255]
```

**Immutable design.** All `with*` methods return new instances. Build parameter variations safely without side effects.

**Three validation strategies.** Choose the approach that fits your architecture:

StrategyHowBest for[Inline](#inline-validation)`int(min: 1)($value)`Quick checks, scripts[Attribute delegated](#attribute-delegated-validation)`validated('fn', ...$args)`Functions, controllers[Attribute inline](#attribute-inline-validation)`assertArguments()` inside bodyGranular controlReference
---------

[](#reference)

### Core types

[](#core-types)

TypeHelperAttributeDescription[String](#string)`string``_string`String, optionally matching a regex[Int](#int)`int``_int`Integer with optional range/accept/reject[Float](#float)`float``_float`Float with optional range/accept/reject[Bool](#bool)`bool``_bool`Boolean[Null](#null)`null``_null`Null[Object](#object)`object`—Object of a given class[Mixed](#mixed)`mixed``_mixed`Any type[Array](#array)`arrayp``_arrayp`Array with named parameters[Iterable](#iterable)`iterable``_iterable`Iterable with generic key/value[Union](#union)`union``_union`Value matching at least one parameter[UnionNull](#union-null)`unionNull``_unionNull`Value matching at least one parameter or null### Derived types

[](#derived-types)

String-based parameters:

TypeHelperDescription[Enum](#enum-string)`enum`String matching a fixed list[IntString](#int-string)`intString`String of digits[BoolString](#bool-string)`boolString``"0"` or `"1"`[Date](#date-string)`date``YYYY-MM-DD` string[Time](#time-string)`time``hh:mm:ss` string[Datetime](#datetime-string)`datetime``YYYY-MM-DD hh:mm:ss` stringInt-based parameters:

TypeHelperDescription[BoolInt](#bool-int)`boolInt``0` or `1` integerArray-based parameters:

TypeHelperDescription[ArrayString](#array-string)`arrayString`Array with string values only[File](#file)`file``$_FILES` upload shape### Nullable helpers

[](#nullable-helpers)

Shorthand functions that create a union of a type with `null`:

HelperEquivalent to`nullInt(...)``union(null(), int(...))``nullFloat(...)``union(null(), float(...))``nullBool(...)``union(null(), bool(...))``nullString(...)``union(null(), string(...))``nullArray(...)``union(null(), arrayp(...))``nullArrayString(...)``union(null(), arrayString(...))``nullObject(...)``union(null(), object(...))`All accept the same arguments as their non-null counterparts.

```
use function Chevere\Parameter\nullInt;

$maybeId = nullInt(min: 1);
$maybeId(42);   // 42
$maybeId(null); // null
```

### Special attributes

[](#special-attributes)

AttributeDescription[\_callable](#_callable)Forward parameter resolution to a callable[\_return](#_return)Return value validationTypes
-----

[](#types)

A Parameter is an object implementing `ParameterInterface`. Every parameter can define a `description`, `default` value, and `sensitive` flag, plus additional validation rules depending on the type.

Parameters can be created using either helper functions or PHP attributes, both accept the same arguments.

### Immutability

[](#immutability)

Every `with*` method returns a new instance preserving the original state. This enables building parameter variations from a base definition without side effects.

```
use function Chevere\Parameter\int;

// All three are independent instances
$base = int(min: 0);
$small = $base->withMax(100);
$large = $base->withMax(10000);
```

Common methods available on all parameters:

```
$parameter->withDescription('A human-readable label');
$parameter->withIsSensitive(true); // marks value as sensitive (omitted from error messages)
$parameter->withDefault($defaultValue); // sets a default value used when the parameter is optional and not provided
```

Methods specific to each parameter type:

ParameterImmutable methods`IntParameter``withMin`, `withMax`, `withAccept`, `withReject``FloatParameter``withMin`, `withMax`, `withAccept`, `withReject``StringParameter``withRegex``ArrayParameter``withRequired`, `withOptional`, `withModify`, `withMakeOptional`, `withMakeRequired`, `without`, `withOptionalMinimum``ObjectParameter``withClassName`,### Schema introspection

[](#schema-introspection)

Every parameter exposes its validation rules via the `schema()` method. This enables programmatic access to constraints for documentation generation, API contracts, or UI form building.

```
use function Chevere\Parameter\string;
use function Chevere\Parameter\int;

string('/^[a-z]+$/')->schema();
// ['type' => 'string', 'regex' => '/^[a-z]+$/']

int(min: 0, max: 100)->schema();
// ['type' => 'int', 'min' => 0, 'max' => 100]
```

String
------

[](#string)

Use function `string` to create a `StringParameter`. Pass a `regex` for pattern matching.

```
use function Chevere\Parameter\string;

// Any string
$string = string();

// String matching "bin-" followed by digits
$string = string('/^bin-[\d]+$/');
$string('bin-123'); // 'bin-123'

// With a default value
$string = string(default: 'hello');
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_string;

#[_string('/^bin-[\d]+$/')]
```

### String-based derived types

[](#string-based-derived-types)

#### Enum string

[](#enum-string)

Matches one of a fixed list of strings.

```
use function Chevere\Parameter\enum;

$status = enum('active', 'inactive', 'pending');
$status('active');  // 'active'
$status('deleted'); // throws
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_enum;

#[_enum('active', 'inactive', 'pending')]
```

#### Int string

[](#int-string)

Matches strings representing integer digits.

```
use function Chevere\Parameter\intString;

$int = intString();
$int('100'); // '100'
$int('abc'); // throws
```

#### Bool string

[](#bool-string)

Matches `"0"` and `"1"` strings.

```
use function Chevere\Parameter\boolString;

$bool = boolString();
$bool('0'); // '0'
$bool('1'); // '1'
```

#### Date string

[](#date-string)

Matches `YYYY-MM-DD` date strings.

```
use function Chevere\Parameter\date;

$date = date();
$date('2025-01-15'); // '2025-01-15'
```

#### Time string

[](#time-string)

Matches `hh:mm:ss` time strings.

```
use function Chevere\Parameter\time;

$time = time();
$time('14:30:00'); // '14:30:00'
```

#### Datetime string

[](#datetime-string)

Matches `YYYY-MM-DD hh:mm:ss` datetime strings. Supports an optional `precision` argument for fractional seconds.

```
use function Chevere\Parameter\datetime;

$datetime = datetime();
$datetime('2025-01-15 14:30:00');

// With fractional seconds (up to 6 digits)
$precise = datetime(precision: 6);
$precise('2025-01-15 14:30:00.123456');
```

Int
---

[](#int)

Use function `int` to create an `IntParameter`. Supports `min`, `max`, `accept` (whitelist), and `reject` (blacklist).

```
use function Chevere\Parameter\int;

// Any integer
$int = int();
$int(42);

// Ranged
$int = int(min: 0, max: 100);
$int(50);  // 50
$int(200); // throws

// Whitelist
$int = int(accept: [1, 2, 3]);
$int(2);  // 2
$int(4);  // throws

// Blacklist
$int = int(reject: [0, -1]);
$int(5);  // 5
$int(0);  // throws
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_int;

#[_int(min: 0, max: 100)]
```

### Int-based derived types

[](#int-based-derived-types)

#### Bool int

[](#bool-int)

Matches `0` or `1` integers.

```
use function Chevere\Parameter\boolInt;

$flag = boolInt();
$flag(0); // 0
$flag(1); // 1
$flag(2); // throws
```

Float
-----

[](#float)

Use function `float` to create a `FloatParameter`. Supports `min`, `max`, `accept`, and `reject`.

```
use function Chevere\Parameter\float;

// Ranged
$price = float(min: 0.0, max: 9999.99);
$price(19.95); // 19.95

// Whitelist
$rate = float(accept: [0.5, 1.0, 1.5]);
$rate(1.0); // 1.0

// Blacklist
$score = float(reject: [0.0]);
$score(3.14); // 3.14
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_float;

#[_float(min: 0, max: 100)]
```

Bool
----

[](#bool)

Use function `bool` to create a `BoolParameter`.

```
use function Chevere\Parameter\bool;

$flag = bool();
$flag(true);  // true
$flag(false); // false
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_bool;

#[_bool]
```

Null
----

[](#null)

Use function `null` to create a `NullParameter`.

```
use function Chevere\Parameter\null;

$null = null();
$null(null); // null
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_null;

#[_null]
```

Object
------

[](#object)

Use function `object` to create an `ObjectParameter`. Pass a `className` to restrict the accepted class.

```
use function Chevere\Parameter\object;

$object = object(stdClass::class);
$object(new stdClass()); // stdClass instance
```

Mixed
-----

[](#mixed)

Use function `mixed` to create a `MixedParameter`. Accepts any value.

```
use function Chevere\Parameter\mixed;

$any = mixed();
$any(1);
$any('hello');
$any(null);
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_mixed;

#[_mixed]
```

Union
-----

[](#union)

Use function `union` to create a `UnionParameter`. The value must match at least one of the provided parameters.

```
use function Chevere\Parameter\union;
use function Chevere\Parameter\int;
use function Chevere\Parameter\null;
use function Chevere\Parameter\intString;
use function Chevere\Parameter\string;

// Nullable string
$union = union(string(), null());
$union('hello'); // 'hello'
$union(null);    // null

// Accept both digit strings and integers
$union = union(intString(), int());
$union('100'); // '100'
$union(100);   // 100
```

UnionNull
---------

[](#unionnull)

You can also use `unionNull()` as a shorthand for nullable unions:

```
use function Chevere\Parameter\unionNull;
use function Chevere\Parameter\int;

$maybeInt = unionNull(int(min: 1));
$maybeInt(5);    // 5
$maybeInt(null); // null
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_null;
use Chevere\Parameter\Attributes\_int;

#[_unionNull(
    new _int()
)]
```

Array
-----

[](#array)

The array parameter validates each member of an associative array against its own parameter definition.

Use function `arrayp` to create an `ArrayParameter`.

```
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\int;
use function Chevere\Parameter\string;

// Empty array
$array = arrayp();
$array([]); // []

// Required keys
$user = arrayp(
    id: int(min: 1),
    name: string('/^[A-Z][a-z]+$/'),
);
$user(['id' => 1, 'name' => 'Rodolfo']);
```

Nested arrays of any depth are supported:

```
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\float;
use function Chevere\Parameter\int;

$order = arrayp(
    id: int(min: 0),
    item: arrayp(
        sku: int(min: 0),
        price: float(min: 0),
    ),
);
$order([
    'id' => 1,
    'item' => [
        'sku' => 25,
        'price' => 16.50,
    ],
]);
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_arrayp;
use Chevere\Parameter\Attributes\_float;
use Chevere\Parameter\Attributes\_int;

#[_arrayp(
    id: new _int(),
    item: new _arrayp(
        sku: new _int(),
        price: new _float(),
    ),
)]
```

### Modifying array parameters

[](#modifying-array-parameters)

Array parameters provide methods to add, modify, and remove keys.

#### withRequired

[](#withrequired)

Add required keys.

```
$array = $array->withRequired(
    username: string(),
    email: string(),
);
```

#### withOptional

[](#withoptional)

Add optional keys. Optional parameters are validated only when a matching key is present.

```
$array = $array->withOptional(
    address: string(),
);
```

#### withModify

[](#withmodify)

Replace the definition of an existing key.

```
$array = $array->withModify(
    username: string('/^\w+$/'),
);
```

#### withMakeOptional

[](#withmakeoptional)

Convert a required key to optional.

```
$array = $array->withMakeOptional('username');
```

#### withMakeRequired

[](#withmakerequired)

Convert an optional key to required.

```
$array = $array->withMakeRequired('email');
```

#### without

[](#without)

Remove keys.

```
$array = $array->without('address');
```

#### withOptionalMinimum

[](#withoptionalminimum)

Require at least `n` optional parameters to be present. Useful when all keys are optional but at least one is expected.

```
$array = $array->withOptionalMinimum(1);
```

### Array-based derived types

[](#array-based-derived-types)

#### Array String

[](#array-string)

An array parameter accepting only string values.

```
use function Chevere\Parameter\arrayString;
use function Chevere\Parameter\string;

$headers = arrayString(
    accept: string('/^application\/json$/'),
);
$headers(['accept' => 'application/json']);
```

#### File

[](#file)

An array parameter matching the `$_FILES` upload shape. Customize individual fields as needed.

```
use function Chevere\Parameter\file;
use function Chevere\Parameter\string;

// Default $_FILES shape validation
$upload = file();
$upload([
    'name' => 'report.pdf',
    'type' => 'application/pdf',
    'tmp_name' => '/tmp/phpABC123',
    'error' => 0,
    'size' => 4096,
]);

// With custom rules
$upload = file(
    name: string('/\.csv$/'),
    contents: string('/^id,name/'),
);
```

Iterable
--------

[](#iterable)

Validates each item in a `Traversable|array` against a generic key/value definition. Use this to define collections of items sharing the same shape.

Use function `iterable` to create an `IterableParameter`. Pass `V` for the value parameter and optionally `K` for the key parameter (defaults to `int`).

```
use function Chevere\Parameter\int;
use function Chevere\Parameter\iterable;

// List of non-negative integers
$ids = iterable(int(min: 0));
$ids([0, 1, 2, 3]);
```

With named string keys and structured values:

```
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\int;
use function Chevere\Parameter\iterable;
use function Chevere\Parameter\string;

$roster = iterable(
    V: arrayp(
        id: int(min: 0),
        name: string('/^[\w]{1,255}$/'),
    ),
    K: string(),
);
$roster([
    'player1' => [
        'id' => 1,
        'name' => 'OscarGangas',
    ],
    'player2' => [
        'id' => 2,
        'name' => 'BomboFica',
    ],
]);
```

Attribute notation:

```
use Chevere\Parameter\Attributes\_int;
use Chevere\Parameter\Attributes\_iterable;

#[_iterable(
    new _int(min: 0),
)]
```

Inline validation
-----------------

[](#inline-validation)

Inline validation is the direct use of parameter functions to validate values. Create the parameter and then invoke it with the value.

```
use function Chevere\Parameter\string;
use function Chevere\Parameter\int;
use function Chevere\Parameter\float;
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\iterable;
use function Chevere\Parameter\union;
use function Chevere\Parameter\null;

// String starting with "a"
string('/^a.+/')('ahhh');

// Integer in range
int(min: 1, max: 100)(50);

// Integer whitelist
int(accept: [1, 2, 3])(2);

// Float blacklist
float(reject: [1.1, 2.1])(3.14);

// Structured array
arrayp(
    id: int(min: 1),
    name: string('/^[A-Z]{1}\w+$/'),
)(['id' => 1, 'name' => 'Pepe']);

// Iterable with key rules
iterable(
    K: string('/ila$/'),
    V: int(min: 1),
)(['unila' => 1, 'dorila' => 2, 'tirifila' => 3]);

// Nullable integer
union(int(), null())(null);
```

Attribute-based validation
--------------------------

[](#attribute-based-validation)

Use PHP 8 attributes to declare validation rules directly on function/method signatures. This keeps constraints co-located with the code they protect.

### Attribute delegated validation

[](#attribute-delegated-validation)

Call `validated()` to validate both arguments and return value against attribute rules.

```
use Chevere\Parameter\Attributes\_int;
use Chevere\Parameter\Attributes\_return;
use Chevere\Parameter\Attributes\_string;
use function Chevere\Parameter\validated;

#[_return(
    new String('/ok$/')
)]
function process(
    #[Int(min: 1, max: 10)]
    int $var,
): string {
    return 'done ok';
}

$result = validated('process', 5); // 'done ok'
```

For manual control, use `reflectionToParameters` and `reflectionToReturn` to extract and apply rules separately:

```
use ReflectionFunction;
use function Chevere\Parameter\reflectionToParameters;
use function Chevere\Parameter\reflectionToReturn;

$reflection = new ReflectionFunction('process');
$parameters = reflectionToParameters($reflection);
$return = reflectionToReturn($reflection);

$parameters(...$args);               // validate arguments
$result = process(...$args);          // call
$return($result);                     // validate return
```

### Attribute inline validation

[](#attribute-inline-validation)

Use `assertArguments()` inside the function body for granular control over when validation runs.

```
use Chevere\Parameter\Attributes\_enum;
use Chevere\Parameter\Attributes\_float;
use function Chevere\Parameter\Attributes\assertArguments;

function myEnum(
    #[_enum('Hugo', 'Paco', 'Luis')]
    string $name,
    #[_float(min: 1000)]
    float $money,
): void {
    // Validate all arguments
    assertArguments();
    // Or validate specific ones
    assertArguments('name');
    assertArguments('money');
}

myEnum('Paco', 1000.50);
```

Use `assertReturn()` to validate the return value inline:

```
use Chevere\Parameter\Attributes\_int;
use Chevere\Parameter\Attributes\_return;
use function Chevere\Parameter\Attributes\assertReturn;

#[_return(
    new _int(min: 0, max: 5)
)]
function clamp(): int
{
    $result = 3;

    return assertReturn($result);
}
```

### \_return

[](#_return)

Defines a validation rule for the return value of a function or method.

```
use Chevere\Parameter\Attributes\_return;
use Chevere\Parameter\Attributes\_string;

#[_return(
    new _string('/ok$/')
)]
function myFunction(): string
{
    return 'done ok';
}
```

> By convention, when `_return` is omitted the method `public static function return(): ParameterInterface` (if any) will be used to determine return validation rules.

### \_callable

[](#_callable)

PHP attributes only support constant expressions. To define dynamic parameters (e.g., nested arrays with optional keys), use `_callable` to delegate parameter resolution to a callable.

```
use Chevere\Parameter\Interfaces\ParameterInterface;
use Chevere\Parameter\Attributes\_callable;
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\string;

function contactSchema(): ParameterInterface
{
    return arrayp(
        email: string(),
    )->withOptional(
        name: string(),
    );
}

function saveContact(
    #[_callable('contactSchema')]
    array $contact,
): void {
    // ...
}
```

### Native attributes support

[](#native-attributes-support)

Parameter recognizes native PHP attribute annotations and works alongside them.

```
use SensitiveParameter;
use Chevere\Parameter\Attributes\_int;

function authenticate(
    #[SensitiveParameter]
    #[_int(min: 1)]
    int $token,
): void {
    // $token value will be omitted from error messages
}
```

Arguments
---------

[](#arguments)

The `Arguments` object is the validated counterpart to `Parameters`. It holds argument values that have been validated against a `Parameters` instance, providing type-safe access by name.

### Creating arguments

[](#creating-arguments)

```
use function Chevere\Parameter\parameters;
use function Chevere\Parameter\arguments;
use function Chevere\Parameter\int;
use function Chevere\Parameter\string;

$parameters = parameters(
    id: int(min: 1),
    name: string('/^[A-Z]{1}\w+$/'),
)->withOptional(
    email: string(),
);

$arguments = arguments($parameters, [
    'id' => 1,
    'name' => 'Pepe',
]);
```

### Checking and retrieving values

[](#checking-and-retrieving-values)

```
// Check existence
$arguments->has('id');    // true
$arguments->has('nope');  // false

// Get as mixed
$id = $arguments->get('id'); // 1

// Get with type safety
$id = $arguments->required('id')->int();       // 1
$email = $arguments->optional('email')?->string(); // null
```

### Modifying arguments

[](#modifying-arguments)

Use `withPut()` to create a new instance with an added or replaced argument.

```
$arguments = $arguments->withPut('email', 'mail@chevere.org');
```

### Converting to array

[](#converting-to-array)

```
// Only provided arguments
$array = $arguments->toArray();

// Including optional parameters filled with a default
$array = $arguments->toArrayFill(null);
```

### Nested arguments

[](#nested-arguments)

Access nested validated data structures using `nested()`.

```
use function Chevere\Parameter\parameters;
use function Chevere\Parameter\arguments;
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\string;

$parameters = parameters(
    meta: arrayp(
        custom_data: arrayp(
            product: string(),
            product_id_external: string(),
        ),
    ),
);
$data = [
    'meta' => [
        'custom_data' => [
            'product' => 'Book',
            'product_id_external' => 'book_987654321',
        ],
    ],
];
$arguments = arguments($parameters, $data);
$product = $arguments
    ->nested('meta', 'custom_data')
    ->required('product')->string(); // 'Book'
```

Type-safe access with `typed()`
-------------------------------

[](#type-safe-access-with-typed)

Use function `typed` to get a `TypedInterface` accessor for any variable, enabling safe type casting with optional deep array access.

```
use function Chevere\Parameter\typed;

$data = ['user' => ['age' => 30]];
$age = typed($data, 'user', 'age')->int(); // 30
```

Cast helpers
------------

[](#cast-helpers)

### castArguments

[](#castarguments)

Casts argument values to match the types defined by parameters, then validates. Useful for loosely-typed input (e.g., query strings).

```
use function Chevere\Parameter\castArguments;
use function Chevere\Parameter\parameters;
use function Chevere\Parameter\int;
use function Chevere\Parameter\bool;

$parameters = parameters(
    page: int(min: 1),
    active: bool(),
);
$arguments = castArguments($parameters, [
    'page' => '3',     // cast to int
    'active' => '1',   // cast to bool
]);
```

### castValues

[](#castvalues)

Returns the casted values as an array without creating an `Arguments` instance.

```
use function Chevere\Parameter\castValues;

$values = castValues($parameters, ['page' => '3', 'active' => '1']);
// ['page' => 3, 'active' => true]
```

Parameters
----------

[](#parameters)

The `Parameters` object collects parameter definitions and validates arguments against them.

### Creating parameters

[](#creating-parameters)

```
use function Chevere\Parameter\parameters;
use function Chevere\Parameter\int;
use function Chevere\Parameter\string;

// Required parameters via named arguments
$params = parameters(
    id: int(min: 1),
    name: string(),
);
```

### Adding and modifying

[](#adding-and-modifying)

```
// Add optional parameters
$params = $params->withOptional('email', string());

// Make a required parameter optional
$params = $params->withMakeOptional('name');

// Make an optional parameter required
$params = $params->withMakeRequired('email');

// Remove a parameter
$params = $params->without('email');

// Merge with another Parameters instance
$params = $params->withMerge($otherParameters);

// Require at least n optional parameters
$params = $params->withOptionalMinimum(1);
```

### Querying

[](#querying)

```
$params->has('id');          // true
$params->requiredKeys();     // VectorInterface
$params->optionalKeys();     // VectorInterface
$params->optionalMinimum();  // int
$params->get('id');          // ParameterInterface
```

### Direct invocation

[](#direct-invocation)

Invoke a `Parameters` instance to validate named arguments and get an `Arguments` instance back.

```
$arguments = $params(id: 1, name: 'Rodolfo');
```

Helpers
-------

[](#helpers)

### toParameter

[](#toparameter)

Create a `ParameterInterface` from a type string.

```
use function Chevere\Parameter\toParameter;

$param = toParameter('int'); // IntParameter
```

### toUnionParameter

[](#tounionparameter)

Create a `UnionParameter` from multiple type strings.

```
use function Chevere\Parameter\toUnionParameter;

$param = toUnionParameter('int', 'string'); // UnionParameter
```

### assertNamedArgument

[](#assertnamedargument)

Assert a single named argument against a parameter.

```
use function Chevere\Parameter\assertNamedArgument;
use function Chevere\Parameter\int;

assertNamedArgument(
    name: 'age',
    parameter: int(min: 0),
    argument: 25,
);
```

### arrayFrom

[](#arrayfrom)

Create an `ArrayParameter` from selected keys of another array parameter.

```
use function Chevere\Parameter\arrayFrom;
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\int;
use function Chevere\Parameter\string;

$source = arrayp(
    id: int(),
    name: string(),
    email: string(),
    age: int(),
);
$subset = arrayFrom($source, 'name', 'id');
```

### takeKeys

[](#takekeys)

Retrieve an array of key names from a parameter.

```
use function Chevere\Parameter\takeKeys;
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\int;

$keys = takeKeys(arrayp(id: int(), size: int()));
// ['id', 'size']
```

### takeOne

[](#takeone)

Retrieve a single key-parameter pair as an array.

```
use function Chevere\Parameter\takeOne;
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\int;
use function Chevere\Parameter\string;

$array = arrayp(
    id: int(min: 0),
    size: int(min: 100),
    name: string(),
);
$parameter = takeOne($array, 'size');
```

### takeFrom

[](#takefrom)

Retrieve an iterator yielding selected key-parameter pairs.

```
use function Chevere\Parameter\takeFrom;
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\int;
use function Chevere\Parameter\string;

$array = arrayp(
    id: int(min: 0),
    size: int(min: 100),
    name: string(),
);
$iterator = takeFrom($array, 'size', 'name');
```

### parametersFrom

[](#parametersfrom)

Create a `Parameters` instance from selected keys of a parameter.

```
use function Chevere\Parameter\parametersFrom;
use function Chevere\Parameter\arrayp;
use function Chevere\Parameter\int;
use function Chevere\Parameter\string;

$array = arrayp(
    id: int(min: 0),
    size: int(min: 100),
    name: string(),
);
$parameters = parametersFrom($array, 'size', 'name');
```

### getParameters

[](#getparameters)

Retrieve a `Parameters` instance from an object implementing `ParametersAccessInterface` or `ParametersInterface`.

```
use function Chevere\Parameter\getParameters;

$parameters = getParameters($object);
```

### getType

[](#gettype)

Get the type name of a variable as defined by this library.

```
use function Chevere\Parameter\getType;

getType(1);     // 'int'
getType(true);  // 'bool'
getType(1.5);   // 'float'
getType(null);  // 'null'
```

### parameterAttribute

[](#parameterattribute)

Retrieve a `ParameterAttributeInterface` from a function or method parameter by name.

```
use function Chevere\Parameter\parameterAttribute;
use Chevere\Parameter\Attributes\_string;

function myFunction(
    #[_string('/^bin-[\d]+$/')]
    string $foo,
): void {
    // ...
}

$attr = parameterAttribute('foo', 'myFunction');
$attr('bin-123'); // validates
```

### reflectionToParameter

[](#reflectiontoparameter)

Retrieve a `ParameterInterface` instance from a `ReflectionProperty` or `ReflectionParameter`.

```
use function Chevere\Parameter\reflectionToParameter;
;
$parameter = reflectionToParameter($reflection);
```

### reflectionToParameters

[](#reflectiontoparameters)

Retrieve a `ParametersInterface` instance from a `ReflectionFunction` or `ReflectionMethod`.

```
use function Chevere\Parameter\reflectionToParameters;

$parameters = reflectionToParameters($reflection);
```

### reflectionToReturn

[](#reflectiontoreturn)

Retrieve a `ParameterInterface` instance for the return type from a `ReflectionFunction` or `ReflectionMethod`.

```
use function Chevere\Parameter\reflectionToReturn;

$return = reflectionToReturn($reflection);
```

### validated

[](#validated)

Validate function/method arguments and return value in one call.

```
use function Chevere\Parameter\validated;

$result = validated('myFunction', $arg1, $arg2);
```

Advanced examples
-----------------

[](#advanced-examples)

### Nested array with attribute validation

[](#nested-array-with-attribute-validation)

```
use Chevere\Parameter\Attributes\_arrayp;
use Chevere\Parameter\Attributes\_int;
use Chevere\Parameter\Attributes\_string;
use Chevere\Parameter\Attributes\_iterable;
use function Chevere\Parameter\Attributes\assertArguments;

function createUser(
    #[_arrayp(
        id: new _int(min: 1),
        role: new _arrayp(
            mask: new _int(accept: [64, 128, 256]),
            name: new _string('/[a-z]+/'),
            tenants: new _iterable(
                new _int(min: 1)
            ),
        ),
    )]
    array $user,
): void {
    assertArguments();
}

createUser([
    'id' => 10,
    'role' => [
        'mask' => 128,
        'name' => 'admin',
        'tenants' => [1, 2, 3, 4, 5],
    ],
]);
```

### Validating a return array

[](#validating-a-return-array)

```
use Chevere\Parameter\Attributes\_arrayp;
use Chevere\Parameter\Attributes\_int;
use Chevere\Parameter\Attributes\_string;
use Chevere\Parameter\Attributes\_return;
use function Chevere\Parameter\Attributes\assertReturn;

#[_return(
    new _arrayp(
        id: new _int(min: 0),
        name: new _string(),
    )
)]
function fetchUser(): array
{
    $result = [
        'id' => 1,
        'name' => 'Peoples Hernandez',
    ];

    return assertReturn($result);
}
```

### Using reflection for method validation

[](#using-reflection-for-method-validation)

```
use ReflectionMethod;
use Chevere\Parameter\Attributes\_int;
use function Chevere\Parameter\reflectionToParameters;

$class = new class() {
    public function score(
        #[_int(accept: [1, 10, 100])]
        int $base,
    ): void {
    }
};

$reflection = new ReflectionMethod($class, 'score');
$parameters = reflectionToParameters($reflection);
$parameters(base: 10); // validates
```

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

[](#documentation)

Documentation is available at [chevere.org/packages/parameter](https://chevere.org/packages/parameter).

License
-------

[](#license)

Copyright [Rodolfo Berrios A.](https://rodolfoberrios.com/)

Chevere is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

###  Health Score

51

—

FairBetter than 96% of packages

Maintenance78

Regular maintenance activity

Popularity35

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity60

Established project with proven stability

 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.

###  Release Activity

Cadence

Every ~36 days

Recently: every ~6 days

Total

23

Last Release

52d ago

Major Versions

1.3.x-dev → 2.0.02026-02-20

### Community

Maintainers

![](https://www.gravatar.com/avatar/a87fbbcb1518fe64878bc53dedd9f61b81243cbb21b73c26f5e299d501375984?d=identicon)[rodolfo](/maintainers/rodolfo)

---

Top Contributors

[![rodber](https://avatars.githubusercontent.com/u/20590102?v=4)](https://github.com/rodber "rodber (236 commits)")

---

Tags

cheverephpphp-library

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleECS

Type Coverage Yes

### Embed Badge

![Health badge](/badges/chevere-parameter/health.svg)

```
[![Health](https://phpackages.com/badges/chevere-parameter/health.svg)](https://phpackages.com/packages/chevere-parameter)
```

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)[crazybooot/base64-validation

Laravel validators for base64 encoded files

1341.9M8](/packages/crazybooot-base64-validation)

PHPackages © 2026

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