|
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); |
|
|
|
|
|
|
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 === $this->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
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: