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
|
21 |
|
protected function configure() |
24
|
|
|
{ |
25
|
|
|
$this |
26
|
21 |
|
->setName('php:eval') |
27
|
21 |
|
->setDescription('Run arbitrary PHP code from an argument or file') |
28
|
21 |
|
->addOption('run', 'r', InputOption::VALUE_REQUIRED) |
29
|
21 |
|
->addOption('file', 'f', InputOption::VALUE_REQUIRED) |
30
|
21 |
|
->addOption('format', null, InputOption::VALUE_REQUIRED, '', 'string') |
31
|
21 |
|
->setHelp("In order to display output, ensure the code returns something.\nExample: <info>cachetool php:eval -r 'return gethostname();'</info>"); |
32
|
21 |
|
} |
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': $stringified = sprintf('%s', $result); break; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$output->writeln($stringified); |
|
|
|
|
63
|
|
|
return 0; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
If you define a variable conditionally, it can happen that it is not defined for all execution paths.
Let’s take a look at an example:
In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.
Available Fixes
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: