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: 
<?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;

/**
 * One item response
 */
class ItemResponse extends Response
{
    /**
     * Item
     * @var object
     */
    protected $item = null;

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

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

    /**
     * Get item
     *
     * @return object Item
     */
    public function getItem()
    {
        return $this->item;
    }

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

    /**
     * JsonSerializable
     *
     * @return object Item
     */
    public function jsonSerialize()
    {
        return $this->getItem();
    }

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

    /**
     * Property overloading
     * This way we can get item data directly from response
     *
     * @param string $name Property name
     *
     * @return mixed Property value or false if dosen't exist
     */
    public function __get($name)
    {
        if (isset($this->item->{$name})) {
            return $this->item->{$name};
        }

        return false;
    }

    /**
     * Detect if item has specified property
     *
     * @param string $name Property name
     *
     * @return boolean True if property exists, false otherwise
     */
    public function __isset($name)
    {
        return isset($this->item->{$name});
    }
}