/
Tinker.php
76 lines (56 loc) · 1.91 KB
/
Tinker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace Spatie\WebTinker;
use Psy\Shell;
use Psy\Configuration;
use Psy\ExecutionLoopClosure;
use Illuminate\Support\Collection;
use Illuminate\Foundation\Application;
use Illuminate\Database\Eloquent\Model;
use Laravel\Tinker\ClassAliasAutoloader;
use Symfony\Component\Console\Output\BufferedOutput;
class Tinker
{
/** @var \Symfony\Component\Console\Output\BufferedOutput */
protected $output;
/** @var \Psy\Shell */
protected $shell;
public static function execute(string $phpCode): string
{
return(new static())->run($phpCode);
}
public function __construct()
{
$this->output = new BufferedOutput();
$this->shell = $this->createShell($this->output);
}
public function run(string $phpCode): string
{
$this->shell->addInput($phpCode);
$closure = new ExecutionLoopClosure($this->shell);
$closure->execute();
return $this->cleanOutput($this->output->fetch());
}
protected function createShell(BufferedOutput $output): Shell
{
$config = new Configuration([
'updateCheck' => 'never',
]);
$config->getPresenter()->addCasters([
Collection::class => 'Laravel\Tinker\TinkerCaster::castCollection',
Model::class => 'Laravel\Tinker\TinkerCaster::castModel',
Application::class => 'Laravel\Tinker\TinkerCaster::castApplication',
]);
$shell = new Shell($config);
$shell->setOutput($output);
$composerClassMap = base_path('vendor/composer/autoload_classmap.php');
if (file_exists($composerClassMap)) {
ClassAliasAutoloader::register($shell, $composerClassMap);
}
return $shell;
}
protected function cleanOutput(string $output): string
{
$output = preg_replace('/<aside>(.*)?<\/aside>(.*)Exit: Ctrl\+D/ms', '$2', $output);
return trim($output);
}
}