Created
August 6, 2018 13:40
-
-
Save tsukasa-mixer/7952bd87b7e5c6c66a6ce106398ede19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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