1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102:
<?php
namespace LeanCloud\Operation;
use LeanCloud\Operation\SetOperation;
class IncrementOperation implements IOperation {
private $key;
private $value;
public function __construct($key, $val) {
if (!is_numeric($val)) {
throw new \InvalidArgumentException("Operand must be number.");
}
$this->key = $key;
$this->value = $val;
}
public function getKey() {
return $this->key;
}
public function getValue() {
return $this->value;
}
public function encode() {
return array("__op" => "Increment",
"amount" => $this->value);
}
public function applyOn($oldval) {
$oldval = is_null($oldval) ? 0 : $oldval;
if (is_numeric($oldval)) {
return $this->value + $oldval;
}
throw new \RuntimeException("Operation incompatible with previous value.");
}
public function mergeWith($prevOp) {
if (!$prevOp) {
return $this;
} else if ($prevOp instanceof SetOperation) {
return new SetOperation($this->getKey(),
$this->applyOn($prevOp->getValue()));
} else if ($prevOp instanceof IncrementOperation) {
return new IncrementOperation($this->getKey(),
$this->applyOn($prevOp->getValue()));
} else if ($prevOp instanceof DeleteOperation){
return new SetOperation($this->getKey(), $this->getValue());
} else {
throw new \RuntimeException("Operation incompatible with previous one.");
}
}
}