47 lines
1.5 KiB
PHP
47 lines
1.5 KiB
PHP
<?php
|
|||
|
|
declare( strict_types=1 );
|
||
|
|
|
||
|
|
namespace StreamGoals\Rules;
|
||
|
|
|
||
|
|
/** Counts `step` per `per_minor`, optionally carrying the remainder to the next donation. */
|
||
|
|
final class CounterRule {
|
||
|
|
|
||
|
|
public function __construct(
|
||
|
|
public readonly int $step,
|
||
|
|
public readonly int $perMinor,
|
||
|
|
public readonly bool $carryOver = true,
|
||
|
|
public readonly string $basis = 'base'
|
||
|
|
) {
|
||
|
|
if ( $perMinor <= 0 || $step < 0 ) {
|
||
|
|
throw new \InvalidArgumentException( 'Invalid counter config.' );
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function fromConfig( array $c ): self {
|
||
|
|
return new self(
|
||
|
|
(int) ( $c['step'] ?? 1 ),
|
||
|
|
(int) ( $c['per_minor'] ?? 0 ),
|
||
|
|
(bool) ( $c['carry_over'] ?? true ),
|
||
|
|
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base'
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/** @return array{delta:int, counter:int, carry:int} */
|
||
|
|
public function apply( Donation $d, int $counter, int $carry ): array {
|
||
|
|
$pool = ( $this->carryOver ? $carry : 0 ) + $d->amountFor( $this->basis );
|
||
|
|
$delta = intdiv( $pool, $this->perMinor ) * $this->step;
|
||
|
|
return array(
|
||
|
|
'delta' => $delta,
|
||
|
|
'counter' => $counter + $delta,
|
||
|
|
'carry' => $this->carryOver ? $pool % $this->perMinor : 0,
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/** @return array{counter:int, carry:int} Counter floors at 0; carry is rolled back by the donation amount. */
|
||
|
|
public function reverse( Donation $d, int $delta, int $counter, int $carry ): array {
|
||
|
|
$carry = $this->carryOver
|
||
|
|
? ( ( $carry - $d->amountFor( $this->basis ) ) % $this->perMinor + $this->perMinor ) % $this->perMinor
|
||
|
|
: 0;
|
||
|
|
return array( 'counter' => max( 0, $counter - $delta ), 'carry' => $carry );
|
||
|
|
}
|
||
|
|
}
|