CompressionMetrics   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 147
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 90
dl 0
loc 147
rs 10
c 0
b 0
f 0
wmc 15

7 Methods

Rating   Name   Duplication   Size   Complexity  
A detailed() 0 3 1
A summary() 0 9 1
A generateRecommendations() 0 39 5
A benchmark() 0 22 3
A __construct() 0 4 1
A compareSizes() 0 23 1
A full() 0 29 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Squareetlabs\LaravelToon\Services;
6
7
class CompressionMetrics
8
{
9
    public function __construct(
10
        private readonly ToonService $toon = new ToonService(),
11
        private readonly TokenAnalyzer $tokenAnalyzer = new TokenAnalyzer(),
12
    ) {}
13
14
    public function full(mixed $data): array
15
    {
16
        $compressed = $this->toon->compress($data);
17
        $tokenComparison = $this->tokenAnalyzer->compareJsonVsToon($data);
18
19
        return [
20
            'data_summary' => [
21
                'type' => gettype($data),
22
                'size' => is_string($data) ? strlen($data) : (is_array($data) ? count($data) : 0),
23
            ],
24
            'compression' => [
25
                'json_size_bytes' => $compressed['original']['size_bytes'],
26
                'toon_size_bytes' => $compressed['compressed']['size_bytes'],
27
                'bytes_reduced' => $compressed['metrics']['bytes_reduced'],
28
                'percent_reduced' => $compressed['metrics']['percent_reduced'],
29
                'compression_ratio' => $compressed['metrics']['compression_ratio'],
30
            ],
31
            'tokens' => [
32
                'json_tokens' => $tokenComparison['json_tokens'],
33
                'toon_tokens' => $tokenComparison['toon_tokens'],
34
                'tokens_saved' => $tokenComparison['tokens_saved'],
35
                'percent_saved' => $tokenComparison['percent_saved'],
36
                'efficiency_ratio' => $tokenComparison['efficiency_ratio'],
37
            ],
38
            'content' => [
39
                'original_json' => $compressed['original']['content'],
40
                'compressed_toon' => $compressed['compressed']['content'],
41
            ],
42
            'recommendations' => $this->generateRecommendations($compressed, $tokenComparison),
43
        ];
44
    }
45
46
    public function summary(mixed $data): array
47
    {
48
        $compressed = $this->toon->compress($data);
49
50
        return [
51
            'json_size_bytes' => $compressed['original']['size_bytes'],
52
            'toon_size_bytes' => $compressed['compressed']['size_bytes'],
53
            'bytes_saved_percent' => $compressed['metrics']['percent_reduced'],
54
            'tokens_saved_percent' => $compressed['metrics']['token_percent_reduced'],
55
        ];
56
    }
57
58
    public function detailed(mixed $data): array
59
    {
60
        return $this->full($data);
61
    }
62
63
    public function benchmark(mixed $data, int $iterations = 100): array
64
    {
65
        $startTime = microtime(true);
66
        for ($i = 0; $i < $iterations; ++$i) {
67
            $this->toon->encode($data);
68
        }
69
        $encodeTime = microtime(true) - $startTime;
70
71
        $startTime = microtime(true);
72
        $encoded = $this->toon->encode($data);
73
        for ($i = 0; $i < $iterations; ++$i) {
74
            $this->toon->decode($encoded);
75
        }
76
        $decodeTime = microtime(true) - $startTime;
77
78
        return [
79
            'iterations' => $iterations,
80
            'encode_time_seconds' => round($encodeTime, 4),
81
            'encode_time_per_op_ms' => round(($encodeTime / $iterations) * 1000, 4),
82
            'decode_time_seconds' => round($decodeTime, 4),
83
            'decode_time_per_op_ms' => round(($decodeTime / $iterations) * 1000, 4),
84
            'total_time_seconds' => round($encodeTime + $decodeTime, 4),
85
        ];
86
    }
87
88
    public function compareSizes(mixed $data): array
89
    {
90
        $json = json_encode($data, JSON_THROW_ON_ERROR);
91
        $toon = $this->toon->encode($data);
92
        $toonCompact = $this->toon->encodeCompact($data);
93
        $toonTabular = $this->toon->encodeTabular($data);
94
95
        return [
96
            'json' => [
97
                'size_bytes' => strlen($json),
98
                'size_kb' => round(strlen($json) / 1024, 2),
99
            ],
100
            'toon_readable' => [
101
                'size_bytes' => strlen($toon),
102
                'size_kb' => round(strlen($toon) / 1024, 2),
103
            ],
104
            'toon_compact' => [
105
                'size_bytes' => strlen($toonCompact),
106
                'size_kb' => round(strlen($toonCompact) / 1024, 2),
107
            ],
108
            'toon_tabular' => [
109
                'size_bytes' => strlen($toonTabular),
110
                'size_kb' => round(strlen($toonTabular) / 1024, 2),
111
            ],
112
        ];
113
    }
114
115
    private function generateRecommendations(array $compressed, array $tokens): array
116
    {
117
        $recommendations = [];
118
119
        if ($compressed['metrics']['percent_reduced'] > 70) {
120
            $recommendations[] = [
121
                'level' => 'excellent',
122
                'message' => 'Excelente compresión: mayor al 70% de reducción',
123
                'action' => 'Use TOON para este tipo de datos en producción',
124
            ];
125
        } elseif ($compressed['metrics']['percent_reduced'] > 50) {
126
            $recommendations[] = [
127
                'level' => 'good',
128
                'message' => 'Buena compresión: 50-70% de reducción',
129
                'action' => 'TOON es altamente recomendado para este contenido',
130
            ];
131
        } elseif ($compressed['metrics']['percent_reduced'] > 30) {
132
            $recommendations[] = [
133
                'level' => 'moderate',
134
                'message' => 'Compresión moderada: 30-50% de reducción',
135
                'action' => 'Considere usar TOON para casos de uso con restricción de tokens',
136
            ];
137
        } else {
138
            $recommendations[] = [
139
                'level' => 'low',
140
                'message' => 'Compresión baja: menos del 30%',
141
                'action' => 'TOON puede no ser ideal para este tipo de datos',
142
            ];
143
        }
144
145
        if ($tokens['percent_saved'] > 60) {
146
            $recommendations[] = [
147
                'level' => 'important',
148
                'message' => 'Ahorro significativo de tokens: superior al 60%',
149
                'action' => 'Esto resultará en ahorros sustanciales en costos de API',
150
            ];
151
        }
152
153
        return $recommendations;
154
    }
155
}
156
157