PhpEvalCommand   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 30.76%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
dl 0
loc 48
ccs 8
cts 26
cp 0.3076
rs 10
c 1
b 0
f 0
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
B execute() 0 29 7
A configure() 0 9 1
1
<?php
2
3
/*
4
 * This file is part of CacheTool.
5
 *
6
 * (c) Samuel Gordalina <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CacheTool\Command;
13
14
use Symfony\Component\Console\Input\InputInterface;
15
use Symfony\Component\Console\Input\InputOption;
16
use Symfony\Component\Console\Output\OutputInterface;
17
18
class PhpEvalCommand extends AbstractCommand
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23 25
    protected function configure()
24
    {
25
        $this
26 25
            ->setName('php:eval')
27 25
            ->setDescription('Run arbitrary PHP code from an argument or file')
28 25
            ->addOption('run', 'r', InputOption::VALUE_REQUIRED)
29 25
            ->addOption('file', 'f', InputOption::VALUE_REQUIRED)
30 25
            ->addOption('format', null, InputOption::VALUE_REQUIRED, '', 'string')
31 25
            ->setHelp("In order to display output, ensure the code returns something.\nExample: <info>cachetool php:eval -r 'return gethostname();'</info>");
32 25
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    protected function execute(InputInterface $input, OutputInterface $output): int
38
    {
39
        if ($input->getOption('run')) {
40
            $code = $input->getOption('run');
41
        } else if ($input->getOption('file')) {
42
            $path = $input->getOption('file');
43
44
            if (!is_file($path)) {
45
              throw new \RuntimeException("Could not read file: {$path}");
46
            }
47
48
            $code = file_get_contents($path);
49
            $code = str_replace('<?php','',$code);
50
        } else {
51
          throw new \RuntimeException("Need to specify a --run or a --file input option");
52
        }
53
54
        $result = $this->getCacheTool()->_eval($code);
55
56
        switch ($input->getOption('format')) {
57
          case 'var_export': $stringified = var_export($result, true); break;
58
          case 'json': $stringified = json_encode($result); break;
59
          case 'string':
60
          default:
61
            $stringified = sprintf('%s', $result); break;
62
        }
63
64
        $output->writeln($stringified);
65
        return 0;
66
    }
67
}
68