parameter is a library around parameter-argument which provides additional functionality with validation rules and schema introspection.
parameter is available through Packagist and the repository source is at chevere/parameter.
composer require chevere/parameterparameter enables to spawn dynamic parameters of any type with extra rules.
For example, an integer of minimum value 10.
use function Chevereparameterint;
$int = int(min: 10);
$int($var); // exception if $var < 10In function or method parameters you can use attributes to define validation rules for parameters and return value.
use ChevereparameterAttributesFloatAttr;
use ChevereparameterAttributesIntAttr;
use ChevereparameterAttributesReturnAttr;
use function ChevereparameterreturnAttr;
use function Chevereparametervalidated;
#[ReturnAttr(
new FloatAttr(min: 0, max: 2400)
)]
function wageWeekWA(
#[IntAttr(min: 1628)]
int $cents,
#[FloatAttr(min: 0, max: 40)]
float $hours
) {
return $cents*$hours/100;
}
validated('wageWeekWA', $cents, $hours);Validation can be triggered using validated (example above), inline and/or delegated to a caller wrapper. parameter provides helpers to access rules for both parameters and return value to ease wiring process.
Rules defined by each parameter provide a human-readable schema which allows to expose the validation criteria.
parameter provides an API which can be used to create parameters using functions and/or attributes. parameter objects can be used directly in the logic while attributes requires a read step.
Use inline validation to go from this:
if($var > 10 || $var < 1) {
throw new InvalidArgumentException();
}To this:
use function Chevereparameterint;
int(min: 1, max: 10)($var);Use attributes to define rules for parameters and return value.
Use attribute delegated validation with the validated() function to go from this:
function myFunction(int $var): string
{
if($var > 10 || $var < 1) {
throw new InvalidArgumentException();
}
$return = 'done ok';
return preg_match('/ok$/', $return)
? $return
: throw new InvalidArgumentException();
}
$result = myFunction($var);To this:
use ChevereparameterAttributesIntAttr;
use ChevereparameterAttributesReturnAttr;
use ChevereparameterAttributesStringAttr;
use function Chevereparametervalidated;
#[ReturnAttr(
new StringAttr('/ok$/')
)]
function myFunction(
#[IntAttr(min: 1, max: 10)]
int $var
): string
{
return 'done ok';
}
$result = validated('myFunction', $var);Use reflectionToparameters and reflectionToReturn functions for manual validation for arguments and return value:
use ReflectionFunction;
use function ChevereparameterreflectionToparameters;
use function ChevereparameterreflectionToReturn;
$reflection = new ReflectionFunction('myFunction');
$parameters = reflectionToparameters($reflection);
$return = reflectionToReturn($reflection);
$parameters(...$args); // valid $args
$result = myFunction(...$args); // myFunction call
$return($result); // valid $resultUse attribute inline validation for manual validation within the function body:
use ChevereparameterAttributesIntAttr;
use ChevereparameterAttributesReturnAttr;
use ChevereparameterAttributesStringAttr;
use function Chevereparametervalid;
use function ChevereparameterreturnAttr;
#[ReturnAttr(
new StringAttr('/ok$/')
)]
function myFunction(
#[IntAttr(min: 1, max: 10)]
int $var
): string
{
valid(); // valid $var
$return = 'ok';
return returnAttr()($return); // valid $return
}Attributes in PHP only support expressions you can use on class constants. Is not possible to directly define dynamic parameters using attributes.
To avoid this limitation you can use CallableAttr attribute which enables to forward parameter resolution to a callable returning a parameterInterface instance.
use ChevereparameterInterfacesparameterInterface;
use ChevereparameterAttributesCallableAttr;
function myCallable(): parameterInterface
{
return arrayp(
email: string(),
)->withOptional(
name: string(),
);
}
#[CallableAttr('myCallable')]A parameter is an object implementing parameterInterface. Every parameter can define a description and a default value, plus additional validation rules depending on the type.
A parameter can be defined using functions and/or attributes, it takes same arguments for both.
When invoking a parameter $param('value') it will trigger validation against the passed argument.
Use function string to create a Stringparameter. Pass a regex for string matching.
use function Chevereparameterstring;
// Any string
$string = string();
// String matching bin-<digits>
$string = string('/^bin-[d]+$/');
$string('bin-123');Use StringAttr attribute to define a string parameter.
use ChevereparameterAttributesStringAttr;
#[StringAttr('/^bin-[d]+$/')]The following parameters are based on String.
Use function enum to create a Stringparameter matching a list of strings.
use function Chevereparameterenum;
$enum = enum('on', 'off');
$enum('on');
$enum('off');Use EnumAttr attribute to define an enum string parameter.
use ChevereparameterAttributesEnumAttr;
#[EnumAttr('on', 'off')]Use function intString to create a Stringparameter matching a string integers.
use function ChevereparameterintString;
$int = intString();
$int('100');Use function boolString to create a Stringparameter matching 0 and 1 strings.
use function ChevereparameterboolString;
$bool = boolString();
$bool('0');
$bool('1');Use function date to create a Stringparameter matching YYYY-MM-DD strings.
use function Chevereparameterdate;
$date = date();
$date('2021-01-01');Use function time to create a Stringparameter matching hh:mm:ss strings.
use function Chevereparametertime;
$time = time();
$time('12:00:00');Use function datetime to create a Stringparameter matching YYYY-MM-DD hh:mm:ss strings.
use function Chevereparameterdatetime;
$datetime = datetime();
$datetime('2024-01-09 10:53:00');Use function int to create a Intparameter. Pass min and max values for integer range, accept for a list of accepted integers and reject for a list of rejected integers.
use function Chevereparameterint;
// Any int
$int = int();
$int(1);
// Integer between 0 and 100
$int = int(min: 0, max: 100);
$int(50);
// Integer matching 1, 2 or 3
$int = int(accept: [1, 2, 3]);
$int(2);
// Integer not-matching 1, 2 or 3
$int = int(reject: [1, 2, 3]);
$int(4);Use IntAttr attribute to define an integer parameter.
use ChevereparameterAttributesIntAttr;
#[IntAttr(min: 0, max: 100)]The following parameters are based on Int.
Use function boolInt to create a Intparameter matching 0 and 1 integers.
use function ChevereparameterboolInt;
$bool = boolInt();
$bool(0);
$bool(1);Use function float to create a Floatparameter. Pass min and max values for float range, accept for a list of accepted floats and reject for a list of rejected floats.
use function Chevereparameterfloat;
// Any float
$float = float();
$float(1.5);
// Float between 0 and 100
$float = float(min: 0, max: 100);
$float(50.5);
// Float matching 1.5, 2.5 or 3.5
$float = float(accept: [1.5, 2.5, 3.5]);
$float(2.5);
// Float not-matching 1.5, 2.5 or 3.5
$float = float(reject: [1.5, 2.5, 3.5]);
$float(4.5);Use FloatAttr attribute to define a float parameter.
use ChevereparameterAttributesFloatAttr;
#[FloatAttr(min: 0, max: 100)]Use function bool to create a Boolparameter.
use function Chevereparameterbool;
$bool = bool();
$bool(true);
$bool(false);Use BoolAttr attribute to define a bool parameter.
use ChevereparameterAttributesBoolAttr;
#[BoolAttr]Use function null to create a Nullparameter.
use function Chevereparameternull;
$null = null();
$null(null);Use NullAttr attribute to define a null parameter.
use ChevereparameterAttributesNullAttr;
#[NullAttr]Use function object to create a Objectparameter. Pass a className for the object class name.
use function Chevereparameterobject;
$object = object(stdClass::class);
$object(new stdClass());Use ObjectAttr attribute to define an object parameter.
use ChevereparameterAttributesObjectAttr;
#[ObjectAttr(stdClass::class)]Use function mixed to create a Mixedparameter.
use function Chevereparametermixed;
$mixed = mixed();
$mixed(1);
$mixed('1');
$mixed(true);
$mixed(null);Use function union to create a Unionparameter. Pass a list of parameters to match, target value must match at least one.
use function Chevereparameterunion;
// Any string or null
$union = union(string(), null());
$union('abc');
$union(null);
// Any digit string or any integer
$union = union(
intString(),
integer()
);
$union('100');
$union(100);parameter for type array is handled as a composite parameter holding parameter definition for each one of its members.
Use function arrayp to create an Arrayparameter for named arguments as required array keys.
use function Chevereparameterarrayp;
// Empty array
$array = arrayp();
$array([]);
// Required 'a' => <string>
$array = arrayp(a: string());
$array(['a' => 'Hello world']);parameter supports nested arrays of any depth:
use function Chevereparameterarrayp;
use function Chevereparameterfloat;
use function Chevereparameterint;
$array = arrayp(
id: int(min: 0),
items: arrayp(
id: int(min: 0),
price: float(min: 0),
),
);
$array([
'id' => 1,
'items' => [
'id' => 25,
'price' => 16.5,
]
]);Use ArrayAttr attribute to define an array parameter.
use ChevereparameterAttributesArrayAttr;
use ChevereparameterAttributesFloatAttr;
use ChevereparameterAttributesIntAttr;
#[ArrayAttr(
id: new IntAttr(),
items: new ArrayAttr(
id: new IntAttr(),
price: new FloatAttr(),
),
)]use method withRequired to define required parameters.
$array = $array
->withRequired(
username: string(),
email: string()
);use method withOptional to define optional parameters.
$array = $array
->withOptional(address: string());Note: Optional parameters will be validated only if a matching key is provided.
use method withModify to define modify parameters.
$array = $array
->withModify(
username: string('/w+/'),
);use method withMakeOptional to make required parameters optional.
$array = $array
->withMakeOptional('username');use method withMakeRequired to make optional parameters required.
$array = $array
->withMakeRequired('email');use method without to remove parameters.
$array = $array
->without('a');use method withOptionalMinimum to define a minimum number of optional parameters. Useful if all parameters are optional but 1.
$array = $array
->withOptionalMinimum(1);The following parameters are based on Array.
Use function arrayString to create an ArrayStringparameterInterface for string values. It only supports string parameters.
use function ChevereparameterarrayString;
use function Chevereparameterstring;
$array = arrayString(
test: string(),
);
$array(['test' => 'foo']);Use function file to create an Arrayparameter for file uploads.
use function Chevereparameterfile;
$array = file();
$file = [
'name' => 'foo.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpYzdqkD',
'error' => 0,
'size' => 123,
];
$array($file);By default it provides validation for $_FILES shape, but you can define your own validation rules. For example, to validate name and contents:
use function Chevereparameterfile;
$array = file(
name: string('/^.txt$/'),
contents: string('/wage-/'),
);
$array(
'name' => 'wage-2024.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpYzdqkD',
'error' => 0,
'size' => 27,
'contents' => 'yada yada wage-2024 bla bla',
);Iterable type Traversable|array is considered as a composite parameter holding a generic definition for key and value. parameter enables to describe this collection of items sharing the same shape.
Use function iterable to create an Iterableparameter. Pass a V and K parameters for generic key and value.
use function Chevereparameterint;
use function Chevereparameteriterable;
$iterable = iterable(int(min: 0));
$iterable([0, 1, 2, 3]);It also works with named keys:
use function Chevereparameterint;
use function Chevereparameteriterable;
use function Chevereparameterstring;
$iterable = iterable(
V: arrayp(
id: int(min: 0),
name: string('^[w]{1,255}'),
)
K: string(),
);
$iterable([
'based' => [
'id' => 1,
'name' => 'OscarGangas'
],
'fome' => [
'id' => 2,
'name' => 'BomboFica'
],
]);Use function parameters to create a parameters instance.
use function Chevereparametersparameters;
use function Chevereparametersstring;
$parameters = parameters(foo: string());Use function arguments to create a Arguments instance.
use function Chevereparametersarguments;
use function Chevereparametersstring;
$arguments = arguments($parameters, ['foo' => 'bar']);Use function assertNamedArgument to assert a named argument.
use function ChevereparametersassertNamedArgument;
use function Chevereparametersint;
use function Chevereparametersparameters;
$parameter = int(min: 10);
assertNamedArgument(
name: 'foo',
parameter: $parameter,
argument: 20
);Use function toparameter to create a parameterInterface instance from a type string. In the example below the resulting $parameter will be an Intparameter.
use function Chevereparameterstoparameter;
$parameter = toparameter('int');Use function arrayFrom to create an Array parameter from another array parameter. In the example below the resulting $array will contain only name and id keys as defined in $source.
use function ChevereparametersarrayFrom;
use function Chevereparametersarrayp;
use function Chevereparametersint;
use function Chevereparametersstring;
$source = arrayp(
id: int(),
name: string(),
email: string(),
age: int(),
);
$array = arrayFrom($source, 'name', 'id');Use function takeKeys to retrieve an array with the keys from a parameter. In the example below $keys will contain id and size.
use function Chevereparametersarrayp;
use function Chevereparametersint;
use function ChevereparameterstakeKeys;
$array = arrayp(
id: int(),
size: int(),
);
$keys = takeKeys($array);Use function takeFrom to retrieve an iterator with the desired keys from a parameter. In the example below $iterator will yield size and name keys.
use function Chevereparametersarrayp;
use function Chevereparametersint;
use function Chevereparametersstring;
use function ChevereparameterstakeFrom;
$array = arrayp(
id: int(min: 0),
size: int(min: 100),
name: string(),
);
$iterator = takeFrom($array, 'size', 'name');Use function parametersFrom to create a parameters with desired keys from a parameter. In the example below $parameters will contain size and name keys.
use function Chevereparametersarrayp;
use function Chevereparametersint;
use function Chevereparametersstring;
use function ChevereparametersparametersFrom;
$array = arrayp(
id: int(min: 0),
size: int(min: 100),
name: string(),
);
$parameters = parametersFrom($array, 'size', 'name');Use function getparameters to retrieve a parameters instance from an object implementing either parameterAccessInterface or parametersInterface.
use function Chevereparametersgetparameters;
$parameters = getparameters($object);Use function getType to retrieve the type as is known by this library.
use function ChevereparametersgetType;
$type = getType(1); // intUse function parameterAttr to retrieve an object implementing parameterAttributeInterface from a function or class method parameter.
use function ChevereparametersparameterAttr;
use ChevereparameterAttributesStringAttr;
function myFunction(
#[StringAttr('/^bin-[d]+$/')]
string $foo
): void {
// ...
}
$stringAttr = parameterAttr('foo', 'myFunction');
$stringAttr('bin-123');Use function reflectionToparameters to retrieve a parameters instance from a ReflectionFunction or ReflectionMethod instance.
use function ChevereparameterreflectionToparameters;
$parameters = reflectionToparameters($reflection);Use function reflectionToReturn to retrieve a parameterInterface instance from a ReflectionFunction or ReflectionMethod instance.
use function ChevereparameterreflectionToReturn;
$parameter = reflectionToReturn($reflection);Use function reflectedparameterAttribute to retrieve an object implementing parameterAttributeInterface from a Reflectionparameter instance.
use function ChevereparameterreflectedparameterAttribute;
$parameterAttribute = reflectedparameterAttribute($reflectionparameter);Use function validated to validate a function or method arguments.
use function Chevereparametervalidated;
$result = validated('myFunction', $arg1, $arg2,);use function Chevereparameterstring;
$value = 'ahhh';
string('/^a.+/')($value);100:use function Chevereparameterint;
$value = 100;
int(min: 100)($value);use function Chevereparameterint;
$value = 1;
int(accept: [1, 2, 3])($value);use function Chevereparameterfloat;
$value = 3.1;
float(reject: [1.1, 2.1])($value);use function Chevereparameterarrayp;
use function Chevereparameterint;
use function Chevereparameterstring;
$value = [
'id' => 1,
'name' => 'Pepe'
];
arrayp(
id: int(min: 1),
name: string('/^[A-Z]{1}w+$/')
)($value);int list:use function Chevereparameterint;
use function Chevereparameteriterable;
$value = [1, 2, 3];
iterable(int())($value);use function Chevereparameterint;
use function Chevereparameteriterable;
$value = [
'unila' => 1,
'dorila' => 2,
'tirifila' => 3,
];
iterable(
K: string('/ila$/'),
V: int(min: 1)
)($value);use function Chevereparameterint;
use function Chevereparameternull;
$value = 1;
union(int(), null())($value);validated() to get a return validated against all rules.use function Chevereparametervalidated;
$result = validated('myFunction', $var);reflectionToparameters() to get rules for validating arguments.use ReflectionMethod;
use ChevereparameterAttributesIntAttr;
use function Chevereparameterarguments;
use function ChevereparameterreflectionToparameters;
$class = new class() {
public function wea(
#[IntAttr(accept: [1, 10, 100])]
int $base
): void {
}
};
$object = new $class();
$reflection = new ReflectionMethod($object, 'wea');
$parameters = reflectionToparameters($reflection);
$args = ['base' => 10];
$parameters(...$args); // valid $args
$result = $object->wea(...$args);reflectionToReturn() to get rules for validating function/method return value:use ReflectionFunction;
use ChevereparameterAttributesIntAttr;
use ChevereparameterAttributesReturnAttr;
use function ChevereparameterreflectionToReturn;
$function =
#[ReturnAttr(
new IntAttr(min: 1000)
)]
function (int $base): int {
return 10 * $base;
};
$reflection = new ReflectionFunction($function);
$return = reflectionToReturn($reflection);
$base = 10;
$result = $function($base);
$result = $return($result); // Validates resultUse valid() on the function/method body to trigger validation for arguments.
Hugo, Paco, Luis:1000:use ChevereparameterAttributesEnumAttr;
use function Chevereparametervalidate;
function myEnum(
#[EnumAttr('Hugo', 'Paco', 'Luis')]
string $name,
#[FloatAttr(min: 1000)]
float $money
): void
{
valid();
// Or single...
valid('name');
valid('money');
}
$arg1 = 'Paco';
$arg2 = 1000.50;
myEnum($arg1, $arg2);0 and 100:use ChevereparameterAttributesIntAttr;
use function Chevereparametervalidate;
function myInt(
#[IntAttr(reject: [0, 100])]
int $id
): void
{
valid();
}
$value = 50;
myInt($value);use ChevereparameterAttributesArrayAttr;
use ChevereparameterAttributesIntAttr;
use ChevereparameterAttributesStringAttr;
use ChevereparameterAttributesIterableAttr;
use function Chevereparametervalidate;
function myArray(
#[ArrayAttr(
id: new IntAttr(min: 1),
role: new ArrayAttr(
mask: new IntAttr(accept: [64, 128, 256]),
name: new StringAttr('/[a-z]+/'),
tenants: new IterableAttr(
new IntAttr(min: 1)
)
),
)]
array $spooky
): void
{
valid();
}
$value = [
'id' => 10,
'role' => [
'mask' => 128,
'name' => 'admin',
'tenants' => [1, 2, 3, 4, 5]
],
];
myArray($value);use ChevereparameterAttributesIntAttr;
use ChevereparameterAttributesIterableAttr;
use function Chevereparametervalidate;
function myIterable(
#[IterableAttr(
new IntAttr(),
)]
array $list = [0,1,2]
): void
{
valid();
}Use function returnAttr() on the function/method body.
min: 0, max: 5 return:use ChevereparameterAttributesIntAttr;
use ChevereparameterAttributesReturnAttr;
use function ChevereparameterreturnAttr;
#[ReturnAttr(
new IntAttr(min: 0, max: 5)
)]
public function myReturnInt(): int
{
$result = 1;
return returnAttr()($result);
}use ChevereparameterAttributesArrayAttr;
use ChevereparameterAttributesIntAttr;
use ChevereparameterAttributesStringAttr;
use ChevereparameterAttributesReturnAttr;
use function ChevereparameterreturnAttr;
#[ReturnAttr(
new ArrayAttr(
id: new IntAttr(min: 0),
name: new StringAttr()
)
)]
public function myReturnArray(): array
{
$result = [
'id' => 1,
'name' => 'Peoples Hernandez'
];
return returnAttr()($result);
} By convention when omitting ReturnAttr the method public static function return(): parameterInterface (if any) will be used to determine return validation rules.
Documentation is available at chevere.org.
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.