| 1 |
<?php |
| 2 |
/** |
| 3 |
* Legacy PHP receipt renderer. |
| 4 |
* |
| 5 |
* @package WCPOS\WooCommercePOS\Templates\Renderers |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WCPOS\WooCommercePOS\Templates\Renderers; |
| 9 |
|
| 10 |
use WCPOS\WooCommercePOS\Interfaces\Receipt_Renderer_Interface; |
| 11 |
use WC_Abstract_Order; |
| 12 |
|
| 13 |
/** |
| 14 |
* Legacy_Php_Renderer class. |
| 15 |
*/ |
| 16 |
class Legacy_Php_Renderer implements Receipt_Renderer_Interface { |
| 17 |
/** |
| 18 |
* Render legacy PHP template. |
| 19 |
* |
| 20 |
* @param array $template Template metadata/content. |
| 21 |
* @param WC_Abstract_Order|null $order Order object, or null for sample-data preview. |
| 22 |
* @param array $receipt_data Canonical receipt payload. |
| 23 |
* |
| 24 |
* @throws \RuntimeException When the temporary template file cannot be created. |
| 25 |
*/ |
| 26 |
public function render( array $template, ?WC_Abstract_Order $order, array $receipt_data ): void { |
| 27 |
if ( ! empty( $template['file_path'] ) && file_exists( $template['file_path'] ) && is_readable( $template['file_path'] ) ) { |
| 28 |
include $template['file_path']; |
| 29 |
return; |
| 30 |
} |
| 31 |
|
| 32 |
if ( empty( $template['content'] ) || ! \is_string( $template['content'] ) ) { |
| 33 |
echo '<!-- Empty legacy receipt template -->'; |
| 34 |
return; |
| 35 |
} |
| 36 |
|
| 37 |
$temp_file = $this->create_temp_template_file( $template['content'] ); |
| 38 |
if ( ! $temp_file ) { |
| 39 |
throw new \RuntimeException( esc_html__( 'Failed to create temporary template file.', 'woocommerce-pos' ) ); |
| 40 |
} |
| 41 |
|
| 42 |
include $temp_file; |
| 43 |
@unlink( $temp_file ); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Create a temporary template file. |
| 48 |
* |
| 49 |
* @param string $content Template content. |
| 50 |
* |
| 51 |
* @return false|string |
| 52 |
*/ |
| 53 |
private function create_temp_template_file( string $content ) { |
| 54 |
$upload_dir = wp_upload_dir(); |
| 55 |
$temp_dir = trailingslashit( $upload_dir['basedir'] ) . 'wcpos-templates'; |
| 56 |
|
| 57 |
if ( ! file_exists( $temp_dir ) ) { |
| 58 |
wp_mkdir_p( $temp_dir ); |
| 59 |
} |
| 60 |
|
| 61 |
$temp_file = tempnam( $temp_dir, 'receipt_' ); |
| 62 |
if ( ! $temp_file ) { |
| 63 |
return false; |
| 64 |
} |
| 65 |
|
| 66 |
$written = file_put_contents( $temp_file, $content ); |
| 67 |
if ( false === $written ) { |
| 68 |
@unlink( $temp_file ); |
| 69 |
return false; |
| 70 |
} |
| 71 |
|
| 72 |
return $temp_file; |
| 73 |
} |
| 74 |
} |
| 75 |
|