| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\WRStats; |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
class LimitBatch { |
| 11 |
|
| 12 |
private $limiter; |
| 13 |
|
| 14 |
|
| 15 |
private $defaultAmount; |
| 16 |
|
| 17 |
|
| 18 |
private $operations = []; |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
public function __construct( |
| 26 |
WRStatsRateLimiter $limiter, |
| 27 |
$defaultAmount |
| 28 |
) { |
| 29 |
$this->limiter = $limiter; |
| 30 |
$this->defaultAmount = $defaultAmount; |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
public function localOp( $condName, $components = [], $amount = null ) { |
| 43 |
if ( !is_array( $components ) ) { |
| 44 |
$components = [ $components ]; |
| 45 |
} |
| 46 |
$this->queueOp( |
| 47 |
$condName, |
| 48 |
new LocalEntityKey( array_merge( [ $condName ], $components ) ), |
| 49 |
$amount |
| 50 |
); |
| 51 |
return $this; |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
public function globalOp( $condName, $components = [], $amount = null ) { |
| 64 |
if ( !is_array( $components ) ) { |
| 65 |
$components = [ $components ]; |
| 66 |
} |
| 67 |
$this->queueOp( |
| 68 |
$condName, |
| 69 |
new GlobalEntityKey( array_merge( [ $condName ], $components ) ), |
| 70 |
$amount |
| 71 |
); |
| 72 |
return $this; |
| 73 |
} |
| 74 |
|
| 75 |
private function queueOp( $type, $entity, $amount ) { |
| 76 |
$amount ??= $this->defaultAmount; |
| 77 |
if ( isset( $this->operations[$type] ) ) { |
| 78 |
throw new WRStatsError( 'Cannot queue multiple actions of the same type, ' . |
| 79 |
'because the result array is indexed by type' ); |
| 80 |
} |
| 81 |
$this->operations[$type] = new LimitOperation( $type, $entity, $amount ); |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
public function peek() { |
| 91 |
return $this->limiter->peekBatch( $this->operations ); |
| 92 |
} |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
public function incr() { |
| 98 |
$this->limiter->incrBatch( $this->operations ); |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
public function tryIncr() { |
| 110 |
return $this->limiter->tryIncrBatch( $this->operations ); |
| 111 |
} |
| 112 |
} |