Completed
Pull Request — master (#51)
by
unknown
10:35
created

CacheLockStorage::exists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * This file is part of php-task library.
5
 *
6
 * (c) php-task
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Task\TaskBundle\Locking;
13
14
use Psr\Cache\CacheItemInterface;
15
use Psr\Cache\InvalidArgumentException;
16
use Symfony\Contracts\Cache\CacheInterface;
17
use Task\Lock\LockStorageInterface;
18
19
/**
20
 * Save locks in Symfony Cache.
21
 */
22
class CacheLockStorage implements LockStorageInterface
23
{
24
25
    /**
26
     * Avoid key collision with a key prefix.
27
     */
28
    const KEY_PREFIX = 'php_task_lock__';
29
30
    /**
31
     * @var CacheInterface
32
     */
33
    protected $cache;
34
35
    /**
36
     * @param CacheInterface $cache
37
     */
38
    public function __construct($cache)
39
    {
40
        $this->cache = $cache;
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function save($key, $ttl)
47
    {
48
        /** @var CacheItemInterface $cacheItem */
49
        $cacheItem = $this->cache->getItem(self::KEY_PREFIX . $key);
50
        $cacheItem->set('LOCK');
51
        $cacheItem->expiresAfter($ttl);
52
        $this->cache->save($cacheItem);
53
        return true;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function delete($key)
60
    {
61
        try {
62
            return $this->cache->deleteItem(self::KEY_PREFIX . $key);
0 ignored issues
show
Bug introduced by
The method deleteItem() does not exist on Symfony\Contracts\Cache\CacheInterface. Did you maybe mean delete()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
63
        } catch (InvalidArgumentException $e) {
64
            return false;
65
        }
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function exists($key)
72
    {
73
        /** @var CacheItemInterface $cacheItem */
74
        $cacheItem = $this->cache->getItem(self::KEY_PREFIX . $key);
75
        return $cacheItem->isHit();
76
    }
77
78
}
79
80