*/ private array $limits; /** @var array */ private array $used; /** * @param array $limits Maximum milliseconds/items/requests/bytes. * @param array|null $used Already consumed amounts. */ public function __construct( array $limits, ?array $used = null ) { $dimensions = array( 'milliseconds', 'items', 'requests', 'bytes' ); $normalized = array(); $consumed = array(); foreach ( $dimensions as $dimension ) { if ( ! isset( $limits[ $dimension ] ) || $limits[ $dimension ] < 0 ) { throw new InvalidArgumentException( 'invalid_budget_limit' ); } $normalized[ $dimension ] = $limits[ $dimension ]; $consumed[ $dimension ] = $used[ $dimension ] ?? 0; if ( $consumed[ $dimension ] < 0 || $consumed[ $dimension ] > $normalized[ $dimension ] ) { throw new InvalidArgumentException( 'invalid_consumed_budget' ); } } $this->limits = $normalized; $this->used = $consumed; } public function consume( string $dimension, int $amount ): self { if ( ! array_key_exists( $dimension, $this->limits ) || $amount < 0 ) { throw new InvalidArgumentException( 'invalid_budget_consumption' ); } $next = $this->used[ $dimension ] + $amount; if ( $next > $this->limits[ $dimension ] ) { // The validated dimension key is stored for control flow, never rendered. // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped throw new BudgetExceeded( $dimension ); } $used = $this->used; $used[ $dimension ] = $next; return new self( $this->limits, $used ); } public function remaining( string $dimension ): int { if ( ! array_key_exists( $dimension, $this->limits ) ) { throw new InvalidArgumentException( 'unknown_budget_dimension' ); } return $this->limits[ $dimension ] - $this->used[ $dimension ]; } /** * @return array> */ public function to_array(): array { return array( 'limits' => $this->limits, 'used' => $this->used, ); } }