ifEmpty()

IfEmpty operator tracks the number of yielded items. If the stream is empty, it will invoke the provided callable and yield from it as an alternative source of data.

If exception is provided instead of alternative source of data, that exception will be thrown.

class RunOpenCode\Component\Dataset\Operator\IfEmpty
__construct(iterable<TKey, TValue> $source, \Throwable|callable()|null: iterable<TKey, TValue> $fallback = null)
Parameters:
  • $sourceiterable<TKey, TValue> Stream source to iterate over.

  • $fallback\Throwable|callable()|null: iterable<TKey, TValue> Fallback stream source, or exception to throw, or null to use the default empty-stream exception.

getIterator()
Returns:

\Traversable<TKey, TValue> Provided stream source or fallback stream source.

Use cases

  • Provide an alternative source of data if the original is empty.

  • Assert that the stream is not empty and throw an exception if it is.

Example

Try with dataset stored in cache first. If cache is empty, load data from database.

1<?php
2
3new Stream($dataset)
4    ->ifEmpty(function() use ($database): iterable {
5        return $database->fetch();
6    });

Expect that the query will return at least one result; otherwise, throw an exception.

1<?php
2
3new Stream($dataset)
4    ->ifEmpty(new \RuntimeException('At least one record is expected.'));