Strings\composeSafeStringFunc()

higher-order composer variadic returns Closure pure
...(mixed → string) → (mixed → string | null)
At a glance — Compose several string-returning callables into one pipeline; an 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): Closure

Returned Closure

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

/**
  * @param mixed $source
  * @return string
  */
$function ($source): string

Examples

Partial Application

This 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']

Curried

This can be called inline using currying.

// Compose and invoke inline.
echo Strings\composeSafeStringFunc('trim', 'strtoupper')('  hello  '); // HELLO

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.

// 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!']

Details

Strings Functions

Releated String manipulation Functions