*/ use HasFactory; /** * The setting key holding the advertised amount, in minor units, of the * given plan. */ public static function planAmountKey(string $plan): string { return "plans.{$plan}.amount"; } /** * Get a setting's value, falling back to the given default when the * setting is absent or blank. */ public static function get(string $key, ?string $default = null): ?string { $value = static::query()->where('key', $key)->value('value'); return $value === null || $value === '' ? $default : $value; } /** * Get a setting's value as an integer amount in minor units. * * A value that is not a valid amount is treated as unset rather than shown * as zero, so a bad edit cannot silently advertise a free plan. */ public static function amount(string $key, int $default): int { $value = static::get($key); return is_numeric($value) && (int) $value >= 0 ? (int) $value : $default; } /** * Create or update a setting's value. */ public static function put(string $key, string $value): void { static::query()->updateOrCreate(['key' => $key], ['value' => $value]); } /** * Convert a price typed in major units, such as "12.5", into the minor * units amounts are stored in. * * The value is split as a string rather than multiplied, so that a price * with cents is not subject to floating point drift. */ public static function toMinorUnits(string $amount): int { [$whole, $fraction] = array_pad(explode('.', str_replace(',', '.', trim($amount)), 2), 2, ''); $fraction = substr(str_pad($fraction, 2, '0'), 0, 2); return (int) $whole * 100 + (int) $fraction; } }