1<?php
2
3namespace Mike42\Escpos\PrintConnectors;
4
5use Guzzle\Http\Client;
6use Guzzle\Http\Message\Request;
7use Guzzle\Http\Message\Response;
8use Exception;
9
10class ApiPrintConnector implements PrintConnector
11{
12    /**
13     * @var string
14     */
15    protected $stream;
16    /**
17     * @var Client
18     */
19    protected $httpClient;
20
21    /**
22     * @var string
23     */
24    protected $printerId;
25    /**
26     * @var string
27     */
28    protected $apiToken;
29
30    /**
31    * Construct new connector
32    *
33    * @param string $host
34    * @param string $printerId
35    * @param string $apiToken
36    */
37    public function __construct($host, $printerId, $apiToken)
38    {
39        $this->httpClient = new Client(['base_uri' => $host]);
40        $this->printerId = $printerId;
41        $this->apiToken = $apiToken;
42
43        $this->stream = '';
44    }
45
46    /**
47     * Print connectors should cause a NOTICE if they are deconstructed
48     * when they have not been finalized.
49     */
50    public function __destruct()
51    {
52        if (! empty($this->stream)) {
53            trigger_error("Print connector was not finalized. Did you forget to close the printer?", E_USER_NOTICE);
54        }
55    }
56
57    /**
58     * Finish using this print connector (close file, socket, send
59     * accumulated output, etc).
60     */
61    public function finalize()
62    {
63        /** @var Request $request */
64        $request = $this->httpClient->post(
65            'printers/'.$this->printerId.'/print?api_token='.$this->apiToken,
66            null,
67            $this->stream
68        );
69
70        /** @var Response $response */
71        $response = $request->send();
72
73        if (! $response->isSuccessful()) {
74            throw new Exception(
75                sprintf('Failed to print. API returned "%s: %s"', $response->getStatusCode(), $response->getReasonPhrase())
76            );
77        }
78
79        $this->stream = '';
80    }
81
82    /**
83     * Read data from the printer.
84     *
85     * @param string $len Length of data to read.
86     * @return string Data read from the printer.
87     */
88    public function read($len)
89    {
90        return $this->stream;
91    }
92
93    /**
94     * Write data to the print connector.
95     *
96     * @param string $data The data to write
97     */
98    public function write($data)
99    {
100        $this->stream .= $data;
101    }
102}
103