Passed
Pull Request — master (#160)
by Dmitriy
02:29
created

HttpStreamCollector   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 24
dl 0
loc 69
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A getCollected() 0 3 1
A startup() 0 12 1
A reset() 0 3 1
A collect() 0 9 2
A getIndexData() 0 11 2
A shutdown() 0 7 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Debug\Collector\Stream;
6
7
use Yiisoft\Yii\Debug\Collector\CollectorInterface;
8
use Yiisoft\Yii\Debug\Collector\CollectorTrait;
9
use Yiisoft\Yii\Debug\Collector\IndexCollectorInterface;
10
11
final class HttpStreamCollector implements CollectorInterface, IndexCollectorInterface
12
{
13
    use CollectorTrait;
14
15
    public function __construct(private array $ignoredPathPatterns = [], private array $ignoredClasses = [])
16
    {
17
    }
18
19
    private array $requests = [];
20
21
    public function getCollected(): array
22
    {
23
        return $this->requests;
24
    }
25
26
    public function startup(): void
27
    {
28
        $this->isActive = true;
29
        HttpStreamProxy::register();
30
        // TODO: add cURL support, maybe through proxy?
31
        // https://github.com/php/php-src/issues/10509
32
        //stream_context_set_default([
33
        //    'http' => [
34
        //        'proxy' => 'yii-debug-http://127.0.0.1',
35
        //    ],
36
        //]);
37
        HttpStreamProxy::$collector = $this;
38
    }
39
40
    public function shutdown(): void
41
    {
42
        HttpStreamProxy::unregister();
43
        HttpStreamProxy::$collector = null;
44
45
        $this->reset();
46
        $this->isActive = false;
47
    }
48
49
    public function collect(string $operation, string $path, array $args): void
50
    {
51
        if (!$this->isActive()) {
52
            return;
53
        }
54
55
        $this->requests[$operation][] = [
56
            'uri' => $path,
57
            'args' => $args,
58
        ];
59
    }
60
61
    public function getIndexData(): array
62
    {
63
        return [
64
            'http_stream' => array_merge(
65
                ...array_map(
66
                    fn (string $operation) => [
67
                        $operation => is_countable($this->requests[$operation]) ? count(
68
                            $this->requests[$operation]
69
                        ) : 0,
70
                    ],
71
                    array_keys($this->requests)
72
                )
73
            ),
74
        ];
75
    }
76
77
    private function reset(): void
78
    {
79
        $this->requests = [];
80
    }
81
}
82