| 1 |
<?php |
| 2 |
/** |
| 3 |
* Class Helper |
| 4 |
* |
| 5 |
* @package Packetery |
| 6 |
*/ |
| 7 |
|
| 8 |
declare( strict_types=1 ); |
| 9 |
|
| 10 |
|
| 11 |
namespace Packetery\Core; |
| 12 |
|
| 13 |
use DateTimeImmutable; |
| 14 |
|
| 15 |
/** |
| 16 |
* Class Helper |
| 17 |
* |
| 18 |
* @package Packetery |
| 19 |
*/ |
| 20 |
class Helper { |
| 21 |
public const TRACKING_URL = 'https://tracking.packeta.com/?id=%s'; |
| 22 |
public const MYSQL_DATETIME_FORMAT = 'Y-m-d H:i:s'; |
| 23 |
public const MYSQL_DATE_FORMAT = 'Y-m-d'; |
| 24 |
public const DATEPICKER_FORMAT = 'Y-m-d'; |
| 25 |
public const DATEPICKER_FORMAT_JS = 'yy-mm-dd'; |
| 26 |
|
| 27 |
/** |
| 28 |
* Simplifies weight. |
| 29 |
* |
| 30 |
* @param float|null $weight Weight. |
| 31 |
* |
| 32 |
* @return float|null |
| 33 |
*/ |
| 34 |
public static function simplifyWeight( ?float $weight ): ?float { |
| 35 |
return self::simplifyFloat( $weight, 3 ); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Simplifies float value to have max decimal places. |
| 40 |
* |
| 41 |
* @param float|null $value Value. |
| 42 |
* @param int $maxDecimalPlaces Max decimal places. |
| 43 |
* |
| 44 |
* @return float|null |
| 45 |
*/ |
| 46 |
public static function simplifyFloat( ?float $value, int $maxDecimalPlaces ): ?float { |
| 47 |
if ( null === $value ) { |
| 48 |
return null; |
| 49 |
} |
| 50 |
|
| 51 |
return (float) number_format( $value, $maxDecimalPlaces, '.', '' ); |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Returns tracking URL. |
| 56 |
* |
| 57 |
* @param string $packet_id Packet ID. |
| 58 |
* |
| 59 |
* @return string |
| 60 |
*/ |
| 61 |
public function get_tracking_url( string $packet_id ): string { |
| 62 |
return sprintf( self::TRACKING_URL, rawurlencode( $packet_id ) ); |
| 63 |
} |
| 64 |
|
| 65 |
/** |
| 66 |
* Creates UTC DateTime. |
| 67 |
* |
| 68 |
* @return DateTimeImmutable |
| 69 |
* @throws \Exception From DateTimeImmutable. |
| 70 |
*/ |
| 71 |
public static function now(): DateTimeImmutable { |
| 72 |
return new DateTimeImmutable( 'now', new \DateTimeZone( 'UTC' ) ); |
| 73 |
} |
| 74 |
|
| 75 |
/** |
| 76 |
* Creates string in given format from DateTimeImmutable object |
| 77 |
* |
| 78 |
* @param DateTimeImmutable|null $date Datetime. |
| 79 |
* @param string $format Datetime format. |
| 80 |
* |
| 81 |
* @return string|null |
| 82 |
*/ |
| 83 |
public function getStringFromDateTime( ?DateTimeImmutable $date, string $format ): ?string { |
| 84 |
return $date ? $date->format( $format ) : null; |
| 85 |
} |
| 86 |
|
| 87 |
/** |
| 88 |
* Creates DateTimeImmutable object from string |
| 89 |
* |
| 90 |
* @param string $date Date. |
| 91 |
* |
| 92 |
* @return \DateTimeImmutable |
| 93 |
* @throws \Exception From DateTimeImmutable. |
| 94 |
*/ |
| 95 |
public function getDateTimeFromString( ?string $date ): ?DateTimeImmutable { |
| 96 |
return $date ? new DateTimeImmutable( $date ) : null; |
| 97 |
} |
| 98 |
} |
| 99 |
|