/
FileLogger.php
94 lines (78 loc) · 2.39 KB
/
FileLogger.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace Concrete\Core\Command\Process\Logger;
use Concrete\Core\Entity\Command\Process;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Serializer\Normalizer\DenormalizableInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizableInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class FileLogger implements LoggerInterface, NormalizableInterface, DenormalizableInterface
{
/**
* @var string
*/
protected $directory;
/**
* @var Process
*/
protected $process;
/**
* @var Filesystem
*/
protected $filesystem;
/**
* FileLogger constructor.
* @param string $directory
* @param Process $process
*/
public function __construct(string $directory = null, Process $process = null)
{
$this->filesystem = new Filesystem();
$this->directory = $directory;
$this->process = $process;
}
protected function getLogFileName()
{
$date = date('Y-m-d-H-i', $this->process->getDateStarted());
return snake_case($this->process->getName()) . '-' . $date . '-' . $this->process->getID() . '.log';
}
protected function getFilePath()
{
if (!isset($this->filePath)) {
$this->filePath = $this->directory . $this->getLogFileName();
}
return $this->filePath;
}
public function write($message)
{
$this->filesystem->append($this->getFilePath(), $message . "\n");
}
public function normalize(NormalizerInterface $normalizer, string $format = null, array $context = [])
{
return [
'filePath' => $this->getFilePath(),
];
}
public function denormalize(DenormalizerInterface $denormalizer, $data, string $format = null, array $context = [])
{
$this->filePath = $data['filePath'];
}
public function remove(): void
{
if ($this->logExists()) {
$this->filesystem->delete($this->getFilePath());
}
}
public function readAsArray(): array
{
$output = [];
if ($this->logExists()) {
$output = explode("\n", trim($this->filesystem->get($this->getFilePath())));
}
return $output;
}
public function logExists(): bool
{
return $this->filesystem->exists($this->getFilePath());
}
}