Completed
Branch symfony-console (0fa491)
by Kacper
03:12
created

HighlightCommand::execute()   F

Complexity

Conditions 14
Paths 538

Size

Total Lines 85
Code Lines 53

Duplication

Lines 8
Ratio 9.41 %

Importance

Changes 5
Bugs 0 Features 1
Metric Value
cc 14
eloc 53
c 5
b 0
f 1
nc 538
nop 2
dl 8
loc 85
rs 2.8147

How to fix   Long Method    Complexity   

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
 * Highlighter
4
 *
5
 * Copyright (C) 2016, Some right reserved.
6
 *
7
 * @author Kacper "Kadet" Donat <[email protected]>
8
 *
9
 * Contact with author:
10
 * Xmpp: [email protected]
11
 * E-mail: [email protected]
12
 *
13
 * From Kadet with love.
14
 */
15
16
namespace Kadet\Highlighter\bin\Commands;
17
18
19
use Kadet\Highlighter\Formatter\DebugFormatter;
20
use Kadet\Highlighter\KeyLighter;
21
use Kadet\Highlighter\Language\Language;
22
use Symfony\Component\Console\Command\Command;
23
use Symfony\Component\Console\Exception\InvalidArgumentException;
24
use Symfony\Component\Console\Input\InputArgument;
25
use Symfony\Component\Console\Input\InputInterface;
26
use Symfony\Component\Console\Input\InputOption;
27
use Symfony\Component\Console\Output\Output;
28
use Symfony\Component\Console\Output\OutputInterface;
29
30
class HighlightCommand extends Command
31
{
32
    protected $_debug = ['time', 'detailed-time', 'count', 'tree-before', 'tree-after', 'memory'];
33
34
    protected function configure()
35
    {
36
        $this->setName('highlight')
37
            ->addArgument('path', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'File(s) to highlight')
38
            ->addOption('language', 'l', InputOption::VALUE_OPTIONAL, 'Source Language to highlight, see <comment>list-languages</comment> command')
39
            ->addOption('format', 'f', InputOption::VALUE_OPTIONAL, 'Output format, see <comment>list-languages</comment> command', 'cli')
40
            ->addOption(
41
                'debug', 'd', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
42
                'Debug features (only in verbose): '.implode(', ', array_map(function($f) { return "<info>{$f}</info>"; }, $this->_debug))
43
            )
44
            ->setDescription('<comment>[DEFAULT]</comment> Highlights given file')
45
        ;
46
    }
47
48
    protected function execute(InputInterface $input, OutputInterface $output)
49
    {
50
        if(!empty($input->getOption('debug')) && $output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) {
51
            $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
52
        }
53
54
        $output->writeln($this->getApplication()->getLongVersion()."\n", Output::VERBOSITY_VERBOSE);
55
56
        $debugFormatter = new DebugFormatter();
57
        foreach($input->getArgument('path') as $filename) {
58
            $language = $input->getOption('language')
59
                ? Language::byName($input->getOption('language'))
60
                : Language::byFilename($filename);
61
62
            $formatter = KeyLighter::get()->getFormatter($input->getOption('format')) ?: KeyLighter::get()->getDefaultFormatter();
63
64
            if(!($source = $this->content($filename))) {
65
                throw new InvalidArgumentException(sprintf('Specified file %s doesn\'t exist, check if given path is correct.', $filename));
66
            }
67
68
            if($output->isVerbose()) {
69
                $counts = ['before' => null, 'after' => null];
70
                $times  = ['tokenization' => null, 'parsing' => null, 'formatting' => null];
71
72
                $output->writeln(sprintf(
73
                    "Used file: <path>%s</path>, Language: <language>%s</language>, Formatter: <formatter>%s</formatter>",
74
                    $filename, $language->getFQN(), get_class($formatter)
75
                ));
76
77
                $tokens    = $this->benchmark($output, function() use($language, $source) { return $language->tokenize($source); }, $times['tokenization']);
78
                $counts['before'] = count($tokens);
79 View Code Duplication
                if(in_array('tree-before', $input->getOption('debug'))) {
80
                    $output->writeln('<comment>Token tree before parsing: </comment>');
81
                    $output->writeln($debugFormatter->format(clone $tokens, false));
82
                }
83
84
                $tokens    = $this->benchmark($output, function() use($language, $tokens) { return $language->parse($tokens); }, $times['parsing']);
85
                $counts['after'] = count($tokens);
86 View Code Duplication
                if(in_array('tree-after', $input->getOption('debug'))) {
87
                    $output->writeln('<comment>Token tree after parsing: </comment>');
88
                    $output->writeln($debugFormatter->format(clone $tokens));
89
                }
90
91
                $formatted = $this->benchmark($output, function() use($formatter, $tokens) { return $formatter->format($tokens); }, $times['formatting']);
92
93
                if(in_array('count', $input->getOption('debug'))) {
94
                    $output->writeln(sprintf(
95
                        '<comment>Token count before parsing: </comment> %s (%s tokens/kB)',
96
                        $counts['before'], number_format($counts['before']/strlen($source) * 1024)
97
                    ));
98
                    $output->writeln(sprintf(
99
                        '<comment>Token count after parsing:  </comment> %s (%s tokens/kB)',
100
                        $counts['after'], number_format($counts['after']/strlen($source) * 1024)
101
                    ));
102
                }
103
104
                if(in_array('detailed-time', $input->getOption('debug'))) {
105
                    $output->writeln(sprintf(
106
                        '<info>Time taken</info>  [s]       <comment>tokenization</comment>/<comment>parsing</comment>/<comment>formatting</comment>: %.4f / %.4f / %.4f',
107
                        $times['tokenization'], $times['parsing'], $times['formatting']
108
                    ));
109
110
                    $output->writeln(sprintf(
111
                        '<info>Performance</info> [chars/s] <comment>tokenization</comment>/<comment>parsing</comment>/<comment>formatting</comment>: %s / %s / %s',
112
                        number_format(strlen($source) / $times['tokenization']),
113
                        number_format(strlen($source) / $times['parsing']),
114
                        number_format(strlen($source) / $times['formatting'])
115
                    ));
116
                }
117
118
                if(in_array('time', $input->getOption('debug'))) {
119
                    $output->writeln(sprintf(
120
                        '<info>Overall:</info> %.4fs, %s chars/s',
121
                        array_sum($times), number_format(strlen($source) / array_sum($times))
122
                    ));
123
                }
124
            } else {
125
                $formatted = KeyLighter::get()->highlight($source, $language, $formatter);
126
            }
127
            
128
            if(!$input->getOption('no-output')) {
129
                $output->writeln($formatted);
130
            }
131
        }
132
    }
133
134
    protected function content($path)
135
    {
136
        if(!($file = @fopen($path, 'r'))) {
137
            return false;
138
        }
139
140
        $content = '';
141
        while(!feof($file)) {
142
            $content .= fgets($file);
143
        }
144
        fclose($file);
145
146
        return $content;
147
    }
148
149
    protected function benchmark(OutputInterface $output, callable $callable, &$time = null) {
1 ignored issue
show
Unused Code introduced by
The parameter $output is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
150
        $start = microtime(true);
151
        $return = $callable();
152
        $time = microtime(true) - $start;
153
154
        return $return;
155
    }
156
157
    public function mergeApplicationDefinition($arguments = true)
158
    {
159
        parent::mergeApplicationDefinition($this->getApplication()->explicit);
1 ignored issue
show
Bug introduced by
The property explicit does not seem to exist in Symfony\Component\Console\Application.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
160
    }
161
}
162