jasny/iterator-stream

This package is abandoned and no longer maintained. No replacement package was suggested.

Output streams for iterators, formatting and writing one element at a time

dev-master 2020-10-08 14:15 UTC

This package is auto-updated.

Last update: 2024-08-29 21:06:08 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Packagist Stable Version Packagist License

Output streams for iterators, formatting and writing one element at a time.

If you're looking for a traversable input stream, take a look at SplFileObject.

Installation

composer require jasny/iterator-stream

Usage

$handler = fopen('path/to/some/file.txt');
$stream = new LineOutputStream($handler);

$iterable = ['hello, 'sweet', 'world'];

$stream->write($iterator);

The write() takes an array or Traversable object (not just Iterators).

All iterator stream objects take a stream resource or URI (string) as first parameter of the constructor.

new LineOutputStream('php://output');
new CsvOutputStream('file://path/to/some/file.csv');

If an URI is passed, the iterator stream will open it using fopen. Using a scheme is required, also for regular files.

To use it with PSR-7 streams, you need to detach the underlying resource and pass it to constructor.

$handler = $psr7stream->detach();
$stream = new LineOutputStream($handler);

Prototype pattern

Iterator output streams support the prototype design pattern. They may be created detached of a stream resource. The withStream creates a clone of the output stream with the given resource attached.

$prototype = new JsonOutputStream();

$stream = $prototype->withStream($resource);
$stream->write($iterable);

Prototyping makes the library easier to use with dependency inversion in SOLID applictions.

Output streams

Line

Write to a stream line by line.

LineOutputStream(resource|string $stream, string $endLine = "\n")

CSV

Write to a stream as CSV. See fputcsv().

CsvOutputStream(
    resource|string $stream,
    string $delimiter = ',',
    string $enclosure = '"',
    string $escapeChar = '\\'
)

The write() method optionally takes headers as a seconds argument. These are written as first line.

$output = new CsvOutputStream($stream);
$output->write($data, ['name', 'age', 'email']);

Each element of the iterable MUST be an array with a fixed number of values. Keys are ignored, if the elements are associative arrays or objects, use iterable_project from jasny\iterable-functions.

JSON

Write to a stream as JSON array. See json_encode.

JsonOutputStream(resource|string $stream, int $options = 0)

Options may be provided as binary set using the JSON_* constants.

You can add JsonOutputStream::OUTPUT_LINES as option, in which case each element is outputed as line, without turning the complete output into a JSON array.

$output = new JsonOutputStream($stream, \JSON_PRETTY_PRINT | JsonOutputStream::OUTPUT_LINES);