1<?php
2
3
4namespace ComboStrap;
5
6/**
7 * Class Mutex
8 * @package ComboStrap
9 * Based on https://www.php.net/manual/en/function.flock.php
10 *
11 * May use also:
12 * https://www.php.net/manual/en/class.syncmutex.php
13 * https://github.com/php-lock/lock
14 *
15 */
16class Mutex
17{
18    /**
19     * @var string
20     */
21    private $filePath;
22    /**
23     * @var false|ResourceCombo
24     */
25    private $filePointer;
26
27
28    /**
29     * Mutex constructor.
30     */
31    public function __construct($filePath)
32    {
33        $this->filePath = $filePath;
34    }
35
36    function lock($wait=10)
37    {
38
39        $this->filePointer = fopen($this->filePath,"w");
40
41        $lock = false;
42        for($i = 0; $i < $wait && !($lock = flock($this->filePointer,LOCK_EX|LOCK_NB)); $i++)
43        {
44            sleep(1);
45        }
46
47        if(!$lock)
48        {
49            trigger_error("Not able to create a lock in $wait seconds");
50        }
51
52        return $this->filePointer;
53    }
54
55    function unlock(): bool
56    {
57        $result = flock($this->filePointer,LOCK_UN);
58        fclose($this->filePointer);
59        @unlink($this->filePath);
60
61        return $result;
62    }
63}
64