Skip to content

Instantly share code, notes, and snippets.

@ablunier
Last active April 17, 2024 23:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ablunier/f91e2d2adb8db4c560a9d63f82cb3bb7 to your computer and use it in GitHub Desktop.
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
<?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