79 lines
1.9 KiB
PHP
79 lines
1.9 KiB
PHP
<?php
|
|
|
|
if ( ! defined( 'ABSPATH' ) ) {
|
|
exit;
|
|
} // Exit if accessed directly
|
|
|
|
require_once 'class-api-shipx.php';
|
|
|
|
if ( ! class_exists( 'WPDesk_Paczkomaty_ShipX_Status_Translation' ) ) {
|
|
|
|
/**
|
|
* Can translate inpost status to a given locale
|
|
*/
|
|
class WPDesk_Paczkomaty_ShipX_Status_Translation {
|
|
/** @var WPDesk_Paczkomaty_ShipX */
|
|
private $api;
|
|
|
|
/** @var string */
|
|
private $default_locale;
|
|
|
|
/**
|
|
* WPDesk_Paczkomaty_ShipX_Status_Translation constructor.
|
|
*
|
|
* @param WPDesk_Paczkomaty_ShipX $api
|
|
* @param string $default_locale Used when no or invalid locale given later
|
|
*/
|
|
public function __construct( WPDesk_Paczkomaty_ShipX $api, $default_locale = 'pl_PL' ) {
|
|
$this->api = $api;
|
|
$this->default_locale = $default_locale;
|
|
}
|
|
|
|
/**
|
|
* Fallbacks given locale to default if cant be translated
|
|
*
|
|
* @param string|null $target_locale
|
|
*
|
|
* @return string
|
|
*/
|
|
private function fallback_target_locale( $target_locale ) {
|
|
$possible_locales = array( 'en_GB', 'pl_PL' );
|
|
|
|
if ( ! $target_locale || ! in_array( $target_locale, $possible_locales, true ) ) {
|
|
return $this->default_locale;
|
|
}
|
|
|
|
return $target_locale;
|
|
}
|
|
|
|
/**
|
|
* Translates status to given locale
|
|
*
|
|
* @param string $status
|
|
* @param string|null $target_locale
|
|
*
|
|
* @return string
|
|
*/
|
|
public function translate_status( $status, $target_locale = null ) {
|
|
try {
|
|
$translated_statuses = $this->api->get_statuses( $this->fallback_target_locale( $target_locale ) );
|
|
|
|
$translated = current( array_filter( $translated_statuses->items, function ( $item ) use ( $status ) {
|
|
return $item->name === $status;
|
|
} ) );
|
|
|
|
if ( $translated ) {
|
|
return $translated->title;
|
|
}
|
|
|
|
return $status;
|
|
|
|
} catch ( \Exception $e ) {
|
|
error_log( "Can't translate status: {$status}. Error: {$e->getMessage()}. Code: {$e->getCode()}" );
|
|
|
|
return $status;
|
|
}
|
|
}
|
|
}
|
|
}
|