Files
2026-04-28 15:13:50 +02:00

125 lines
3.3 KiB
PHP

<?php
/**
* Shipment status refresher.
*
* @package PaczkomatyInpost
*/
use VendorInPost\Psr\Log\LoggerInterface;
use VendorInPost\WPDesk\PluginBuilder\Plugin\Hookable;
/**
* Can update shipment status.
*/
class WPDesk_Paczkomaty_Shipment_Status_Refresher {
/**
* @var int
*/
private $shipment_id;
/**
* @var string
*/
private $inpost_shipment_id;
/**
* @var int
*/
private $current_run_number;
/**
* @var WPDesk_Paczkomaty_Shipment_Status_Scheduler
*/
private $scheduler;
/**
* @var LoggerInterface
*/
private $logger;
/**
* WPDesk_Paczkomaty_Shipment_Status_Refresher constructor.
*
* @param int $shipment_id .
* @param string $inpost_shipment_id .
* @param int $current_run_number .
* @param WPDesk_Paczkomaty_Shipment_Status_Scheduler $scheduler .
* @param LoggerInterface $logger .
*/
public function __construct(
$shipment_id,
$inpost_shipment_id,
$current_run_number,
WPDesk_Paczkomaty_Shipment_Status_Scheduler $scheduler,
LoggerInterface $logger
) {
$this->shipment_id = $shipment_id;
$this->inpost_shipment_id = $inpost_shipment_id;
$this->current_run_number = $current_run_number;
$this->scheduler = $scheduler;
$this->logger = $logger;
}
/**
* Refresh status.
*/
public function refresh_status() {
$run = array( $this, 'do_refresh_status' );
if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
$run();
} else {
if ( did_action( 'wp_loaded' ) ) {
$run();
} else {
add_action( 'wp_loaded', $run );
}
}
}
/**
* @param Exception|Throwable $e .
* @param WPDesk_Flexible_Shipping_Shipment_Paczkomaty $shipment .
*/
private function catch_refresh_exception( $e, WPDesk_Flexible_Shipping_Shipment_Paczkomaty $shipment ) {
$this->logger->warning(
'Inpost status scheduler: status refresh exception.',
array(
'shipment_id' => $this->shipment_id,
'exception' => $e->getMessage(),
)
);
$this->scheduler->schedule_next_refresh( $shipment, $this->current_run_number );
}
/**
* Do refresh status.
*
* @internal
*/
public function do_refresh_status() {
$shipment_post = get_post( $this->shipment_id );
if ( $shipment_post ) {
/** @var WPDesk_Flexible_Shipping_Shipment_Paczkomaty $shipment */
$shipment = fs_get_shipment( $this->shipment_id );
if ( (string) $this->inpost_shipment_id === (string) $shipment->get_meta( WPDesk_Flexible_Shipping_Shipment_Paczkomaty::META_PACZKOMAT_SHIPMENT_ID ) ) {
try {
$shipment->api_refresh();
if ( $shipment::STATUS_FS_CREATED === $shipment->get_status() ) {
$this->scheduler->schedule_next_refresh( $shipment, $this->current_run_number );
}
} catch ( Exception $e ) {
$this->catch_refresh_exception( $e, $shipment );
} catch ( Throwable $t ) {
$this->catch_refresh_exception( $t, $shipment );
}
} else {
$this->logger->warning( 'Inpost status scheduler: shipment has other inpost ID.', array( 'shipment_id' => $this->shipment_id ) );
}
} else {
$this->logger->warning( 'Inpost status scheduler: shipment not found.', array( 'shipment_id' => $this->shipment_id ) );
}
}
}