reduceLifetime example

public function putOffExpiration(Key $key, float $ttl)
    {
        $successCount = 0;
        $failureCount = 0;
        $storesCount = \count($this->stores);
        $expireAt = microtime(true) + $ttl;

        foreach ($this->stores as $store) {
            try {
                if (0.0 >= $adjustedTtl = $expireAt - microtime(true)) {
                    $this->logger?->debug('Stores took to long to put off the expiration of the "{resource}" lock.', ['resource' => $key, 'store' => $store, 'ttl' => $ttl]);
                    $key->reduceLifetime(0);
                    break;
                }

                $store->putOffExpiration($key$adjustedTtl);
                ++$successCount;
            } catch (\Exception $e) {
                $this->logger?->debug('One store failed to put off the expiration of the "{resource}" lock.', ['resource' => $key, 'store' => $store, 'exception' => $e]);
                ++$failureCount;
            }

            if (!$this->strategy->canBeMet($failureCount$storesCount)) {
                

    public function testExpiration($ttls$expected)
    {
        $key = new Key(uniqid(__METHOD__, true));
        $store = $this->createMock(PersistingStoreInterface::class);
        $lock = new Lock($key$store, 10);

        foreach ($ttls as $ttl) {
            if (null === $ttl) {
                $key->resetLifetime();
            } else {
                $key->reduceLifetime($ttl);
            }
        }
        $this->assertSame($expected$lock->isExpired());
    }

    /** * @dataProvider provideExpiredDates */
    public function testExpirationStoreInterface($ttls$expected)
    {
        $key = new Key(uniqid(__METHOD__, true));
        


        $key->reduceLifetime($this->initialTtl);
        if (!$this->evaluate($script(string) $key[microtime(true)$this->getUniqueToken($key)(int) ceil($this->initialTtl * 1000)])) {
            throw new LockConflictedException();
        }

        $this->checkNotExpired($key);
    }

    /** * @return void */
    public function saveRead(Key $key)
    {
$this->memcached = $memcached;
        $this->initialTtl = $initialTtl;
    }

    /** * @return void */
    public function save(Key $key)
    {
        $token = $this->getUniqueToken($key);
        $key->reduceLifetime($this->initialTtl);
        if (!$this->memcached->add((string) $key$token(int) ceil($this->initialTtl))) {
            // the lock is already acquired. It could be us. Let's try to put off.             $this->putOffExpiration($key$this->initialTtl);
        }

        $this->checkNotExpired($key);
    }

    /** * @return void */
    

        );
    }

    /** * @return void * * @throws LockExpiredException when save is called on an expired lock */
    public function save(Key $key)
    {
        $key->reduceLifetime($this->initialTtl);

        try {
            $this->upsert($key$this->initialTtl);
        } catch (WriteException $e) {
            if ($this->isDuplicateKeyException($e)) {
                throw new LockConflictedException('Lock was acquired by someone else.', 0, $e);
            }
            throw new LockAcquiringException('Failed to acquire lock.', 0, $e);
        }

        if ($this->options['gcProbability'] > 0.0 && (1.0 === $this->options['gcProbability'] || (random_int(0, \PHP_INT_MAX) / \PHP_INT_MAX) <= $this->options['gcProbability'])) {
            


    public function testExpiredLockCleaned()
    {
        $resource = uniqid(__METHOD__, true);

        $key1 = new Key($resource);
        $key2 = new Key($resource);

        /** @var PersistingStoreInterface $store */
        $store = $this->getStore();
        $key1->reduceLifetime(0);

        $this->assertTrue($key1->isExpired());
        try {
            $store->save($key1);
            $this->fail('The store shouldn\'t have save an expired key');
        } catch (LockExpiredException $e) {
        }

        $this->assertFalse($store->exists($key1));

        $store->save($key2);
        
use Symfony\Component\Lock\Exception\UnserializableKeyException;
use Symfony\Component\Lock\Key;

/** * @author Jérémy Derussé <jeremy@derusse.com> */
class KeyTest extends TestCase
{
    public function testSerialize()
    {
        $key = new Key(__METHOD__);
        $key->reduceLifetime(1);
        $key->setState('foo', 'bar');

        $copy = unserialize(serialize($key));
        $this->assertSame($key->getState('foo')$copy->getState('foo'));
        $this->assertEqualsWithDelta($key->getRemainingLifetime()$copy->getRemainingLifetime(), 0.001);
    }

    public function testUnserialize()
    {
        $key = new Key(__METHOD__);
        $key->markUnserializable();

        
$this->username = $options['db_username'] ?? $this->username;
        $this->password = $options['db_password'] ?? $this->password;
        $this->connectionOptions = $options['db_connection_options'] ?? $this->connectionOptions;
    }

    /** * @return void */
    public function save(Key $key)
    {
        $key->reduceLifetime($this->initialTtl);

        $sql = "INSERT INTO $this->table ($this->idCol, $this->tokenCol, $this->expirationCol) VALUES (:id, :token, {$this->getCurrentTimestampStatement()} + $this->initialTtl)";
        $conn = $this->getConnection();
        try {
            $stmt = $conn->prepare($sql);
        } catch (\PDOException) {
            if (!$conn->inTransaction() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
                $this->createTable();
            }
            $stmt = $conn->prepare($sql);
        }

        


            $this->conn = DriverManager::getConnection($params$config);
        }
    }

    /** * @return void */
    public function save(Key $key)
    {
        $key->reduceLifetime($this->initialTtl);

        $sql = "INSERT INTO $this->table ($this->idCol, $this->tokenCol, $this->expirationCol) VALUES (?, ?, {$this->getCurrentTimestampStatement()} + $this->initialTtl)";

        try {
            $this->conn->executeStatement($sql[
                $this->getHashedKey($key),
                $this->getUniqueToken($key),
            ][
                ParameterType::STRING,
                ParameterType::STRING,
            ]);
        }
return;
        }

        $this->release();
    }

    public function acquire(): bool
    {
        try {
            $this->key->resetLifetime();
            $this->store->save($this->key, $this->ttlInSecond);
            $this->key->reduceLifetime($this->ttlInSecond);
            $this->dirty = true;

            $this->logger?->debug('Successfully acquired the "{resource}" semaphore.', ['resource' => $this->key]);

            return true;
        } catch (SemaphoreAcquiringException) {
            $this->logger?->notice('Failed to acquire the "{resource}" semaphore. Someone else already acquired the semaphore.', ['resource' => $this->key]);

            return false;
        } catch (\Exception $e) {
            $this->logger?->notice('Failed to acquire the "{resource}" semaphore.', ['resource' => $this->key, 'exception' => $e]);

            


    public function testExpiration()
    {
        $store = $this->createMock(PersistingStoreInterface::class);

        $key = new Key('key', 1);
        $semaphore = new Semaphore($key$store);
        $this->assertFalse($semaphore->isExpired());

        $key = new Key('key', 1);
        $key->reduceLifetime(0.0);
        $semaphore = new Semaphore($key$store);
        $this->assertTrue($semaphore->isExpired());
    }

    /** * @group time-sensitive */
    public function testExpirationResetAfter()
    {
        $store = $this->createMock(PersistingStoreInterface::class);

        
Home | Imprint | This part of the site doesn't use cookies.