is_string guard between each step makes the chain abort with null rather than passing bad data onward.
Composes a pipeline of callables into a single function, guarding each intermediate value with an is_string check. The composed Closure passes its input through each callable in turn, so the output of one becomes the input of the next. If any step produces a non-string value, the composed function aborts and returns null rather than calling the next callable with bad data.
/**
* @param callable(mixed):string ...$callable
* @return Closure(mixed):string
*/
Strings\composeSafeStringFunc(callable ...$callable): ClosureWhen Strings\composeSafeStringFunc() is called, it returns the following Closure which can be used like a regular function.
/**
* @param mixed $source
* @return string
*/
$function ($source): stringThis can be used to create a simple closure which can be used as a regular function.
// Build a reusable normaliser from several string-returning callables.
$normalise = Strings\composeSafeStringFunc(
'trim',
'strtolower',
Strings\replaceWith(' ', '-')
);
// Called as a function.
echo $normalise(' Some Title '); // some-title
// Used in a higher order function.
$slugs = array_map($normalise, [' First Post ', 'SECOND post']);
print_r($slugs); // ['first-post', 'second-post']This can be called inline using currying.
// Compose and invoke inline.
echo Strings\composeSafeStringFunc('trim', 'strtoupper')(' hello '); // HELLOIf you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.
// Drop straight into array_map without naming the pipeline.
$shouts = array_map(
Strings\composeSafeStringFunc('trim', 'strtoupper', Strings\append('!')),
[' hi ', ' there ']
);
print_r($shouts); // ['HI!', 'THERE!']