ToonAnalyzeCommand::handle()   B
last analyzed

Complexity

Conditions 8
Paths 63

Size

Total Lines 99
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 63
nc 63
nop 2
dl 0
loc 99
rs 7.5628
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\ToonService;
10
11
class ToonAnalyzeCommand extends Command
12
{
13
    protected $signature = 'toon:analyze 
14
        {file : Ruta del archivo JSON a analizar}
15
        {--verbose : Mostrar análisis detallado}';
16
17
    protected $description = 'Analiza compresión y eficiencia de TOON vs JSON';
18
19
    public function handle(
20
        ToonService $toonService,
21
        CompressionMetrics $metrics
22
    ): int {
23
        $file = $this->argument('file');
24
        $verbose = $this->option('verbose');
25
26
        if (!file_exists($file)) {
27
            $this->error("Archivo no encontrado: {$file}");
28
29
            return self::FAILURE;
30
        }
31
32
        $content = file_get_contents($file);
33
        if (false === $content) {
34
            $this->error("No se pudo leer el archivo: {$file}");
35
36
            return self::FAILURE;
37
        }
38
39
        try {
40
            $data = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
41
42
            $this->info('📊 ANÁLISIS DE COMPRESIÓN TOON');
43
            $this->newLine();
44
45
            if ($verbose) {
46
                $full = $metrics->full($data);
47
48
                // Data summary
49
                $this->info('Resumen de Datos:');
50
                $this->table(['Propiedad', 'Valor'], [
51
                    ['Tipo', $full['data_summary']['type']],
52
                    ['Tamaño', $full['data_summary']['size']],
53
                ]);
54
55
                // Compression metrics
56
                $this->info('Compresión:');
57
                $this->table(['Métrica', 'Valor'], [
58
                    ['Tamaño JSON', number_format($full['compression']['json_size_bytes']).' bytes'],
59
                    ['Tamaño TOON', number_format($full['compression']['toon_size_bytes']).' bytes'],
60
                    ['Bytes reducidos', number_format($full['compression']['bytes_reduced']).' bytes'],
61
                    ['% Reducción', $full['compression']['percent_reduced'].'%'],
62
                    ['Ratio compresión', $full['compression']['compression_ratio']],
63
                ]);
64
65
                // Token metrics
66
                $this->info('Tokens:');
67
                $this->table(['Métrica', 'Valor'], [
68
                    ['Tokens JSON', number_format($full['tokens']['json_tokens'])],
69
                    ['Tokens TOON', number_format($full['tokens']['toon_tokens'])],
70
                    ['Tokens ahorrados', number_format($full['tokens']['tokens_saved'])],
71
                    ['% Ahorrado', $full['tokens']['percent_saved'].'%'],
72
                ]);
73
74
                // Recommendations
75
                if (!empty($full['recommendations'])) {
76
                    $this->info('Recomendaciones:');
77
                    foreach ($full['recommendations'] as $rec) {
78
                        $icon = match ($rec['level']) {
79
                            'excellent' => '✓',
80
                            'good' => '→',
81
                            'moderate' => '~',
82
                            'important' => '!',
83
                            default => '•',
84
                        };
85
                        $this->info("  {$icon} {$rec['message']}");
86
                        $this->line("    {$rec['action']}");
87
                    }
88
                }
89
90
                $this->newLine();
91
92
                if ($this->confirm('¿Desea ver el contenido comprimido?')) {
93
                    $this->info('JSON Original:');
94
                    $this->line($full['content']['original_json']);
95
                    $this->newLine();
96
                    $this->info('TOON Comprimido:');
97
                    $this->line($full['content']['compressed_toon']);
98
                }
99
            } else {
100
                $summary = $metrics->summary($data);
101
102
                $this->table(['Métrica', 'Valor'], [
103
                    ['JSON Size', number_format($summary['json_size_bytes']).' bytes'],
104
                    ['TOON Size', number_format($summary['toon_size_bytes']).' bytes'],
105
                    ['Bytes Saved', $summary['bytes_saved_percent'].'%'],
106
                    ['Tokens Saved', $summary['tokens_saved_percent'].'%'],
107
                ]);
108
            }
109
110
            $this->newLine();
111
            $this->info('✓ Análisis completado');
112
113
            return self::SUCCESS;
114
        } catch (\Exception $e) {
115
            $this->error('Error durante el análisis: '.$e->getMessage());
116
117
            return self::FAILURE;
118
        }
119
    }
120
}
121
122