58 lines
1.8 KiB
PHP
58 lines
1.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\Reward\Model;
|
|
|
|
class TierResolver
|
|
{
|
|
public function __construct(private readonly Config $config) {}
|
|
|
|
public function resolve(float $lifetimeSpend, ?int $storeId = null): array
|
|
{
|
|
$tiers = $this->config->tiers($storeId);
|
|
$current = $tiers[0];
|
|
$nextThreshold = null;
|
|
|
|
foreach ($tiers as $tier) {
|
|
if ($lifetimeSpend >= $tier['threshold']) {
|
|
$current = $tier;
|
|
continue;
|
|
}
|
|
$nextThreshold = $tier['threshold'];
|
|
break;
|
|
}
|
|
|
|
return [
|
|
'code' => $current['code'],
|
|
'label' => $current['label'],
|
|
'multiplier' => $current['multiplier'],
|
|
'next_threshold' => $nextThreshold,
|
|
];
|
|
}
|
|
|
|
public function resolveEffective(string $savedTierCode, float $lifetimeSpend, ?int $storeId = null): array
|
|
{
|
|
$tiers = $this->config->tiers($storeId);
|
|
$computed = $this->resolve($lifetimeSpend, $storeId);
|
|
$byCode = [];
|
|
foreach ($tiers as $position => $tier) {
|
|
$byCode[$tier['code']] = ['position' => $position, 'tier' => $tier];
|
|
}
|
|
if (!isset($byCode[$savedTierCode])) {
|
|
return $computed;
|
|
}
|
|
$saved = $byCode[$savedTierCode];
|
|
$computedPosition = $byCode[$computed['code']]['position'] ?? 0;
|
|
if ($saved['position'] <= $computedPosition) {
|
|
return $computed;
|
|
}
|
|
$nextThreshold = $tiers[$saved['position'] + 1]['threshold'] ?? null;
|
|
return [
|
|
'code' => $saved['tier']['code'],
|
|
'label' => $saved['tier']['label'],
|
|
'multiplier' => $saved['tier']['multiplier'],
|
|
'next_threshold' => $nextThreshold,
|
|
];
|
|
}
|
|
}
|