ManaPHP\Counter\Adapter\Db::increment PHP Method

increment() public method

public increment ( string $type, string $id, integer $step = 1 ) : integer
$type string
$id string
$step integer
return integer
    public function increment($type, $id, $step = 1)
    {
        $hash = md5($type . ':' . $id);
        /**
         * @var \ManaPHP\Counter\Adapter\Db\Model $counter
         */
        $counter = new $this->_model();
        $counter = $counter::findFirst(['hash' => $hash]);
        if (!$counter) {
            try {
                $counter = new $this->_model();
                $counter->hash = $hash;
                $counter->type = $type;
                $counter->id = $id;
                $counter->value = $step;
                $counter->create();
                return (int) $step;
            } catch (\Exception $e) {
                //maybe this record has been inserted by other request.
            }
        }
        for ($i = 0; $i < $this->_maxTries; $i++) {
            $counter = $counter::findFirst(['hash' => $hash]);
            if ($counter === false) {
                return 0;
            }
            $old_value = $counter->value;
            $r = $counter::updateAll(['value =value + :step'], ['hash' => $hash, 'value' => $old_value], ['step' => $step]);
            if ($r === 1) {
                return $old_value + $step;
            }
        }
        throw new DbException('update `:type`:`:id` counter failed: has been tried :times times.', ['type' => $type, 'id' => $id, 'times' => $this->_maxTries]);
    }