aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/FileLock.class.php
blob: 064d41ef9cf198ba7f3521ab866408eeba22d397 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
/**
 * file_lock.php
 * Simple lock mechanism on a file basis.
 *
 * With the help of this class you can manage persistent locks. Locks are
 * stored in files and potential additional data is stored as json.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * @author    Jan-Hendrik Willms <tleilax+studip@gmail.com>
 * @copyright 2013 Stud.IP Core-Group
 * @license   http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @category  Stud.IP
 * @since     2.4
 */

class FileLock
{
    protected $file;

    /**
     * Constructs a new lock object with the provided id.
     *
     * @param String $id Identifier of the lock
     */
    public function __construct($id)
    {
        $this->file = fopen("{$GLOBALS['TMP_PATH']}/$id.json", 'c+');

        if (!$this->file) {
            throw new RuntimeException('failed to create lock file.');
        }
    }
    
    /**
     * Try to aquire a file lock. The provided lock information will
     * be stored with the lock. If the lock cannot be aquired, the
     * lock information in $data is updated from the lock file.
     *
     * @param array $data additional data to be stored with the lock
     * @return boolean true on success or false on failure
     */
    public function tryLock(&$data = [])
    {
        rewind($this->file);

        if (flock($this->file, LOCK_EX | LOCK_NB)) {
            ftruncate($this->file, 0);
            fwrite($this->file, json_encode($data));
            fflush($this->file);

            return true;
        } else {
            $json = stream_get_contents($this->file);
            $data = json_decode($json, true);

            return false;
        }
    }

    /**
     * Releases a previously obtained lock
     *
     * @return boolean true on success or false on failure
     */
    public function release()
    {
        return flock($this->file, LOCK_UN);
    }
}