2018-02-24 05:12:09 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Support;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Helper math
|
|
|
|
*/
|
|
|
|
class Math
|
|
|
|
{
|
2018-03-06 12:49:42 +08:00
|
|
|
/**
|
|
|
|
* Determine from the base rate, if we want to return the overridden rate
|
|
|
|
* or if the overridden rate is a percentage, then return that amount
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-03-06 12:49:42 +08:00
|
|
|
* @param $base_rate
|
|
|
|
* @param $override_rate
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-03-06 12:49:42 +08:00
|
|
|
* @return float|null
|
|
|
|
*/
|
|
|
|
public static function applyAmountOrPercent($base_rate, $override_rate = null): ?float
|
|
|
|
{
|
|
|
|
if (!$override_rate) {
|
|
|
|
return $base_rate;
|
|
|
|
}
|
|
|
|
|
2018-08-27 00:40:04 +08:00
|
|
|
// Not a percentage override
|
2018-03-06 12:49:42 +08:00
|
|
|
if (substr_count($override_rate, '%') === 0) {
|
|
|
|
return $override_rate;
|
|
|
|
}
|
|
|
|
|
2020-11-27 05:44:57 +08:00
|
|
|
// It is a percent, so apply it
|
|
|
|
return static::getPercent($base_rate, $override_rate);
|
2018-03-06 12:49:42 +08:00
|
|
|
}
|
2018-02-24 05:12:09 +08:00
|
|
|
|
|
|
|
/**
|
2020-11-27 05:44:57 +08:00
|
|
|
* Apply a percentage to a number
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-02-24 05:12:09 +08:00
|
|
|
* @param $number
|
|
|
|
* @param $percent
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-02-24 05:12:09 +08:00
|
|
|
* @return float
|
|
|
|
*/
|
2020-11-27 05:44:57 +08:00
|
|
|
public static function getPercent($number, $percent): float
|
2018-02-24 05:12:09 +08:00
|
|
|
{
|
2018-03-20 09:50:40 +08:00
|
|
|
if (!is_numeric($number)) {
|
2018-02-24 05:12:09 +08:00
|
|
|
$number = (float) $number;
|
|
|
|
}
|
|
|
|
|
2018-03-20 09:50:40 +08:00
|
|
|
if (!is_numeric($percent)) {
|
2018-02-24 05:12:09 +08:00
|
|
|
$percent = (float) $percent;
|
|
|
|
}
|
|
|
|
|
2020-11-27 05:44:57 +08:00
|
|
|
$val = $number * ($percent / 100);
|
|
|
|
|
|
|
|
return $val;
|
2018-02-24 05:12:09 +08:00
|
|
|
}
|
|
|
|
}
|