Skip to content

Instantly share code, notes, and snippets.

@tsukasa-mixer
Created August 6, 2018 13:40
Show Gist options
  • Save tsukasa-mixer/7952bd87b7e5c6c66a6ce106398ede19 to your computer and use it in GitHub Desktop.
Save tsukasa-mixer/7952bd87b7e5c6c66a6ce106398ede19 to your computer and use it in GitHub Desktop.
<?php
class SimpleEncoder implements \Iterator
{
/**
* @var \Iterator
*/
private $iterator;
private $head;
private $i = 0;
public function __construct(\Iterator $iterator)
{
$this->head = $this->getHeader($iterator->current());
$this->iterator = $iterator;
}
/**
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
* @since 5.0.0
*/
public function current()
{
if ($this->i == 0) {
return json_encode($this->head) . "\r\n";
}
$item = $this->iterator->current();
return $this->encode($item);
}
/**
* Move forward to next element
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function next()
{
if ($this->i > 0) {
$this->iterator->next();
}
$this->i++;
}
/**
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
* @since 5.0.0
*/
public function key()
{
return $this->i;
}
/**
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
* @since 5.0.0
*/
public function valid()
{
if ($this->i == 0) {
return true;
}
return $this->iterator->valid();
}
/**
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function rewind()
{
$this->i = 0;
$this->iterator->rewind();
}
private function getHeader($item)
{
if (is_array($item)) {
ksort($item);
return array_keys($item);
}
return [];
}
private function encode($item)
{
$line = [];
foreach ($this->head as $name) {
if (isset($item[$name])) {
$line[] = $item[$name];
}
}
return json_encode($line) . "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment