DocumentLockManager   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 6
Bugs 2 Features 0
Metric Value
eloc 14
c 6
b 2
f 0
dl 0
loc 47
ccs 0
cts 18
cp 0
rs 10
wmc 6

6 Methods

Rating   Name   Duplication   Size   Complexity  
A deleteLock() 0 10 1
A __construct() 0 3 1
A setLock() 0 9 1
A hasLock() 0 5 1
A getLock() 0 3 1
A getCacheId() 0 3 1
1
<?php
2
3
/**
4
 * For the full copyright and license information, please view
5
 * the LICENSE file that was distributed with this source code.
6
 */
7
8
declare(strict_types=1);
9
10
namespace ChampsLibres\WopiLib\Service;
11
12
use ChampsLibres\WopiLib\Contract\Entity\Document;
13
use ChampsLibres\WopiLib\Contract\Service\DocumentLockManagerInterface;
14
use DateInterval;
15
use Psr\Cache\CacheItemPoolInterface;
16
use Psr\Http\Message\RequestInterface;
17
18
final class DocumentLockManager implements DocumentLockManagerInterface
19
{
20
    private CacheItemPoolInterface $cache;
21
22
    public function __construct(CacheItemPoolInterface $cache)
23
    {
24
        $this->cache = $cache;
25
    }
26
27
    public function deleteLock(Document $document, RequestInterface $request): bool
28
    {
29
        // instead of deleting the lock, set a short expiration time
30
        // it gives a chance for concurrent request which put the file content
31
        // to meet an existing lock, and avoid them to be banned
32
        $item = $this->cache->getItem($this->getCacheId($document->getWopiDocId()));
33
34
        $item->expiresAfter(new DateInterval('PT10S'));
35
36
        return $this->cache->save($item);
37
    }
38
39
    public function getLock(Document $document, RequestInterface $request): string
40
    {
41
        return $this->cache->getItem($this->getCacheId($document->getWopiDocId()))->get();
42
    }
43
44
    public function hasLock(Document $document, RequestInterface $request): bool
45
    {
46
        $item = $this->cache->getItem($this->getCacheId($document->getWopiDocId()));
47
48
        return $item->isHit();
49
    }
50
51
    public function setLock(Document $document, string $lockId, RequestInterface $request): bool
52
    {
53
        $item = $this->cache->getItem($this->getCacheId($document->getWopiDocId()));
54
55
        $item->set($lockId);
56
        // according to the specs, lock should last 30M
57
        $item->expiresAfter(new DateInterval('PT31M'));
58
59
        return $this->cache->save($item);
60
    }
61
62
    private function getCacheId(string $documentId): string
63
    {
64
        return sprintf('wopi_lib_lock_%s', $documentId);
65
    }
66
}
67