MatthiasMullie\Scrapbook\Adapters\Apc::doIncrement PHP Method

doIncrement() protected method

Shared between increment/decrement: both have mostly the same logic (decrement just increments a negative value), but need their validation split up (increment won't accept negative values).
protected doIncrement ( string $key, integer $offset, integer $initial, integer $expire ) : integer | boolean
$key string
$offset integer
$initial integer
$expire integer
return integer | boolean
    protected function doIncrement($key, $offset, $initial, $expire)
    {
        $ttl = $this->ttl($expire);
        /*
         * APC has apc_inc & apc_dec, which work great. However, they don't
         * allow for a TTL to be set.
         * I could use apc_inc & apc_dec & then do a touch, but touch also
         * doesn't have an APC implementation & needs a get & cas. That would
         * be 2 operations + CAS.
         * Instead, I'll just do a get, implement the increase or decrease in
         * PHP, then CAS the new value = 1 operation + CAS.
         */
        $value = $this->get($key, $token);
        if ($value === false) {
            // don't even set initial value, it's already expired...
            if ($ttl < 0) {
                return $initial;
            }
            // no need for locking - set will do that
            $success = $this->add($key, $initial, $ttl);
            return $success ? $initial : false;
        }
        if (!is_numeric($value) || $value < 0) {
            return false;
        }
        $value += $offset;
        // value can never be lower than 0
        $value = max(0, $value);
        // negative TTLs don't always seem to properly treat the key as deleted
        if ($ttl < 0) {
            $success = $this->delete($key);
            return $success ? $value : false;
        }
        // no need for locking - cas will do that
        $success = $this->cas($token, $key, $value, $ttl);
        return $success ? $value : false;
    }