| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Utilities; |
| 4 |
|
| 5 |
defined('ABSPATH') || exit; |
| 6 |
|
| 7 |
/** |
| 8 |
* A price adjustment value is one of: |
| 9 |
* - 'commission' : calculated from the Basalam category commission |
| 10 |
* - -100 to 100 : a percentage (negative means a price reduction; capped at 35% either way) |
| 11 |
* - outside that range : a fixed amount in Toman (negative means a reduction) |
| 12 |
*/ |
| 13 |
class PriceAdjustment |
| 14 |
{ |
| 15 |
public const COMMISSION = 'commission'; |
| 16 |
|
| 17 |
/** Range in which a value is read as a percentage; outside it the value is a fixed Toman amount. */ |
| 18 |
public const PERCENT_RANGE_MIN = -100; |
| 19 |
public const PERCENT_RANGE_MAX = 100; |
| 20 |
|
| 21 |
/** Maximum allowed increase and decrease percentage. */ |
| 22 |
public const MAX_PERCENT = 35; |
| 23 |
public const MIN_PERCENT = -35; |
| 24 |
|
| 25 |
public static function isCommission($value): bool |
| 26 |
{ |
| 27 |
return $value === self::COMMISSION; |
| 28 |
} |
| 29 |
|
| 30 |
public static function isPercent($value): bool |
| 31 |
{ |
| 32 |
return is_numeric($value) && intval($value) >= self::PERCENT_RANGE_MIN && intval($value) <= self::PERCENT_RANGE_MAX; |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Turns a raw input value into a storable value. |
| 37 |
* |
| 38 |
* @return string|null null means the value is empty or invalid |
| 39 |
*/ |
| 40 |
public static function normalize($value): ?string |
| 41 |
{ |
| 42 |
if (self::isCommission($value)) return self::COMMISSION; |
| 43 |
|
| 44 |
if ($value === '' || $value === null || !is_numeric($value)) return null; |
| 45 |
|
| 46 |
return (string) self::clamp(intval($value)); |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Clamps percentages to the allowed -35..35 range; fixed Toman amounts are left untouched. |
| 51 |
*/ |
| 52 |
public static function clamp(int $value): int |
| 53 |
{ |
| 54 |
if (!self::isPercent($value)) return $value; |
| 55 |
|
| 56 |
if ($value > self::MAX_PERCENT) return self::MAX_PERCENT; |
| 57 |
if ($value < self::MIN_PERCENT) return self::MIN_PERCENT; |
| 58 |
|
| 59 |
return $value; |
| 60 |
} |
| 61 |
|
| 62 |
public static function unitLabel($value): string |
| 63 |
{ |
| 64 |
if (self::isCommission($value) || !is_numeric($value)) return 'درصد'; |
| 65 |
|
| 66 |
return self::isPercent($value) ? 'درصد' : 'تو� |
| 67 |
ان'; |
| 68 |
} |
| 69 |
} |
| 70 |
|