Last active
April 17, 2024 23:11
-
-
Save ablunier/f91e2d2adb8db4c560a9d63f82cb3bb7 to your computer and use it in GitHub Desktop.
This a print connector implementation to communicate the mike42/escpos-php package with the ablunier/escpos-print-api API
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 | |
namespace Ablunier\Escpos\PrintConnectors\Connectors; | |
use Mike42\Escpos\PrintConnectors\PrintConnector; | |
use GuzzleHttp\Client; | |
/** | |
* Class PrintServerApi | |
*/ | |
class PrintServerApi implements PrintConnector | |
{ | |
/** | |
* @var string | |
*/ | |
protected $stream; | |
/** | |
* @var Client | |
*/ | |
protected $httpClient; | |
/** | |
* @var string | |
*/ | |
protected $printerId; | |
/** | |
* @var string | |
*/ | |
protected $apiToken; | |
/** | |
* Construct new connector, given a filename | |
* | |
* @param string $host | |
* @param string $printerId | |
* @param string $apiToken | |
*/ | |
public function __construct($host, $printerId, $apiToken) | |
{ | |
$this->httpClient = new Client(['base_uri' => $host]); | |
$this->printerId = $printerId; | |
$this->apiToken = $apiToken; | |
$this->stream = ''; | |
} | |
/** | |
* Print connectors should cause a NOTICE if they are deconstructed | |
* when they have not been finalized. | |
*/ | |
public function __destruct() | |
{ | |
if (! empty($this->stream)) { | |
trigger_error("Print connector was not finalized. Did you forget to close the printer?", E_USER_NOTICE); | |
} | |
} | |
/** | |
* Finish using this print connector (close file, socket, send | |
* accumulated output, etc). | |
*/ | |
public function finalize() | |
{ | |
$response = $this->httpClient->request('POST', 'printers/'.$this->printerId.'/print', [ | |
'query' => ['api_token' => $this->apiToken], | |
'body' => $this->stream | |
]); | |
$this->stream = ''; | |
} | |
/** | |
* Read data from the printer. | |
* | |
* @param string $len Length of data to read. | |
* @return string Data read from the printer, or false where reading is not possible. | |
*/ | |
public function read($len) | |
{ | |
return $this->stream; | |
} | |
/** | |
* Write data to the print connector. | |
* | |
* @param string $data The data to write | |
*/ | |
public function write($data) | |
{ | |
$this->stream .= $data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment