Skip to content

Commit 5301488

Browse files
committed
added acquireLock() and better exception messages
1 parent 191feb6 commit 5301488

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/RobotLoader/RobotLoader.php

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -417,10 +417,7 @@ private function loadCache(): void
417417
return;
418418
}
419419

420-
$handle = fopen("$file.lock", 'cb+');
421-
if (!$handle || !flock($handle, LOCK_EX)) {
422-
throw new \RuntimeException("Unable to create or acquire exclusive lock on file '$file.lock'.");
423-
}
420+
$lock = $this->acquireLock("$file.lock", LOCK_EX);
424421

425422
$data = @include $file; // @ file may not exist
426423
if (is_array($data)) {
@@ -429,8 +426,8 @@ private function loadCache(): void
429426
$this->rebuild();
430427
}
431428

432-
flock($handle, LOCK_UN);
433-
fclose($handle);
429+
flock($lock, LOCK_UN);
430+
fclose($lock);
434431
@unlink("$file.lock"); // @ file may become locked on Windows
435432
}
436433

@@ -453,6 +450,18 @@ private function saveCache(): void
453450
}
454451

455452

453+
private function acquireLock(string $file, int $mode)
454+
{
455+
$handle = @fopen($file, 'cb+'); // @ is escalated to exception
456+
if (!$handle) {
457+
throw new \RuntimeException("Unable to create file '$file'. " . error_get_last()['message']);
458+
} elseif (!@flock($handle, $mode)) { // @ is escalated to exception
459+
throw new \RuntimeException('Unable to acquire ' . ($mode & LOCK_EX ? 'exclusive' : 'shared') . " lock on file '$file'. " . error_get_last()['message']);
460+
}
461+
return $handle;
462+
}
463+
464+
456465
private function getCacheFile(): string
457466
{
458467
if (!$this->tempDirectory) {

0 commit comments

Comments
 (0)