1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spiral\Snapshotter; |
4
|
|
|
|
5
|
|
|
use Spiral\Core\Service; |
6
|
|
|
use Spiral\Debug\Configs\SnapshotConfig; |
7
|
|
|
use Spiral\Debug\SnapshotInterface; |
8
|
|
|
use Spiral\Files\FileManager; |
9
|
|
|
use Spiral\Files\FilesInterface; |
10
|
|
|
|
11
|
|
|
class FileHandler extends Service implements HandlerInterface |
12
|
|
|
{ |
13
|
|
|
/** @var SnapshotConfig */ |
14
|
|
|
private $config; |
15
|
|
|
|
16
|
|
|
/** @var FileManager */ |
17
|
|
|
private $files; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* FileHandler constructor. |
21
|
|
|
* |
22
|
|
|
* @param SnapshotConfig $config |
23
|
|
|
* @param FileManager $files |
24
|
|
|
*/ |
25
|
|
|
public function __construct(SnapshotConfig $config, FileManager $files) |
26
|
|
|
{ |
27
|
|
|
$this->config = $config; |
28
|
|
|
$this->files = $files; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Create snapshot aggregation and aggregated snapshot and tie them together. |
33
|
|
|
* |
34
|
|
|
* @param SnapshotInterface $snapshot |
35
|
|
|
*/ |
36
|
|
|
public function registerSnapshot(SnapshotInterface $snapshot) |
37
|
|
|
{ |
38
|
|
|
if ($this->config->reportingEnabled()) { |
39
|
|
|
$this->saveSnapshot($snapshot); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Save snapshot information on hard-drive. |
45
|
|
|
* |
46
|
|
|
* @param SnapshotInterface $snapshot |
47
|
|
|
*/ |
48
|
|
|
protected function saveSnapshot(SnapshotInterface $snapshot) |
49
|
|
|
{ |
50
|
|
|
$filename = $this->config->snapshotFilename($snapshot->getException(), time()); |
51
|
|
|
|
52
|
|
|
$this->files->write( |
53
|
|
|
$filename, |
54
|
|
|
$snapshot->render(), |
55
|
|
|
FilesInterface::RUNTIME, |
56
|
|
|
true |
57
|
|
|
); |
58
|
|
|
|
59
|
|
|
//Rotating files |
60
|
|
|
$snapshots = $this->files->getFiles($this->config->reportingDirectory()); |
61
|
|
|
if (count($snapshots) > $this->config->maxSnapshots()) { |
62
|
|
|
$this->performRotation($snapshots); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Clean old snapshots. |
68
|
|
|
* |
69
|
|
|
* @param array $snapshots |
70
|
|
|
*/ |
71
|
|
|
protected function performRotation(array $snapshots) |
72
|
|
|
{ |
73
|
|
|
$oldest = ''; |
74
|
|
|
$oldestTimestamp = PHP_INT_MAX; |
75
|
|
|
foreach ($snapshots as $snapshot) { |
76
|
|
|
$snapshotTimestamp = $this->files->time($snapshot); |
77
|
|
|
|
78
|
|
|
if ($snapshotTimestamp < $oldestTimestamp) { |
79
|
|
|
$oldestTimestamp = $snapshotTimestamp; |
80
|
|
|
$oldest = $snapshot; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
$this->files->delete($oldest); |
85
|
|
|
} |
86
|
|
|
} |