For better readability, we may wish to convert our data streams into strings. To ensure the conversion works consistently, we will create a custom string representation for our data elements. Have a look at the toString() method in action:
<?php
class DataStream {
private $data;
public function __construct(array $data) {
$this->data = $data;
}
public function get(int $i): array {
if ($i < 0) {
$i += count($this->data);
}
if ($i >= 0 && $i < count($this->data)) {
return $this->data[$i];
} else {
throw new OutOfRangeException("Index out of range");
}
}
public function slice(int $i, int $j): array {
if ($i < 0) {
$i += count($this->data);
}
if ($j < 0) {
$j += count($this->data);
}
if ($i >= 0 && $j <= count($this->data) && $i < $j) {
return array_slice($this->data, $i, $j - $i);
} else {
throw new OutOfRangeException("Slice indices out of range");
}
}
public function toString(): string {
$elements = array_map(function($item) {
return json_encode($item);
}, $this->data);
return '[' . implode(', ', $elements) . ']';
}
}
To see it in action:
<?php
$data = [
["id" => 1, "value" => 100],
["id" => 2, "value" => 200],
["id" => 3, "value" => 300],
["id" => 4, "value" => 400],
];
$stream = new DataStream($data);
echo $stream->toString();
It prints: [{"id":1,"value":100}, {"id":2,"value":200}, {"id":3,"value":300}, {"id":4,"value":400}].