ArtisanTinker::getOptions()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Console\Console\Commands;
6
7
use Illuminate\Console\Command;
8
use Symfony\Component\Console\Input\InputOption;
9
10
class ArtisanTinker extends Command
11
{
12
    /**
13
     * The console command name.
14
     *
15
     * @var string
16
     */
17
    protected $name = 'tinker';
18
19
    /**
20
     * The console command description.
21
     *
22
     * @var string
23
     */
24
    protected $description = 'artisn tinker';
25
26
    /**
27
     * fire.
28
     */
29
    public function handle()
30
    {
31
        $command = $this->option('command');
32
33
        ob_start();
34
        $result = $this->executeCode(
35
            trim(trim($command), ';').';'
36
        );
37
        $output = ob_get_clean();
38
39
        if (empty($output) === false) {
40
            $this->line($output);
41
            $result = null;
42
        }
43
44
        $this->getOutput()->write('=> ');
45
        switch (gettype($result)) {
46
            case 'object':
47
            case 'array':
48
                $this->line(var_export($result, true));
49
                break;
50
            case 'string':
51
                $this->comment($result);
52
                break;
53
            default:
54
                is_numeric($result) === true ? $this->info($result) : $this->line($result);
55
                break;
56
        }
57
    }
58
59
    /**
60
     * executeCode.
61
     *
62
     * @param string $code
63
     *
64
     * @return string
65
     */
66
    protected function executeCode($code): string
67
    {
68
        $result = null;
69
        if (mb_strpos($code, 'echo') === false && mb_strpos($code, 'var_dump') === false) {
70
            $code = 'return '.$code;
71
        }
72
73
        $tmpfname = tempnam(sys_get_temp_dir(), 'artisan-thinker');
74
        $handle = fopen($tmpfname, 'w+');
75
        fwrite($handle, "<?php\n".$code);
76
        fclose($handle);
77
        $result = require $tmpfname;
78
        unlink($tmpfname);
79
80
        return $result;
81
    }
82
83
    /**
84
     * Get the console command options.
85
     *
86
     * @return array
87
     */
88
    protected function getOptions(): array
89
    {
90
        return [
91
            ['command', null, InputOption::VALUE_OPTIONAL],
92
        ];
93
    }
94
}
95