Usephul

Functions

Table of Contents

Functions

fit()  : TResult)
Returns the result of the first callback with a parameter type that fits the type of the given value.

Functions

fit()

Returns the result of the first callback with a parameter type that fits the type of the given value.

fit(TSubject $subject[, callable(mixed $arg, mixed ...$args): TResult|null $callback = null ], callable(mixed $arg, mixed ...$args): TResult ...$callbacks) : TResult)

This function functions similar to a match or switch statement but uses type checks to gauge which expression to evaluate for subject.

use function empaphy\usephul\fit;

$result = fit(
    $example,
    fn(string $v): string      => "value '$v' is a string",
    fn(int|float $v)           => "value is an integer or float",
    fn(array $v, object $w)    => "value is an array or an object",
    fn(Foo&(Bar|(Baz&Qux)) $v) => "both `Foo` & `Bar` or `Baz` & `Qux`",
    fn(mixed $default)         => "value is of some other type",
);

If no callback parameters are provided, fit() will return an instance of the Gauge class:

$gauge = fit('foo');
$result = $gauge->as(
    fn(string $v): string => "value '$v' is a string",
);

Which allows for a more readable format:

$result = fit('foo')->as(
    fn(string $v): string => "value '$v' is a string",
);

fit() is optimized for performance and makes no recursive calls, or calls to any other helper functions; it's completely self-contained.

Parameters
$subject : TSubject

The value to gauge.

$callback : callable(mixed $arg, mixed ...$args): TResult|null = null

A callback function. The first callback argument with a parameter type that fits subject will be called and its result returned.

$callbacks : callable(mixed $arg, mixed ...$args): TResult

Additional callback functions. The first callback function with a parameter type that fits subject will be called and its result returned.

Return values
TResult) —

The result of the first of the callbacks that fits subject.

On this page

Search results