Skip to content

Commit d103ea5

Browse files
authored
Merge pull request #3 from dotkernel/issue-2
issue 2
2 parents 9673802 + 31dd33b commit d103ea5

File tree

2 files changed

+38
-21
lines changed

2 files changed

+38
-21
lines changed

src/Application.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public function __destruct()
4545
*/
4646
public function doRun(InputInterface $input, OutputInterface $output): int
4747
{
48-
$this->fileLocker->setCommandName($this->getCommandName($input));
48+
$this->fileLocker->setCommandName($this->getCommandName($input))->initLockFile();
4949

5050
try {
5151
$this->fileLocker->lock();

src/FileLocker.php

Lines changed: 37 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,19 @@ class FileLocker implements FileLockerInterface
2525
private bool $enabled;
2626
private ?string $dirPath;
2727
private ?string $commandName;
28-
28+
private $lockFile;
29+
30+
/**
31+
* @return $this
32+
*/
33+
public function initLockFile(): self
34+
{
35+
if ($this->enabled) {
36+
$this->lockFile = fopen($this->getLockFilePath(), 'w+');
37+
}
38+
return $this;
39+
}
40+
2941
/**
3042
* @return bool
3143
*/
@@ -85,6 +97,25 @@ public function setCommandName(?string $commandName): self
8597
return $this;
8698
}
8799

100+
/**
101+
* @return false|resource
102+
*/
103+
public function getLockFile(): bool
104+
{
105+
return $this->lockFile;
106+
}
107+
108+
/**
109+
* @param bool $lockFile
110+
* @return $this
111+
*/
112+
public function setLockFile(bool $lockFile): self
113+
{
114+
$this->lockFile = $lockFile;
115+
116+
return $this;
117+
}
118+
88119
/**
89120
* @return string
90121
*/
@@ -104,18 +135,11 @@ public function lock(): void
104135
return;
105136
}
106137

107-
if (!is_dir($this->dirPath)) {
108-
mkdir($this->dirPath);
109-
}
110-
111-
$lockFile = $this->getLockFilePath();
112-
$fp = fopen($lockFile, 'w+');
113-
if (!flock($fp, LOCK_EX|LOCK_NB, $wouldBlock)) {
138+
if (!flock($this->lockFile, LOCK_EX|LOCK_NB, $wouldBlock)) {
114139
if ($wouldBlock) {
115-
throw new Exception('Another process holds the lock!');
140+
throw new \Exception('Another process holds the lock!');
116141
}
117142
}
118-
fclose($fp);
119143
}
120144

121145
/**
@@ -126,15 +150,8 @@ public function unlock(): void
126150
if (!$this->enabled) {
127151
return;
128152
}
129-
130-
$lockFile = $this->getLockFilePath();
131-
if (!file_exists($lockFile)) {
132-
return;
133-
}
134-
135-
$fp = fopen($lockFile, 'w+');
136-
flock($fp, LOCK_UN);
137-
fclose($fp);
138-
unlink($lockFile);
153+
154+
flock($this->lockFile, LOCK_UN);
155+
fclose($this->lockFile);
139156
}
140157
}

0 commit comments

Comments
 (0)