FileFactory::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 3
1
<?php
2
3
namespace TH\Lock;
4
5
use Psr\Log\LoggerInterface;
6
use Psr\Log\NullLogger;
7
8
class FileFactory implements Factory
9
{
10
    private $lock_dir;
11
    private $hash_algo;
12
13
    private $logger;
14
15
    /**
16
     * Create a new FileFactory
17
     * @param string               $lock_dir  directory where lock files will be created
18
     * @param string               $hash_algo hashing algotithms used to generate lock file name from identifier
19
     *                                        see http://php.net/manual/en/function.hash-algos.php
20
     * @param LoggerInterface|null $logger
21
     */
22
    public function __construct($lock_dir, $hash_algo = 'sha256', LoggerInterface $logger = null)
23
    {
24
        $this->lock_dir  = $lock_dir;
25
        $this->hash_algo = $hash_algo;
26
27
        $this->logger = $logger ?: new NullLogger;
28
    }
29
30
    /**
31
     * Create a FileLock for $resource
32
     * @param string      $resource  resource identifier
33
     * @param boolean     $exclusive true for an exclusive lock, false for shared one
34
     * @param boolean     $blocking  true to wait for lock to be available, false to throw exception instead of waiting
35
     * @return FileLock
36
     */
37
    public function create(
38
        $resource,
39
        $exclusive = FileLock::EXCLUSIVE,
40
        $blocking = FileLock::NON_BLOCKING
41
    ) {
42
        if (!is_dir($this->lock_dir)) {
43
            mkdir($this->lock_dir, 0777, true);
44
        }
45
        $hash = hash($this->hash_algo, serialize($resource));
46
        $path = "{$this->lock_dir}/$hash.lock";
47
        return new FileLock($path, $exclusive, $blocking, true, $this->logger);
48
    }
49
}
50