*/ protected function casts(): array { return ['tiers' => 'array', 'replacement_fee' => 'integer']; } /** * The frozen form stored in an offer. * * @return array{name: string, base: string, tiers: list, replacement_fee: ?int} */ public function snapshot(): array { return [ 'name' => $this->name, 'base' => $this->base, 'tiers' => self::normalise((array) $this->tiers), 'replacement_fee' => $this->replacement_fee, ]; } /** * Tiers sorted from the earliest to the latest cancellation: "from N days before arrival: P %". * * @param array> $tiers * @return list */ public static function normalise(array $tiers): array { $clean = array_map(fn (array $tier): array => ['min_days' => max(0, (int) ($tier['min_days'] ?? 0)), 'percent' => min(100, max(0, (int) ($tier['percent'] ?? 0)))], $tiers); usort($clean, fn (array $a, array $b): int => $b['min_days'] <=> $a['min_days']); return array_values($clean); } /** * The tier that applies when cancelling this many days before arrival (the last tier covers everything later). * * @param array{tiers: list} $policy * @return array{min_days: int, percent: int} */ public static function tierFor(array $policy, int $daysBefore): array { foreach ($policy['tiers'] as $tier) { if ($daysBefore >= $tier['min_days']) { return $tier; } } return $policy['tiers'][array_key_last($policy['tiers'])] ?? ['min_days' => 0, 'percent' => 100]; } /** * The rule as readable lines for contracts and pages, e.g. "Rücktritt bis 60 Tage vor Mietbeginn: 0 % …". * * @param array{base: string, tiers: list, replacement_fee: ?int} $policy * @return list */ public static function describe(array $policy): array { $base = $policy['base'] === self::BASE_TOTAL ? 'des Gesamtpreises' : 'des Mietpreises'; $lines = []; $tiers = $policy['tiers']; foreach ($tiers as $index => $tier) { $next = $tiers[$index + 1] ?? null; $when = match (true) { $index === 0 => 'Rücktritt bis '.$tier['min_days'].' Tage vor Mietbeginn', $next === null => 'Rücktritt ab '.($tiers[$index - 1]['min_days'] - 1).' Tage vor Mietbeginn bis Mietbeginn', default => 'Rücktritt '.($tiers[$index - 1]['min_days'] - 1).' bis '.$tier['min_days'].' Tage vor Mietbeginn', }; $lines[] = $when.': '.$tier['percent'].' % '.$base; } if (($policy['replacement_fee'] ?? null) !== null) { $lines[] = 'Stellung eines Ersatzmieters: Bearbeitungsgebühr '.Money::format((int) $policy['replacement_fee']); } return $lines; } }