|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Scheduler\ActionInspector; |
|
4
|
|
|
|
|
5
|
|
|
use Scheduler\Action\ActionInterface; |
|
6
|
|
|
use Scheduler\Exception\SchedulerException; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Class FileActionInspector |
|
10
|
|
|
* @package Scheduler\ActionInspector |
|
11
|
|
|
* @author Aleh Hutnikau, <[email protected]> |
|
12
|
|
|
*/ |
|
13
|
|
|
class FileActionInspector extends AbstractActionInspector |
|
14
|
|
|
{ |
|
15
|
|
|
/** @var string */ |
|
16
|
|
|
private $filePath; |
|
17
|
|
|
|
|
18
|
|
|
/** @var resource */ |
|
19
|
|
|
private $fh; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* FileActionLog constructor. |
|
23
|
|
|
* @param $filePath |
|
24
|
|
|
*/ |
|
25
|
1 |
|
public function __construct($filePath) |
|
26
|
|
|
{ |
|
27
|
1 |
|
$this->filePath = $filePath; |
|
28
|
1 |
|
if (!file_exists($this->filePath)) { |
|
29
|
1 |
|
file_put_contents($this->filePath, ''); |
|
30
|
|
|
} |
|
31
|
1 |
|
$this->fh = fopen($this->filePath, 'r+'); |
|
32
|
1 |
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param ActionInterface $action |
|
36
|
|
|
* @return boolean returns `false` if action is already exists in this state in the log |
|
37
|
|
|
* @throws SchedulerException |
|
38
|
|
|
*/ |
|
39
|
1 |
|
public function update(ActionInterface $action) |
|
40
|
|
|
{ |
|
41
|
1 |
|
flock($this->fh, LOCK_EX); |
|
42
|
1 |
|
fseek($this->fh, 0); |
|
43
|
1 |
|
$content = ''; |
|
44
|
1 |
|
$messages = []; |
|
45
|
1 |
|
while (!feof($this->fh)) { |
|
46
|
1 |
|
$content .= fgets($this->fh); |
|
47
|
|
|
} |
|
48
|
1 |
|
$actionId = $action->getId(); |
|
49
|
1 |
|
$actionState = $action->getState(); |
|
50
|
1 |
|
if ($content) { |
|
51
|
1 |
|
$messages = json_decode($content, true); |
|
52
|
|
|
} |
|
53
|
1 |
|
if (!isset($messages[$actionId])) { |
|
54
|
1 |
|
$messages[$actionId] = ['state' => $actionState]; |
|
55
|
1 |
|
$result = true; |
|
56
|
1 |
|
} else if ($this->isStateAllowed($action, $messages[$actionId]['state'])){ |
|
57
|
|
|
$messages[$actionId]['state'] = $actionState; |
|
58
|
|
|
if ($actionState === ActionInterface::STATE_FINISHED) { |
|
59
|
|
|
$messages[$actionId]['report'] = $action->getReport(); |
|
60
|
|
|
} |
|
61
|
|
|
$result = true; |
|
62
|
|
|
} else { |
|
63
|
1 |
|
$result = false; |
|
64
|
|
|
} |
|
65
|
1 |
|
fseek($this->fh, 0); |
|
66
|
1 |
|
fwrite($this->fh, json_encode($messages)); |
|
67
|
1 |
|
flock($this->fh, LOCK_UN); |
|
68
|
1 |
|
return $result; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
1 |
|
function __destruct() |
|
|
|
|
|
|
72
|
|
|
{ |
|
73
|
1 |
|
fclose($this->fh); |
|
74
|
|
|
} |
|
75
|
|
|
} |
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.