1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Buzz\Middleware\History; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Message\RequestInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
|
10
|
|
|
class Journal implements \Countable, \IteratorAggregate |
11
|
|
|
{ |
12
|
|
|
/** @var Entry[] */ |
13
|
|
|
private $entries = []; |
14
|
|
|
private $limit = 10; |
15
|
|
|
|
16
|
3 |
|
public function __construct(int $limit = 10) |
17
|
|
|
{ |
18
|
3 |
|
$this->limit = $limit; |
19
|
3 |
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Records an entry in the journal. |
23
|
|
|
* |
24
|
|
|
* @param RequestInterface $request The request |
25
|
|
|
* @param ResponseInterface $response The response |
26
|
|
|
* @param float|null $duration The duration in seconds |
27
|
|
|
*/ |
28
|
3 |
|
public function record(RequestInterface $request, ResponseInterface $response, float $duration = null): void |
29
|
|
|
{ |
30
|
3 |
|
$this->addEntry(new Entry($request, $response, $duration)); |
31
|
3 |
|
} |
32
|
|
|
|
33
|
3 |
|
public function addEntry(Entry $entry): void |
34
|
|
|
{ |
35
|
3 |
|
array_push($this->entries, $entry); |
36
|
3 |
|
$this->entries = \array_slice($this->entries, $this->getLimit() * -1); |
37
|
3 |
|
end($this->entries); |
38
|
3 |
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @return Entry[] |
42
|
|
|
*/ |
43
|
|
|
public function getEntries(): array |
44
|
|
|
{ |
45
|
|
|
return $this->entries; |
46
|
|
|
} |
47
|
|
|
|
48
|
4 |
|
public function getLast(): ?Entry |
49
|
|
|
{ |
50
|
4 |
|
$entry = end($this->entries); |
51
|
|
|
|
52
|
4 |
|
return false === $entry ? null : $entry; |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
public function getLastRequest(): ?RequestInterface |
56
|
|
|
{ |
57
|
1 |
|
$entry = $this->getLast(); |
58
|
1 |
|
if (null === $entry) { |
59
|
|
|
return null; |
60
|
|
|
} |
61
|
|
|
|
62
|
1 |
|
return $entry->getRequest(); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
public function getLastResponse(): ?ResponseInterface |
66
|
|
|
{ |
67
|
1 |
|
$entry = $this->getLast(); |
68
|
1 |
|
if (null === $entry) { |
69
|
|
|
return null; |
70
|
|
|
} |
71
|
|
|
|
72
|
1 |
|
return $entry->getResponse(); |
73
|
|
|
} |
74
|
|
|
|
75
|
1 |
|
public function clear(): void |
76
|
|
|
{ |
77
|
1 |
|
$this->entries = []; |
78
|
1 |
|
} |
79
|
|
|
|
80
|
3 |
|
public function count(): int |
81
|
|
|
{ |
82
|
3 |
|
return \count($this->entries); |
83
|
|
|
} |
84
|
|
|
|
85
|
1 |
|
public function setLimit(int $limit): void |
86
|
|
|
{ |
87
|
1 |
|
$this->limit = $limit; |
88
|
1 |
|
} |
89
|
|
|
|
90
|
3 |
|
public function getLimit(): int |
91
|
|
|
{ |
92
|
3 |
|
return $this->limit; |
93
|
|
|
} |
94
|
|
|
|
95
|
1 |
|
public function getIterator(): \ArrayIterator |
96
|
|
|
{ |
97
|
1 |
|
return new \ArrayIterator(array_reverse($this->entries)); |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|