1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Copyright Aleksandar Panic |
4
|
|
|
* |
5
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
6
|
|
|
* you may not use this file except in compliance with the License. |
7
|
|
|
* You may obtain a copy of the License at |
8
|
|
|
* |
9
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
10
|
|
|
* |
11
|
|
|
* Unless required by applicable law or agreed to in writing, software |
12
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
13
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
14
|
|
|
* See the License for the specific language governing permissions and |
15
|
|
|
* limitations under the License. |
16
|
|
|
**/ |
17
|
|
|
|
18
|
|
|
namespace ArekX\DataStreamer\FailHandler; |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
use ArekX\DataStreamer\Contracts\FailHandler; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Class FileLogHandler |
25
|
|
|
* @package ArekX\DataStreamer\FailHandler |
26
|
|
|
* |
27
|
|
|
* @codeCoverageIgnore |
28
|
|
|
*/ |
29
|
|
|
class FileLogHandler implements FailHandler |
30
|
|
|
{ |
31
|
|
|
/** |
32
|
|
|
* Represents a resource to the log file. |
33
|
|
|
* @var resource |
34
|
|
|
*/ |
35
|
|
|
protected $logFile; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Represents a path where the log file is located. |
39
|
|
|
* @var string |
40
|
|
|
*/ |
41
|
|
|
protected $path; |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* FileLogHandler constructor. |
45
|
|
|
* @param string $logFilePath |
46
|
|
|
*/ |
47
|
|
|
public function __construct(string $logFilePath) |
48
|
|
|
{ |
49
|
|
|
$this->path = $logFilePath; |
50
|
|
|
$this->openLogFile(); |
51
|
|
|
|
52
|
|
|
register_shutdown_function(function () { |
53
|
|
|
$this->closeLogFile(); |
54
|
|
|
}); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @inheritDoc |
59
|
|
|
*/ |
60
|
|
|
public function handle(array $failedItems) |
61
|
|
|
{ |
62
|
|
|
if (!is_resource($this->logFile)) { |
63
|
|
|
return; |
64
|
|
|
} |
65
|
|
|
$time = microtime(true); |
66
|
|
|
|
67
|
|
|
$lines = ""; |
68
|
|
|
foreach ($failedItems as $failedItem) { |
69
|
|
|
$lines .= "[{$time}]: " . json_encode($failedItem) . PHP_EOL; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
fwrite($this->logFile, $lines); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* Opens the file at location for writing data. |
77
|
|
|
*/ |
78
|
|
|
public function openLogFile(): void |
79
|
|
|
{ |
80
|
|
|
$this->logFile = fopen($this->path, "a"); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* Closes the file and ends writing. |
85
|
|
|
*/ |
86
|
|
|
public function closeLogFile(): void |
87
|
|
|
{ |
88
|
|
|
if (is_resource($this->logFile)) { |
89
|
|
|
fclose($this->logFile); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
} |