GeneralFunctions\compose()

higher-order composer variadic returns Closure pure
...(T → T) → (T → T)
At a glance — The canonical function composer. Left-to-right by default. Use composeR for right-to-left, composeSafe to halt on null, composeTypeSafe to halt on a custom type check.

Creates a Closure that threads a value through a sequence of callables left-to-right — the output of each becomes the input of the next.

/**
  * @param callable(mixed):mixed ...$callables
  * @return Closure(mixed):mixed
  */
GeneralFunctions\compose(callable ...$callables): Closure

Returned Closure

When GeneralFunctions\compose() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param mixed $value
  * @return mixed
  */
$function ($value)

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

$slugify = GeneralFunctions\compose(
  'trim',
  'strtolower',
  Strings\replaceWith(' ', '-')
);

echo $slugify('  Hello World  '); // 'hello-world'

Curried

This can be called inline using currying.

echo GeneralFunctions\compose('trim', 'strtoupper')('  foo  '); // 'FOO'

Inlined with Higher Order Function

If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.

$cleaned = array_map(
  GeneralFunctions\compose('trim', 'strtolower'),
  ['  Foo  ', '  BAR  ']
);
print_r($cleaned); // ['foo', 'bar']

Details

General Functions

Releated Composition Functions