ToonBenchmarkCommand::handle()   B
last analyzed

Complexity

Conditions 6
Paths 27

Size

Total Lines 78
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 48
nc 27
nop 2
dl 0
loc 78
rs 8.5123
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Squareetlabs\LaravelToon\Console\Commands;
6
7
use Illuminate\Console\Command;
8
use Squareetlabs\LaravelToon\Services\CompressionMetrics;
9
use Squareetlabs\LaravelToon\Services\CostCalculator;
0 ignored issues
show
Bug introduced by
The type Squareetlabs\LaravelToon\Services\CostCalculator was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
11
class ToonBenchmarkCommand extends Command
12
{
13
    protected $signature = 'toon:benchmark 
14
        {file : Ruta del archivo JSON}
15
        {--iterations=100 : Número de iteraciones}
16
        {--model= : Modelo LLM para comparar costos}';
17
18
    protected $description = 'Ejecuta benchmark de rendimiento y estimación de costos';
19
20
    public function handle(
21
        CompressionMetrics $metrics,
22
        CostCalculator $costCalculator
23
    ): int {
24
        $file = $this->argument('file');
25
        $iterations = (int)$this->option('iterations');
26
        $model = $this->option('model');
27
28
        if (!file_exists($file)) {
29
            $this->error("Archivo no encontrado: {$file}");
30
31
            return self::FAILURE;
32
        }
33
34
        $content = file_get_contents($file);
35
        if (false === $content) {
36
            $this->error("No se pudo leer el archivo: {$file}");
37
38
            return self::FAILURE;
39
        }
40
41
        try {
42
            $data = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
43
44
            $this->info('⚡ BENCHMARK DE RENDIMIENTO Y COSTOS');
45
            $this->newLine();
46
47
            // Performance benchmark
48
            $this->info('Ejecutando benchmark de rendimiento...');
49
            $benchmark = $metrics->benchmark($data, $iterations);
50
51
            $this->table(['Métrica', 'Valor'], [
52
                ['Iteraciones', number_format($benchmark['iterations'])],
53
                ['Tiempo de codificación (total)', $benchmark['encode_time_seconds'].' s'],
54
                ['Tiempo por operación (encode)', $benchmark['encode_time_per_op_ms'].' ms'],
55
                ['Tiempo de decodificación (total)', $benchmark['decode_time_seconds'].' s'],
56
                ['Tiempo por operación (decode)', $benchmark['decode_time_per_op_ms'].' ms'],
57
                ['Tiempo total', $benchmark['total_time_seconds'].' s'],
58
            ]);
59
60
            // Cost comparison
61
            $this->newLine();
62
            $this->info('Comparación de tamaños:');
63
64
            $sizes = $metrics->compareSizes($data);
65
            $this->table(['Formato', 'Bytes', 'KB'], [
66
                ['JSON', number_format($sizes['json']['size_bytes']), $sizes['json']['size_kb']],
67
                ['TOON Readable', number_format($sizes['toon_readable']['size_bytes']), $sizes['toon_readable']['size_kb']],
68
                ['TOON Compact', number_format($sizes['toon_compact']['size_bytes']), $sizes['toon_compact']['size_kb']],
69
                ['TOON Tabular', number_format($sizes['toon_tabular']['size_bytes']), $sizes['toon_tabular']['size_kb']],
70
            ]);
71
72
            // Cost estimation if model is provided
73
            if ($model) {
74
                $this->newLine();
75
                $this->info('Estimación de costos de API:');
76
77
                $costComparison = $costCalculator->estimateWithJsonComparison($model, $data, 'input');
78
79
                if ($costComparison['success']) {
80
                    $this->table(['Formato', 'Tokens', 'Costo'], [
81
                        ['JSON', number_format($costComparison['json']['tokens']), $costComparison['json']['cost_formatted']],
82
                        ['TOON', number_format($costComparison['toon']['tokens']), $costComparison['toon']['cost_formatted']],
83
                        ['Ahorros', number_format($costComparison['savings']['tokens']), $costComparison['savings']['cost_formatted'].' ('.$costComparison['savings']['percent'].'%)'],
84
                    ]);
85
                } else {
86
                    $this->warn('Modelo no encontrado: '.$model);
87
                }
88
            }
89
90
            $this->newLine();
91
            $this->info('✓ Benchmark completado exitosamente');
92
93
            return self::SUCCESS;
94
        } catch (\Exception $e) {
95
            $this->error('Error durante benchmark: '.$e->getMessage());
96
97
            return self::FAILURE;
98
        }
99
    }
100
}
101
102