4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Filesystem;
14 use Symfony\Component\Filesystem\Exception\IOException;
17 * LockHandler class provides a simple abstraction to lock anything by means of
20 * A locked file is created based on the lock name when calling lock(). Other
21 * lock handlers will not be able to lock the same name until it is released
22 * (explicitly by calling release() or implicitly when the instance holding the
25 * @author Grégoire Pineau <lyrixx@lyrixx.info>
26 * @author Romain Neutron <imprec@gmail.com>
27 * @author Nicolas Grekas <p@tchwork.com>
35 * @param string $name The lock name
36 * @param string|null $lockPath The directory to store the lock. Default values will use temporary directory
38 * @throws IOException If the lock directory could not be created or is not writable
40 public function __construct($name, $lockPath = null)
42 $lockPath = $lockPath ?: sys_get_temp_dir();
44 if (!is_dir($lockPath)) {
45 $fs = new Filesystem();
46 $fs->mkdir($lockPath);
49 if (!is_writable($lockPath)) {
50 throw new IOException(sprintf('The directory "%s" is not writable.', $lockPath), 0, null, $lockPath);
53 $this->file = sprintf('%s/sf.%s.%s.lock', $lockPath, preg_replace('/[^a-z0-9\._-]+/i', '-', $name), hash('sha256', $name));
59 * @param bool $blocking wait until the lock is released
61 * @return bool Returns true if the lock was acquired, false otherwise
63 * @throws IOException If the lock file could not be created or opened
65 public function lock($blocking = false)
71 // Silence error reporting
72 set_error_handler(function () {});
74 if (!$this->handle = fopen($this->file, 'r')) {
75 if ($this->handle = fopen($this->file, 'x')) {
76 chmod($this->file, 0444);
77 } elseif (!$this->handle = fopen($this->file, 'r')) {
78 usleep(100); // Give some time for chmod() to complete
79 $this->handle = fopen($this->file, 'r');
82 restore_error_handler();
85 $error = error_get_last();
86 throw new IOException($error['message'], 0, null, $this->file);
89 // On Windows, even if PHP doc says the contrary, LOCK_NB works, see
90 // https://bugs.php.net/54129
91 if (!flock($this->handle, LOCK_EX | ($blocking ? 0 : LOCK_NB))) {
92 fclose($this->handle);
102 * Release the resource.
104 public function release()
107 flock($this->handle, LOCK_UN | LOCK_NB);
108 fclose($this->handle);
109 $this->handle = null;