1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Debug; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
8
|
|
|
use Yiisoft\Strings\WildcardPattern; |
9
|
|
|
use Yiisoft\Yii\Debug\Collector\CollectorInterface; |
10
|
|
|
use Yiisoft\Yii\Debug\Storage\StorageInterface; |
11
|
|
|
use Yiisoft\Yii\Web\Event\BeforeRequest; |
12
|
|
|
|
13
|
|
|
final class Debugger |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var CollectorInterface[] |
17
|
|
|
*/ |
18
|
|
|
private array $collectors; |
19
|
|
|
private bool $skipCollect = false; |
20
|
|
|
private array $optionalRequests; |
21
|
|
|
private StorageInterface $target; |
22
|
|
|
private DebuggerIdGenerator $idGenerator; |
23
|
|
|
|
24
|
6 |
|
public function __construct( |
25
|
|
|
DebuggerIdGenerator $idGenerator, |
26
|
|
|
StorageInterface $target, |
27
|
|
|
array $collectors, |
28
|
|
|
array $optionalRequests = [] |
29
|
|
|
) { |
30
|
6 |
|
$this->collectors = $collectors; |
31
|
6 |
|
$this->optionalRequests = $optionalRequests; |
32
|
6 |
|
$this->target = $target; |
33
|
6 |
|
$this->idGenerator = $idGenerator; |
34
|
6 |
|
} |
35
|
|
|
|
36
|
1 |
|
public function getId(): string |
37
|
|
|
{ |
38
|
1 |
|
return $this->idGenerator->getId(); |
39
|
|
|
} |
40
|
|
|
|
41
|
3 |
|
public function startup(object $event): void |
42
|
|
|
{ |
43
|
3 |
|
if ($event instanceof BeforeRequest && $this->isOptionalRequest($event->getRequest())) { |
44
|
1 |
|
$this->skipCollect = true; |
45
|
1 |
|
return; |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
$this->idGenerator->reset(); |
49
|
2 |
|
foreach ($this->collectors as $collector) { |
50
|
2 |
|
$this->target->addCollector($collector); |
51
|
2 |
|
$collector->startup(); |
52
|
|
|
} |
53
|
2 |
|
} |
54
|
|
|
|
55
|
2 |
|
private function isOptionalRequest(ServerRequestInterface $request): bool |
56
|
|
|
{ |
57
|
2 |
|
$path = $request->getUri()->getPath(); |
58
|
2 |
|
foreach ($this->optionalRequests as $pattern) { |
59
|
2 |
|
if ((new WildcardPattern($pattern))->match($path)) { |
60
|
1 |
|
return true; |
61
|
|
|
} |
62
|
|
|
} |
63
|
1 |
|
return false; |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
public function shutdown(): void |
67
|
|
|
{ |
68
|
|
|
try { |
69
|
2 |
|
if (!$this->skipCollect) { |
70
|
1 |
|
$this->target->flush(); |
71
|
|
|
} |
72
|
2 |
|
} finally { |
73
|
2 |
|
foreach ($this->collectors as $collector) { |
74
|
2 |
|
$collector->shutdown(); |
75
|
|
|
} |
76
|
2 |
|
$this->skipCollect = false; |
77
|
|
|
} |
78
|
2 |
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @param array $optionalRequests Patterns for optional request URLs. |
82
|
|
|
* |
83
|
|
|
* @see WildcardPattern |
84
|
|
|
* |
85
|
|
|
* @return self |
86
|
|
|
*/ |
87
|
1 |
|
public function withOptionalRequests(array $optionalRequests): self |
88
|
|
|
{ |
89
|
1 |
|
$new = clone $this; |
90
|
1 |
|
$new->optionalRequests = $optionalRequests; |
91
|
1 |
|
return $new; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|