LockingIterator::getLockName()   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 1
1
<?php
2
3
namespace itertools;
4
5
use ArrayIterator;
6
use Exception;
7
use IteratorIterator;
8
9
class LockingIterator extends IteratorIterator
10
{
11
    protected $lockFp;
12
    protected $dir;
13
    protected $lockNameMapper;
14
15
    public function __construct($iterable, $dir, $lockNameMapper = null)
16
    {
17
        parent::__construct(IterUtil::asTraversable($iterable));
18
        $this->dir = $dir;
19
        $this->lockNameMapper = $lockNameMapper;
20
    }
21
22
    protected function lock($name)
23
    {
24
        @mkdir($this->dir, 0777, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
25
        if (! is_dir($this->dir) || ! is_writable($this->dir)) {
26
            throw new Exception("Could not create directory '{$this->dir}' to store lock files");
27
        }
28
        $this->lockFp = fopen("{$this->dir}/$name", 'w+');
29
        if (false === $this->lockFp) {
30
            throw new Exception("Error while trying to open lockfile '{$this->dir}/$name'");
31
        }
32
        $flockStatus = flock($this->lockFp, LOCK_EX);
33
        if (false === $flockStatus) {
34
            throw new Exception("Error while trying to lock file '{$this->dir}/$name'");
35
        }
36
    }
37
38
    protected function unlock()
39
    {
40
        flock($this->lockFp, LOCK_UN);
41
        fclose($this->lockFp);
42
        $this->lockFp = null;
43
    }
44
45
    public function current()
46
    {
47
        $current = parent::current();
48
        if ($this->lockFp === null) {
49
            $this->lock($this->getLockName($current));
50
        }
51
        return $current;
52
    }
53
54
    protected function getLockName($current)
55
    {
56
        if (null === $this->lockNameMapper) {
57
            return $current;
58
        }
59
        return call_user_func($this->lockNameMapper, $current);
60
    }
61
    
62
63
    public function next()
64
    {
65
        if ($this->lockFp !== null) {
66
            $this->unlock();
67
        }
68
        parent::next();
69
    }
70
}
71
72
 
73