| 1 |
<?php |
| 2 |
/** |
| 3 |
* ZPL output adapter. |
| 4 |
* |
| 5 |
* @package WCPOS\WooCommercePOS\Templates\Adapters |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WCPOS\WooCommercePOS\Templates\Adapters; |
| 9 |
|
| 10 |
use WCPOS\WooCommercePOS\Interfaces\Receipt_Output_Adapter_Interface; |
| 11 |
|
| 12 |
/** |
| 13 |
* Zpl_Output_Adapter class. |
| 14 |
*/ |
| 15 |
class Zpl_Output_Adapter implements Receipt_Output_Adapter_Interface { |
| 16 |
/** |
| 17 |
* Transform receipt payload to a ZPL label payload. |
| 18 |
* |
| 19 |
* @param array $receipt_data Canonical payload. |
| 20 |
* @param array $context Optional context. |
| 21 |
* |
| 22 |
* @return string |
| 23 |
*/ |
| 24 |
public function transform( array $receipt_data, array $context = array() ): string { |
| 25 |
$width = isset( $context['label_width'] ) ? (int) $context['label_width'] : 812; |
| 26 |
$length = isset( $context['label_length'] ) ? (int) $context['label_length'] : 1218; |
| 27 |
$print_qr = isset( $context['print_qr'] ) ? (bool) $context['print_qr'] : false; |
| 28 |
$print_barcode = isset( $context['print_barcode'] ) ? (bool) $context['print_barcode'] : true; |
| 29 |
|
| 30 |
$order_number = isset( $receipt_data['order']['number'] ) ? (string) $receipt_data['order']['number'] : ''; |
| 31 |
$total = isset( $receipt_data['totals']['total_incl'] ) ? (float) $receipt_data['totals']['total_incl'] : 0; |
| 32 |
$store_name = isset( $receipt_data['store']['name'] ) ? (string) $receipt_data['store']['name'] : get_bloginfo( 'name' ); |
| 33 |
$qr_payload = isset( $receipt_data['fiscal']['qr_payload'] ) ? (string) $receipt_data['fiscal']['qr_payload'] : ''; |
| 34 |
|
| 35 |
$zpl = array( |
| 36 |
'^XA', |
| 37 |
'^PW' . max( 200, $width ), |
| 38 |
'^LL' . max( 300, $length ), |
| 39 |
'^CF0,28', |
| 40 |
'^FO30,30^FD' . $this->sanitize_zpl_text( $store_name ) . '^FS', |
| 41 |
'^FO30,65^FDWCPOS RECEIPT^FS', |
| 42 |
'^FO30,75^FDOrder #' . $order_number . '^FS', |
| 43 |
'^FO30,120^FDTotal ' . wc_format_decimal( $total, wc_get_price_decimals() ) . '^FS', |
| 44 |
); |
| 45 |
|
| 46 |
if ( $print_barcode ) { |
| 47 |
$zpl[] = '^BY2,2,60'; |
| 48 |
$zpl[] = '^FO30,170^BCN,60,Y,N,N'; |
| 49 |
$zpl[] = '^FD' . $this->sanitize_zpl_text( $order_number ) . '^FS'; |
| 50 |
} |
| 51 |
if ( $print_qr && '' !== $qr_payload ) { |
| 52 |
$zpl[] = '^FO30,260^BQN,2,6'; |
| 53 |
$zpl[] = '^FDLA,' . $this->sanitize_zpl_text( $qr_payload ) . '^FS'; |
| 54 |
} |
| 55 |
|
| 56 |
$zpl[] = '^XZ'; |
| 57 |
|
| 58 |
return implode( "\n", $zpl ); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Sanitize text for ZPL fields. |
| 63 |
* |
| 64 |
* @param string $value Text value. |
| 65 |
* |
| 66 |
* @return string |
| 67 |
*/ |
| 68 |
private function sanitize_zpl_text( string $value ): string { |
| 69 |
$value = preg_replace( '/[\^~]/', '-', $value ); |
| 70 |
|
| 71 |
return trim( $value ); |
| 72 |
} |
| 73 |
} |
| 74 |
|