1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 
<?php
/**
 * Erply Books API PHP client
 *
 * @author Rene Korss <rene@koren.ee>
 * @copyright Copyright (c) 2020 Rene Korss (https://koren.ee)
 * @license MIT
 */

namespace Koren\ErplyBooks\Response;

use GuzzleHttp\Psr7\Response as GuzzleResponse;

/**
 * Items response, iterable
 */
class ItemsResponse extends Response implements \Iterator
{
    /**
     * Items
     * @var array
     */
    protected $items = [];

    /**
     * Iterator position
     * @var int
     */
    private $position = 0;

    /**
     * constructor
     *
     * @param \GuzzleHttp\Psr7\Response $response Response object
     */
    public function __construct(GuzzleResponse $response)
    {
        parent::__construct($response);

        $this->position = 0;

        if ($response->getStatusCode() == 200) {
            if (isset($this->body->items) && is_array($this->body->items)) {
                $this->items = $this->body->items;
            }
        }
    }

    /**
     * Get items
     *
     * @return array Items
     */
    public function getItems() : array
    {
        return $this->items;
    }

    /**
     * Iterator
     *
     * @ignore
     */
    public function current()
    {
        return $this->items[$this->position];
    }

    /**
     * @ignore
     */
    public function key()
    {
        return $this->position;
    }

    /**
     * @ignore
     */
    public function next()
    {
        ++$this->position;
    }

    /**
     * @ignore
     */
    public function rewind()
    {
        $this->position = 0;
    }

    /**
     * @ignore
     */
    public function valid()
    {
        return isset($this->items[$this->position]);
    }

    /**
     * Countable
     *
     * @return int Count of items
     */
    public function count()
    {
        return count($this->items);
    }

    /**
     * JsonSerializable
     *
     * @return array Items
     */
    public function jsonSerialize()
    {
        return $this->getItems();
    }

    /**
     * Magic method so we can echo items
     */
    public function __toString()
    {
        return json_encode($this->items);
    }
}