Download the PHP package chevere/parameter without Composer
On this page you can find all versions of the php package chevere/parameter. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download chevere/parameter
More information about chevere/parameter
Files in chevere/parameter
Package parameter
Short Description Dynamic parameter-argument validation for PHP with rich type constraints, attributes, and schema introspection.
License Apache-2.0
Homepage https://chevere.org
Informations about the package parameter
Parameter
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: Implements the action design pattern for encapsulating business logic, utilizing this package for comprehensive parameter validation.
- chevere/router: Offers powerful routing with built-in parameter validation for handling HTTP requests and responses.
- chevere/sql2p: Transforms SQL queries into parameter definitions, enabling automated validation of database inputs and outputs.
- chevere/workflow: Provides a workflow engine for defining and executing multi-step processes, using this package for parameter validation across workflow jobs.
Installing
Parameter is available through Packagist and the repository source is at chevere/parameter.
Quick start
Validate a single value
Create a parameter with rules and invoke it to validate. If validation fails, an exception is thrown.
Validate multiple values
Compose parameters to validate structured data in a single call.
Validate function arguments with attributes
Decorate functions with attributes and call validated() to enforce rules on both arguments and return values automatically.
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.
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:
| Strategy | How | Best for |
|---|---|---|
| Inline | int(min: 1)($value) |
Quick checks, scripts |
| Attribute delegated | validated('fn', ...$args) |
Functions, controllers |
| Attribute inline | assertArguments() inside body |
Granular control |
Reference
Core types
| Type | Helper | Attribute | Description |
|---|---|---|---|
| String | string |
_string |
String, optionally matching a regex |
| Int | int |
_int |
Integer with optional range/accept/reject |
| Float | float |
_float |
Float with optional range/accept/reject |
| Bool | bool |
_bool |
Boolean |
| Null | null |
_null |
Null |
| Object | object |
— | Object of a given class |
| Mixed | mixed |
_mixed |
Any type |
| Array | arrayp |
_arrayp |
Array with named parameters |
| Iterable | iterable |
_iterable |
Iterable with generic key/value |
| Union | union |
_union |
Value matching at least one parameter |
| UnionNull | unionNull |
_unionNull |
Value matching at least one parameter or null |
Derived types
String-based parameters:
| Type | Helper | Description |
|---|---|---|
| Enum | enum |
String matching a fixed list |
| IntString | intString |
String of digits |
| BoolString | boolString |
"0" or "1" |
| Date | date |
YYYY-MM-DD string |
| Time | time |
hh:mm:ss string |
| Datetime | datetime |
YYYY-MM-DD hh:mm:ss string |
Int-based parameters:
| Type | Helper | Description |
|---|---|---|
| BoolInt | boolInt |
0 or 1 integer |
Array-based parameters:
| Type | Helper | Description |
|---|---|---|
| ArrayString | arrayString |
Array with string values only |
| File | file |
$_FILES upload shape |
Nullable helpers
Shorthand functions that create a union of a type with null:
| Helper | Equivalent 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.
Special attributes
| Attribute | Description |
|---|---|
| _callable | Forward parameter resolution to a callable |
| _return | Return value validation |
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
Every with* method returns a new instance preserving the original state. This enables building parameter variations from a base definition without side effects.
Common methods available on all parameters:
Methods specific to each parameter type:
| Parameter | Immutable 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
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.
String
Use function string to create a StringParameter. Pass a regex for pattern matching.
Attribute notation:
String-based derived types
Enum string
Matches one of a fixed list of strings.
Attribute notation:
Int string
Matches strings representing integer digits.
Bool string
Matches "0" and "1" strings.
Date string
Matches YYYY-MM-DD date strings.
Time string
Matches hh:mm:ss time strings.
Datetime string
Matches YYYY-MM-DD hh:mm:ss datetime strings. Supports an optional precision argument for fractional seconds.
Int
Use function int to create an IntParameter. Supports min, max, accept (whitelist), and reject (blacklist).
Attribute notation:
Int-based derived types
Bool int
Matches 0 or 1 integers.
Float
Use function float to create a FloatParameter. Supports min, max, accept, and reject.
Attribute notation:
Bool
Use function bool to create a BoolParameter.
Attribute notation:
Null
Use function null to create a NullParameter.
Attribute notation:
Object
Use function object to create an ObjectParameter. Pass a className to restrict the accepted class.
Mixed
Use function mixed to create a MixedParameter. Accepts any value.
Attribute notation:
Union
Use function union to create a UnionParameter. The value must match at least one of the provided parameters.
UnionNull
You can also use unionNull() as a shorthand for nullable unions:
Attribute notation:
Array
The array parameter validates each member of an associative array against its own parameter definition.
Use function arrayp to create an ArrayParameter.
Nested arrays of any depth are supported:
Attribute notation:
Modifying array parameters
Array parameters provide methods to add, modify, and remove keys.
withRequired
Add required keys.
withOptional
Add optional keys. Optional parameters are validated only when a matching key is present.
withModify
Replace the definition of an existing key.
withMakeOptional
Convert a required key to optional.
withMakeRequired
Convert an optional key to required.
without
Remove keys.
withOptionalMinimum
Require at least n optional parameters to be present. Useful when all keys are optional but at least one is expected.
Array-based derived types
Array String
An array parameter accepting only string values.
File
An array parameter matching the $_FILES upload shape. Customize individual fields as needed.
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).
With named string keys and structured values:
Attribute notation:
Inline validation
Inline validation is the direct use of parameter functions to validate values. Create the parameter and then invoke it with the value.
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
Call validated() to validate both arguments and return value against attribute rules.
For manual control, use reflectionToParameters and reflectionToReturn to extract and apply rules separately:
Attribute inline validation
Use assertArguments() inside the function body for granular control over when validation runs.
Use assertReturn() to validate the return value inline:
_return
Defines a validation rule for the return value of a function or method.
By convention, when
_returnis omitted the methodpublic static function return(): ParameterInterface(if any) will be used to determine return validation rules.
_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.
Native attributes support
Parameter recognizes native PHP attribute annotations and works alongside them.
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
Checking and retrieving values
Modifying arguments
Use withPut() to create a new instance with an added or replaced argument.
Converting to array
Nested arguments
Access nested validated data structures using nested().
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.
Cast helpers
castArguments
Casts argument values to match the types defined by parameters, then validates. Useful for loosely-typed input (e.g., query strings).
castValues
Returns the casted values as an array without creating an Arguments instance.
Parameters
The Parameters object collects parameter definitions and validates arguments against them.
Creating parameters
Adding and modifying
Querying
Direct invocation
Invoke a Parameters instance to validate named arguments and get an Arguments instance back.
Helpers
toParameter
Create a ParameterInterface from a type string.
toUnionParameter
Create a UnionParameter from multiple type strings.
assertNamedArgument
Assert a single named argument against a parameter.
arrayFrom
Create an ArrayParameter from selected keys of another array parameter.
takeKeys
Retrieve an array of key names from a parameter.
takeOne
Retrieve a single key-parameter pair as an array.
takeFrom
Retrieve an iterator yielding selected key-parameter pairs.
parametersFrom
Create a Parameters instance from selected keys of a parameter.
getParameters
Retrieve a Parameters instance from an object implementing ParametersAccessInterface or ParametersInterface.
getType
Get the type name of a variable as defined by this library.
parameterAttribute
Retrieve a ParameterAttributeInterface from a function or method parameter by name.
reflectionToParameter
Retrieve a ParameterInterface instance from a ReflectionProperty or ReflectionParameter.
reflectionToParameters
Retrieve a ParametersInterface instance from a ReflectionFunction or ReflectionMethod.
Pass an array by reference as $violations to collect all logic violations instead of failing fast on the first one.
When $violations is null (default), the function throws on the first reflection error. When an array is passed, errors are collected and the function continues processing remaining parameters.
reflectionToReturn
Retrieve a ParameterInterface instance for the return type from a ReflectionFunction or ReflectionMethod.
validated
Validate function/method arguments and return value in one call.
Advanced examples
Nested array with attribute validation
Validating a return array
Using reflection for method validation
Documentation
Documentation is available at chevere.org/packages/parameter.
License
Copyright Rodolfo Berrios A.
Chevere is licensed under the Apache License, Version 2.0. See 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.
All versions of parameter with dependencies
chevere/data-structure Version ^1.1.0
chevere/message Version ^1.0.0
chevere/regex Version ^1.0.1