Completed
Push — master ( be4b1a...bef8f6 )
by Mathieu
01:51
created

CronScriptTrait::getLockFileName()   A

Complexity

Conditions 1
Paths 1

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 1
nc 1
nop 0
1
<?php
2
3
namespace Charcoal\App\Script;
4
5
use Exception;
6
7
/**
8
 * Cron-job utilities
9
 */
10
trait CronScriptTrait
11
{
12
    /**
13
     * @var boolean $useLock
14
     */
15
    private $useLock = false;
16
17
    /**
18
     * Lock file pointer
19
     * @var resource $lockFilePointer
20
     */
21
    private $lockFilePointer;
22
23
    /**
24
     * @param boolean $useLock The boolean flag if a lock should be used.
25
     * @return self
26
     */
27
    public function setUseLock($useLock)
28
    {
29
        $this->useLock = !!$useLock;
30
        return $this;
31
    }
32
33
    /**
34
     * @return boolean
35
     */
36
    public function useLock()
37
    {
38
        return $this->useLock;
39
    }
40
41
    /**
42
     * @throws Exception If the lock file can not be opened or the script is already locked.
43
     * @return boolean
44
     */
45
    public function startLock()
46
    {
47
        $lockFile = $this->getLockFileName();
48
        $this->lockFilePointer = fopen($lockFile, 'w');
49
        if (!$this->lockFilePointer) {
50
            throw new Exception(
51
                sprintf('Can not run action. Lock file not available: "%s"', $lockFile)
52
            );
53
        }
54
        if (flock($this->lockFilePointer, LOCK_EX)) {
55
            return true;
56
        } else {
57
            throw new Exception(
58
                sprintf('Can not run action. Action locked: "%s".', $lockFile)
59
            );
60
        }
61
    }
62
63
    /**
64
     * @return void
65
     */
66
    public function stopLock()
67
    {
68
        if ($this->lockFilePointer) {
69
            flock($this->lockFilePointer, LOCK_UN);
70
            fclose($this->lockFilePointer);
71
        }
72
    }
73
74
    /**
75
     * @return string
76
     */
77
    private function getLockFileName()
78
    {
79
        $lockName = str_replace('\\', '-', static::class);
80
        $lockName .= md5(__DIR__);
81
82
        return sys_get_temp_dir().DIRECTORY_SEPARATOR.$lockName;
83
    }
84
}
85