Shell.php
47.4 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2023 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy;
use Psy\CodeCleaner\NoReturnValue;
use Psy\Exception\BreakException;
use Psy\Exception\ErrorException;
use Psy\Exception\Exception as PsyException;
use Psy\Exception\RuntimeException;
use Psy\Exception\ThrowUpException;
use Psy\ExecutionLoop\ProcessForker;
use Psy\ExecutionLoop\RunkitReloader;
use Psy\Formatter\TraceFormatter;
use Psy\Input\ShellInput;
use Psy\Input\SilentInput;
use Psy\Output\ShellOutput;
use Psy\TabCompletion\Matcher;
use Psy\VarDumper\PresenterAware;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command as BaseCommand;
use Symfony\Component\Console\Exception\ExceptionInterface as SymfonyConsoleException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
/**
* The Psy Shell application.
*
* Usage:
*
* $shell = new Shell;
* $shell->run();
*
* @author Justin Hileman <justin@justinhileman.info>
*/
class Shell extends Application
{
const VERSION = 'v0.12.3';
private $config;
private $cleaner;
private $output;
private $originalVerbosity;
private $readline;
private $inputBuffer;
private $code;
private $codeBuffer;
private $codeBufferOpen;
private $codeStack;
private $stdoutBuffer;
private $context;
private $includes;
private $outputWantsNewline = false;
private $loopListeners;
private $autoCompleter;
private $matchers = [];
private $commandsMatcher;
private $lastExecSuccess = true;
private $nonInteractive = false;
private $errorReporting;
/**
* Create a new Psy Shell.
*
* @param Configuration|null $config (default: null)
*/
public function __construct(?Configuration $config = null)
{
$this->config = $config ?: new Configuration();
$this->cleaner = $this->config->getCodeCleaner();
$this->context = new Context();
$this->includes = [];
$this->readline = $this->config->getReadline();
$this->inputBuffer = [];
$this->codeStack = [];
$this->stdoutBuffer = '';
$this->loopListeners = $this->getDefaultLoopListeners();
parent::__construct('Psy Shell', self::VERSION);
$this->config->setShell($this);
// Register the current shell session's config with \Psy\info
\Psy\info($this->config);
}
/**
* Check whether the first thing in a backtrace is an include call.
*
* This is used by the psysh bin to decide whether to start a shell on boot,
* or to simply autoload the library.
*/
public static function isIncluded(array $trace): bool
{
$isIncluded = isset($trace[0]['function']) &&
\in_array($trace[0]['function'], ['require', 'include', 'require_once', 'include_once']);
// Detect Composer PHP bin proxies.
if ($isIncluded && \array_key_exists('_composer_autoload_path', $GLOBALS) && \preg_match('{[\\\\/]psysh$}', $trace[0]['file'])) {
// If we're in a bin proxy, we'll *always* see one include, but we
// care if we see a second immediately after that.
return isset($trace[1]['function']) &&
\in_array($trace[1]['function'], ['require', 'include', 'require_once', 'include_once']);
}
return $isIncluded;
}
/**
* Check if the currently running PsySH bin is a phar archive.
*/
public static function isPhar(): bool
{
return \class_exists("\Phar") && \Phar::running() !== '' && \strpos(__FILE__, \Phar::running(true)) === 0;
}
/**
* Invoke a Psy Shell from the current context.
*
* @see Psy\debug
* @deprecated will be removed in 1.0. Use \Psy\debug instead
*
* @param array $vars Scope variables from the calling context (default: [])
* @param object|string $bindTo Bound object ($this) or class (self) value for the shell
*
* @return array Scope variables from the debugger session
*/
public static function debug(array $vars = [], $bindTo = null): array
{
@\trigger_error('`Psy\\Shell::debug` is deprecated; call `Psy\\debug` instead.', \E_USER_DEPRECATED);
return \Psy\debug($vars, $bindTo);
}
/**
* Adds a command object.
*
* {@inheritdoc}
*
* @param BaseCommand $command A Symfony Console Command object
*
* @return BaseCommand The registered command
*/
public function add(BaseCommand $command): BaseCommand
{
if ($ret = parent::add($command)) {
if ($ret instanceof ContextAware) {
$ret->setContext($this->context);
}
if ($ret instanceof PresenterAware) {
$ret->setPresenter($this->config->getPresenter());
}
if (isset($this->commandsMatcher)) {
$this->commandsMatcher->setCommands($this->all());
}
}
return $ret;
}
/**
* Gets the default input definition.
*
* @return InputDefinition An InputDefinition instance
*/
protected function getDefaultInputDefinition(): InputDefinition
{
return new InputDefinition([
new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
]);
}
/**
* Gets the default commands that should always be available.
*
* @return array An array of default Command instances
*/
protected function getDefaultCommands(): array
{
$sudo = new Command\SudoCommand();
$sudo->setReadline($this->readline);
$hist = new Command\HistoryCommand();
$hist->setReadline($this->readline);
return [
new Command\HelpCommand(),
new Command\ListCommand(),
new Command\DumpCommand(),
new Command\DocCommand(),
new Command\ShowCommand(),
new Command\WtfCommand(),
new Command\WhereamiCommand(),
new Command\ThrowUpCommand(),
new Command\TimeitCommand(),
new Command\TraceCommand(),
new Command\BufferCommand(),
new Command\ClearCommand(),
new Command\EditCommand($this->config->getRuntimeDir()),
// new Command\PsyVersionCommand(),
$sudo,
$hist,
new Command\ExitCommand(),
];
}
/**
* @return Matcher\AbstractMatcher[]
*/
protected function getDefaultMatchers(): array
{
// Store the Commands Matcher for later. If more commands are added,
// we'll update the Commands Matcher too.
$this->commandsMatcher = new Matcher\CommandsMatcher($this->all());
return [
$this->commandsMatcher,
new Matcher\KeywordsMatcher(),
new Matcher\VariablesMatcher(),
new Matcher\ConstantsMatcher(),
new Matcher\FunctionsMatcher(),
new Matcher\ClassNamesMatcher(),
new Matcher\ClassMethodsMatcher(),
new Matcher\ClassAttributesMatcher(),
new Matcher\ObjectMethodsMatcher(),
new Matcher\ObjectAttributesMatcher(),
new Matcher\ClassMethodDefaultParametersMatcher(),
new Matcher\ObjectMethodDefaultParametersMatcher(),
new Matcher\FunctionDefaultParametersMatcher(),
];
}
/**
* Gets the default command loop listeners.
*
* @return array An array of Execution Loop Listener instances
*/
protected function getDefaultLoopListeners(): array
{
$listeners = [];
if (ProcessForker::isSupported() && $this->config->usePcntl()) {
$listeners[] = new ProcessForker();
}
if (RunkitReloader::isSupported()) {
$listeners[] = new RunkitReloader();
}
return $listeners;
}
/**
* Add tab completion matchers.
*
* @param array $matchers
*/
public function addMatchers(array $matchers)
{
$this->matchers = \array_merge($this->matchers, $matchers);
if (isset($this->autoCompleter)) {
$this->addMatchersToAutoCompleter($matchers);
}
}
/**
* @deprecated Call `addMatchers` instead
*
* @param array $matchers
*/
public function addTabCompletionMatchers(array $matchers)
{
@\trigger_error('`addTabCompletionMatchers` is deprecated; call `addMatchers` instead.', \E_USER_DEPRECATED);
$this->addMatchers($matchers);
}
/**
* Set the Shell output.
*
* @param OutputInterface $output
*/
public function setOutput(OutputInterface $output)
{
$this->output = $output;
$this->originalVerbosity = $output->getVerbosity();
}
/**
* Runs PsySH.
*
* @param InputInterface|null $input An Input instance
* @param OutputInterface|null $output An Output instance
*
* @return int 0 if everything went fine, or an error code
*/
public function run(?InputInterface $input = null, ?OutputInterface $output = null): int
{
// We'll just ignore the input passed in, and set up our own!
$input = new ArrayInput([]);
if ($output === null) {
$output = $this->config->getOutput();
}
$this->setAutoExit(false);
$this->setCatchExceptions(false);
try {
return parent::run($input, $output);
} catch (\Throwable $e) {
$this->writeException($e);
}
return 1;
}
/**
* Runs PsySH.
*
* @throws \Throwable if thrown via the `throw-up` command
*
* @param InputInterface $input An Input instance
* @param OutputInterface $output An Output instance
*
* @return int 0 if everything went fine, or an error code
*/
public function doRun(InputInterface $input, OutputInterface $output): int
{
$this->setOutput($output);
$this->resetCodeBuffer();
if ($input->isInteractive()) {
// @todo should it be possible to have raw output in an interactive run?
return $this->doInteractiveRun();
} else {
return $this->doNonInteractiveRun($this->config->rawOutput());
}
}
/**
* Run PsySH in interactive mode.
*
* Initializes tab completion and readline history, then spins up the
* execution loop.
*
* @throws \Throwable if thrown via the `throw-up` command
*
* @return int 0 if everything went fine, or an error code
*/
private function doInteractiveRun(): int
{
$this->initializeTabCompletion();
$this->readline->readHistory();
$this->output->writeln($this->getHeader());
$this->writeVersionInfo();
$this->writeStartupMessage();
try {
$this->beforeRun();
$this->loadIncludes();
$loop = new ExecutionLoopClosure($this);
$loop->execute();
$this->afterRun();
} catch (ThrowUpException $e) {
throw $e->getPrevious();
} catch (BreakException $e) {
// The ProcessForker throws a BreakException to finish the main thread.
}
return 0;
}
/**
* Run PsySH in non-interactive mode.
*
* Note that this isn't very useful unless you supply "include" arguments at
* the command line, or code via stdin.
*
* @param bool $rawOutput
*
* @return int 0 if everything went fine, or an error code
*/
private function doNonInteractiveRun(bool $rawOutput): int
{
$this->nonInteractive = true;
// If raw output is enabled (or output is piped) we don't want startup messages.
if (!$rawOutput && !$this->config->outputIsPiped()) {
$this->output->writeln($this->getHeader());
$this->writeVersionInfo();
$this->writeStartupMessage();
}
$this->beforeRun();
$this->loadIncludes();
// For non-interactive execution, read only from the input buffer or from piped input.
// Otherwise it'll try to readline and hang, waiting for user input with no indication of
// what's holding things up.
if (!empty($this->inputBuffer) || $this->config->inputIsPiped()) {
$this->getInput(false);
}
if ($this->hasCode()) {
$ret = $this->execute($this->flushCode());
$this->writeReturnValue($ret, $rawOutput);
}
$this->afterRun();
$this->nonInteractive = false;
return 0;
}
/**
* Configures the input and output instances based on the user arguments and options.
*/
protected function configureIO(InputInterface $input, OutputInterface $output): void
{
// @todo overrides via environment variables (or should these happen in config? ... probably config)
$input->setInteractive($this->config->getInputInteractive());
if ($this->config->getOutputDecorated() !== null) {
$output->setDecorated($this->config->getOutputDecorated());
}
$output->setVerbosity($this->config->getOutputVerbosity());
}
/**
* Load user-defined includes.
*/
private function loadIncludes()
{
// Load user-defined includes
$load = function (self $__psysh__) {
\set_error_handler([$__psysh__, 'handleError']);
foreach ($__psysh__->getIncludes() as $__psysh_include__) {
try {
include_once $__psysh_include__;
} catch (\Exception $_e) {
$__psysh__->writeException($_e);
}
}
\restore_error_handler();
unset($__psysh_include__);
// Override any new local variables with pre-defined scope variables
\extract($__psysh__->getScopeVariables(false));
// ... then add the whole mess of variables back.
$__psysh__->setScopeVariables(\get_defined_vars());
};
$load($this);
}
/**
* Read user input.
*
* This will continue fetching user input until the code buffer contains
* valid code.
*
* @throws BreakException if user hits Ctrl+D
*
* @param bool $interactive
*/
public function getInput(bool $interactive = true)
{
$this->codeBufferOpen = false;
do {
// reset output verbosity (in case it was altered by a subcommand)
$this->output->setVerbosity($this->originalVerbosity);
$input = $this->readline();
/*
* Handle Ctrl+D. It behaves differently in different cases:
*
* 1) In an expression, like a function or "if" block, clear the input buffer
* 2) At top-level session, behave like the exit command
* 3) When non-interactive, return, because that's the end of stdin
*/
if ($input === false) {
if (!$interactive) {
return;
}
$this->output->writeln('');
if ($this->hasCode()) {
$this->resetCodeBuffer();
} else {
throw new BreakException('Ctrl+D');
}
}
// handle empty input
if (\trim($input) === '' && !$this->codeBufferOpen) {
continue;
}
$input = $this->onInput($input);
// If the input isn't in an open string or comment, check for commands to run.
if ($this->hasCommand($input) && !$this->inputInOpenStringOrComment($input)) {
$this->addHistory($input);
$this->runCommand($input);
continue;
}
$this->addCode($input);
} while (!$interactive || !$this->hasValidCode());
}
/**
* Check whether the code buffer (plus current input) is in an open string or comment.
*
* @param string $input current line of input
*
* @return bool true if the input is in an open string or comment
*/
private function inputInOpenStringOrComment(string $input): bool
{
if (!$this->hasCode()) {
return false;
}
$code = $this->codeBuffer;
$code[] = $input;
$tokens = @\token_get_all('<?php '.\implode("\n", $code));
$last = \array_pop($tokens);
return $last === '"' || $last === '`' ||
(\is_array($last) && \in_array($last[0], [\T_ENCAPSED_AND_WHITESPACE, \T_START_HEREDOC, \T_COMMENT]));
}
/**
* Run execution loop listeners before the shell session.
*/
protected function beforeRun()
{
foreach ($this->loopListeners as $listener) {
$listener->beforeRun($this);
}
}
/**
* Run execution loop listeners at the start of each loop.
*/
public function beforeLoop()
{
foreach ($this->loopListeners as $listener) {
$listener->beforeLoop($this);
}
}
/**
* Run execution loop listeners on user input.
*
* @param string $input
*/
public function onInput(string $input): string
{
foreach ($this->loopListeners as $listeners) {
if (($return = $listeners->onInput($this, $input)) !== null) {
$input = $return;
}
}
return $input;
}
/**
* Run execution loop listeners on code to be executed.
*
* @param string $code
*/
public function onExecute(string $code): string
{
$this->errorReporting = \error_reporting();
foreach ($this->loopListeners as $listener) {
if (($return = $listener->onExecute($this, $code)) !== null) {
$code = $return;
}
}
$output = $this->output;
if ($output instanceof ConsoleOutput) {
$output = $output->getErrorOutput();
}
$output->writeln(\sprintf('<whisper>%s</whisper>', OutputFormatter::escape($code)), ConsoleOutput::VERBOSITY_DEBUG);
return $code;
}
/**
* Run execution loop listeners after each loop.
*/
public function afterLoop()
{
foreach ($this->loopListeners as $listener) {
$listener->afterLoop($this);
}
}
/**
* Run execution loop listers after the shell session.
*/
protected function afterRun()
{
foreach ($this->loopListeners as $listener) {
$listener->afterRun($this);
}
}
/**
* Set the variables currently in scope.
*
* @param array $vars
*/
public function setScopeVariables(array $vars)
{
$this->context->setAll($vars);
}
/**
* Return the set of variables currently in scope.
*
* @param bool $includeBoundObject Pass false to exclude 'this'. If you're
* passing the scope variables to `extract`
* you _must_ exclude 'this'
*
* @return array Associative array of scope variables
*/
public function getScopeVariables(bool $includeBoundObject = true): array
{
$vars = $this->context->getAll();
if (!$includeBoundObject) {
unset($vars['this']);
}
return $vars;
}
/**
* Return the set of magic variables currently in scope.
*
* @param bool $includeBoundObject Pass false to exclude 'this'. If you're
* passing the scope variables to `extract`
* you _must_ exclude 'this'
*
* @return array Associative array of magic scope variables
*/
public function getSpecialScopeVariables(bool $includeBoundObject = true): array
{
$vars = $this->context->getSpecialVariables();
if (!$includeBoundObject) {
unset($vars['this']);
}
return $vars;
}
/**
* Return the set of variables currently in scope which differ from the
* values passed as $currentVars.
*
* This is used inside the Execution Loop Closure to pick up scope variable
* changes made by commands while the loop is running.
*
* @param array $currentVars
*
* @return array Associative array of scope variables which differ from $currentVars
*/
public function getScopeVariablesDiff(array $currentVars): array
{
$newVars = [];
foreach ($this->getScopeVariables(false) as $key => $value) {
if (!\array_key_exists($key, $currentVars) || $currentVars[$key] !== $value) {
$newVars[$key] = $value;
}
}
return $newVars;
}
/**
* Get the set of unused command-scope variable names.
*
* @return array Array of unused variable names
*/
public function getUnusedCommandScopeVariableNames(): array
{
return $this->context->getUnusedCommandScopeVariableNames();
}
/**
* Get the set of variable names currently in scope.
*
* @return array Array of variable names
*/
public function getScopeVariableNames(): array
{
return \array_keys($this->context->getAll());
}
/**
* Get a scope variable value by name.
*
* @param string $name
*
* @return mixed
*/
public function getScopeVariable(string $name)
{
return $this->context->get($name);
}
/**
* Set the bound object ($this variable) for the interactive shell.
*
* @param object|null $boundObject
*/
public function setBoundObject($boundObject)
{
$this->context->setBoundObject($boundObject);
}
/**
* Get the bound object ($this variable) for the interactive shell.
*
* @return object|null
*/
public function getBoundObject()
{
return $this->context->getBoundObject();
}
/**
* Set the bound class (self) for the interactive shell.
*
* @param string|null $boundClass
*/
public function setBoundClass($boundClass)
{
$this->context->setBoundClass($boundClass);
}
/**
* Get the bound class (self) for the interactive shell.
*
* @return string|null
*/
public function getBoundClass()
{
return $this->context->getBoundClass();
}
/**
* Add includes, to be parsed and executed before running the interactive shell.
*
* @param array $includes
*/
public function setIncludes(array $includes = [])
{
$this->includes = $includes;
}
/**
* Get PHP files to be parsed and executed before running the interactive shell.
*
* @return string[]
*/
public function getIncludes(): array
{
return \array_merge($this->config->getDefaultIncludes(), $this->includes);
}
/**
* Check whether this shell's code buffer contains code.
*
* @return bool True if the code buffer contains code
*/
public function hasCode(): bool
{
return !empty($this->codeBuffer);
}
/**
* Check whether the code in this shell's code buffer is valid.
*
* If the code is valid, the code buffer should be flushed and evaluated.
*
* @return bool True if the code buffer content is valid
*/
protected function hasValidCode(): bool
{
return !$this->codeBufferOpen && $this->code !== false;
}
/**
* Add code to the code buffer.
*
* @param string $code
* @param bool $silent
*/
public function addCode(string $code, bool $silent = false)
{
try {
// Code lines ending in \ keep the buffer open
if (\substr(\rtrim($code), -1) === '\\') {
$this->codeBufferOpen = true;
$code = \substr(\rtrim($code), 0, -1);
} else {
$this->codeBufferOpen = false;
}
$this->codeBuffer[] = $silent ? new SilentInput($code) : $code;
$this->code = $this->cleaner->clean($this->codeBuffer, $this->config->requireSemicolons());
} catch (\Throwable $e) {
// Add failed code blocks to the readline history.
$this->addCodeBufferToHistory();
throw $e;
}
}
/**
* Set the code buffer.
*
* This is mostly used by `Shell::execute`. Any existing code in the input
* buffer is pushed onto a stack and will come back after this new code is
* executed.
*
* @throws \InvalidArgumentException if $code isn't a complete statement
*
* @param string $code
* @param bool $silent
*/
private function setCode(string $code, bool $silent = false)
{
if ($this->hasCode()) {
$this->codeStack[] = [$this->codeBuffer, $this->codeBufferOpen, $this->code];
}
$this->resetCodeBuffer();
try {
$this->addCode($code, $silent);
} catch (\Throwable $e) {
$this->popCodeStack();
throw $e;
}
if (!$this->hasValidCode()) {
$this->popCodeStack();
throw new \InvalidArgumentException('Unexpected end of input');
}
}
/**
* Get the current code buffer.
*
* This is useful for commands which manipulate the buffer.
*
* @return string[]
*/
public function getCodeBuffer(): array
{
return $this->codeBuffer;
}
/**
* Run a Psy Shell command given the user input.
*
* @throws \InvalidArgumentException if the input is not a valid command
*
* @param string $input User input string
*
* @return mixed Who knows?
*/
protected function runCommand(string $input)
{
$command = $this->getCommand($input);
if (empty($command)) {
throw new \InvalidArgumentException('Command not found: '.$input);
}
$input = new ShellInput(\str_replace('\\', '\\\\', \rtrim($input, " \t\n\r\0\x0B;")));
if ($input->hasParameterOption(['--help', '-h'])) {
$helpCommand = $this->get('help');
if (!$helpCommand instanceof Command\HelpCommand) {
throw new RuntimeException('Invalid help command instance');
}
$helpCommand->setCommand($command);
return $helpCommand->run(new StringInput(''), $this->output);
}
return $command->run($input, $this->output);
}
/**
* Reset the current code buffer.
*
* This should be run after evaluating user input, catching exceptions, or
* on demand by commands such as BufferCommand.
*/
public function resetCodeBuffer()
{
$this->codeBuffer = [];
$this->code = false;
}
/**
* Inject input into the input buffer.
*
* This is useful for commands which want to replay history.
*
* @param string|array $input
* @param bool $silent
*/
public function addInput($input, bool $silent = false)
{
foreach ((array) $input as $line) {
$this->inputBuffer[] = $silent ? new SilentInput($line) : $line;
}
}
/**
* Flush the current (valid) code buffer.
*
* If the code buffer is valid, resets the code buffer and returns the
* current code.
*
* @return string|null PHP code buffer contents
*/
public function flushCode()
{
if ($this->hasValidCode()) {
$this->addCodeBufferToHistory();
$code = $this->code;
$this->popCodeStack();
return $code;
}
}
/**
* Reset the code buffer and restore any code pushed during `execute` calls.
*/
private function popCodeStack()
{
$this->resetCodeBuffer();
if (empty($this->codeStack)) {
return;
}
list($codeBuffer, $codeBufferOpen, $code) = \array_pop($this->codeStack);
$this->codeBuffer = $codeBuffer;
$this->codeBufferOpen = $codeBufferOpen;
$this->code = $code;
}
/**
* (Possibly) add a line to the readline history.
*
* Like Bash, if the line starts with a space character, it will be omitted
* from history. Note that an entire block multi-line code input will be
* omitted iff the first line begins with a space.
*
* Additionally, if a line is "silent", i.e. it was initially added with the
* silent flag, it will also be omitted.
*
* @param string|SilentInput $line
*/
private function addHistory($line)
{
if ($line instanceof SilentInput) {
return;
}
// Skip empty lines and lines starting with a space
if (\trim($line) !== '' && \substr($line, 0, 1) !== ' ') {
$this->readline->addHistory($line);
}
}
/**
* Filter silent input from code buffer, write the rest to readline history.
*/
private function addCodeBufferToHistory()
{
$codeBuffer = \array_filter($this->codeBuffer, function ($line) {
return !$line instanceof SilentInput;
});
$this->addHistory(\implode("\n", $codeBuffer));
}
/**
* Get the current evaluation scope namespace.
*
* @see CodeCleaner::getNamespace
*
* @return string|null Current code namespace
*/
public function getNamespace()
{
if ($namespace = $this->cleaner->getNamespace()) {
return \implode('\\', $namespace);
}
}
/**
* Write a string to stdout.
*
* This is used by the shell loop for rendering output from evaluated code.
*
* @param string $out
* @param int $phase Output buffering phase
*/
public function writeStdout(string $out, int $phase = \PHP_OUTPUT_HANDLER_END)
{
if ($phase & \PHP_OUTPUT_HANDLER_START) {
if ($this->output instanceof ShellOutput) {
$this->output->startPaging();
}
}
$isCleaning = $phase & \PHP_OUTPUT_HANDLER_CLEAN;
// Incremental flush
if ($out !== '' && !$isCleaning) {
$this->output->write($out, false, OutputInterface::OUTPUT_RAW);
$this->outputWantsNewline = (\substr($out, -1) !== "\n");
$this->stdoutBuffer .= $out;
}
// Output buffering is done!
if ($phase & \PHP_OUTPUT_HANDLER_END) {
// Write an extra newline if stdout didn't end with one
if ($this->outputWantsNewline) {
if (!$this->config->rawOutput() && !$this->config->outputIsPiped()) {
$this->output->writeln(\sprintf('<whisper>%s</whisper>', $this->config->useUnicode() ? '⏎' : '\\n'));
} else {
$this->output->writeln('');
}
$this->outputWantsNewline = false;
}
// Save the stdout buffer as $__out
if ($this->stdoutBuffer !== '') {
$this->context->setLastStdout($this->stdoutBuffer);
$this->stdoutBuffer = '';
}
if ($this->output instanceof ShellOutput) {
$this->output->stopPaging();
}
}
}
/**
* Write a return value to stdout.
*
* The return value is formatted or pretty-printed, and rendered in a
* visibly distinct manner (in this case, as cyan).
*
* @see self::presentValue
*
* @param mixed $ret
* @param bool $rawOutput Write raw var_export-style values
*/
public function writeReturnValue($ret, bool $rawOutput = false)
{
$this->lastExecSuccess = true;
if ($ret instanceof NoReturnValue) {
return;
}
$this->context->setReturnValue($ret);
if ($rawOutput) {
$formatted = \var_export($ret, true);
} else {
$prompt = $this->config->theme()->returnValue();
$indent = \str_repeat(' ', \strlen($prompt));
$formatted = $this->presentValue($ret);
$formattedRetValue = \sprintf('<whisper>%s</whisper>', $prompt);
$formatted = $formattedRetValue.\str_replace(\PHP_EOL, \PHP_EOL.$indent, $formatted);
}
if ($this->output instanceof ShellOutput) {
$this->output->page($formatted.\PHP_EOL);
} else {
$this->output->writeln($formatted);
}
}
/**
* Renders a caught Exception or Error.
*
* Exceptions are formatted according to severity. ErrorExceptions which were
* warnings or Strict errors aren't rendered as harshly as real errors.
*
* Stores $e as the last Exception in the Shell Context.
*
* @param \Throwable $e An exception or error instance
*/
public function writeException(\Throwable $e)
{
// No need to write the break exception during a non-interactive run.
if ($e instanceof BreakException && $this->nonInteractive) {
$this->resetCodeBuffer();
return;
}
// Break exceptions don't count :)
if (!$e instanceof BreakException) {
$this->lastExecSuccess = false;
$this->context->setLastException($e);
}
$output = $this->output;
if ($output instanceof ConsoleOutput) {
$output = $output->getErrorOutput();
}
if (!$this->config->theme()->compact()) {
$output->writeln('');
}
$output->writeln($this->formatException($e));
if (!$this->config->theme()->compact()) {
$output->writeln('');
}
// Include an exception trace (as long as this isn't a BreakException).
if (!$e instanceof BreakException && $output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$trace = TraceFormatter::formatTrace($e);
if (\count($trace) !== 0) {
$output->writeln('--');
$output->write($trace, true);
$output->writeln('');
}
}
$this->resetCodeBuffer();
}
/**
* Check whether the last exec was successful.
*
* Returns true if a return value was logged rather than an exception.
*/
public function getLastExecSuccess(): bool
{
return $this->lastExecSuccess;
}
/**
* Helper for formatting an exception or error for writeException().
*
* @todo extract this to somewhere it makes more sense
*
* @param \Throwable $e
*/
public function formatException(\Throwable $e): string
{
$indent = $this->config->theme()->compact() ? '' : ' ';
if ($e instanceof BreakException) {
return \sprintf('%s<info> INFO </info> %s.', $indent, \rtrim($e->getRawMessage(), '.'));
} elseif ($e instanceof PsyException) {
$message = $e->getLine() > 1
? \sprintf('%s in %s on line %d', $e->getRawMessage(), $e->getFile(), $e->getLine())
: \sprintf('%s in %s', $e->getRawMessage(), $e->getFile());
$messageLabel = \strtoupper($this->getMessageLabel($e));
} else {
$message = $e->getMessage();
$messageLabel = $this->getMessageLabel($e);
}
$message = \preg_replace(
"#(\\w:)?([\\\\/]\\w+)*[\\\\/]src[\\\\/]Execution(?:Loop)?Closure.php\(\d+\) : eval\(\)'d code#",
"eval()'d code",
$message
);
$message = \str_replace(" in eval()'d code", '', $message);
$message = \trim($message);
// Ensures the given string ends with punctuation...
if (!empty($message) && !\in_array(\substr($message, -1), ['.', '?', '!', ':'])) {
$message = "$message.";
}
// Ensures the given message only contains relative paths...
$message = \str_replace(\getcwd().\DIRECTORY_SEPARATOR, '', $message);
$severity = ($e instanceof \ErrorException) ? $this->getSeverity($e) : 'error';
return \sprintf('%s<%s> %s </%s> %s', $indent, $severity, $messageLabel, $severity, OutputFormatter::escape($message));
}
/**
* Helper for getting an output style for the given ErrorException's level.
*
* @param \ErrorException $e
*/
protected function getSeverity(\ErrorException $e): string
{
$severity = $e->getSeverity();
if ($severity & \error_reporting()) {
switch ($severity) {
case \E_WARNING:
case \E_NOTICE:
case \E_CORE_WARNING:
case \E_COMPILE_WARNING:
case \E_USER_WARNING:
case \E_USER_NOTICE:
case \E_USER_DEPRECATED:
case \E_DEPRECATED:
case \E_STRICT:
return 'warning';
default:
return 'error';
}
} else {
// Since this is below the user's reporting threshold, it's always going to be a warning.
return 'warning';
}
}
/**
* Helper for getting an output style for the given ErrorException's level.
*
* @param \Throwable $e
*/
protected function getMessageLabel(\Throwable $e): string
{
if ($e instanceof \ErrorException) {
$severity = $e->getSeverity();
if ($severity & \error_reporting()) {
switch ($severity) {
case \E_WARNING:
return 'Warning';
case \E_NOTICE:
return 'Notice';
case \E_CORE_WARNING:
return 'Core Warning';
case \E_COMPILE_WARNING:
return 'Compile Warning';
case \E_USER_WARNING:
return 'User Warning';
case \E_USER_NOTICE:
return 'User Notice';
case \E_USER_DEPRECATED:
return 'User Deprecated';
case \E_DEPRECATED:
return 'Deprecated';
case \E_STRICT:
return 'Strict';
}
}
}
if ($e instanceof PsyException || $e instanceof SymfonyConsoleException) {
$exceptionShortName = (new \ReflectionClass($e))->getShortName();
$typeParts = \preg_split('/(?=[A-Z])/', $exceptionShortName);
switch ($exceptionShortName) {
case 'RuntimeException':
case 'LogicException':
// These ones look weird without 'Exception'
break;
default:
if (\end($typeParts) === 'Exception') {
\array_pop($typeParts);
}
break;
}
return \trim(\strtoupper(\implode(' ', $typeParts)));
}
return \get_class($e);
}
/**
* Execute code in the shell execution context.
*
* @param string $code
* @param bool $throwExceptions
*
* @return mixed
*/
public function execute(string $code, bool $throwExceptions = false)
{
$this->setCode($code, true);
$closure = new ExecutionClosure($this);
if ($throwExceptions) {
return $closure->execute();
}
try {
return $closure->execute();
} catch (\Throwable $_e) {
$this->writeException($_e);
}
}
/**
* Helper for throwing an ErrorException.
*
* This allows us to:
*
* set_error_handler([$psysh, 'handleError']);
*
* Unlike ErrorException::throwException, this error handler respects error
* levels; i.e. it logs warnings and notices, but doesn't throw exceptions.
* This should probably only be used in the inner execution loop of the
* shell, as most of the time a thrown exception is much more useful.
*
* If the error type matches the `errorLoggingLevel` config, it will be
* logged as well, regardless of the `error_reporting` level.
*
* @see \Psy\Exception\ErrorException::throwException
* @see \Psy\Shell::writeException
*
* @throws \Psy\Exception\ErrorException depending on the error level
*
* @param int $errno Error type
* @param string $errstr Message
* @param string $errfile Filename
* @param int $errline Line number
*/
public function handleError($errno, $errstr, $errfile, $errline)
{
// This is an error worth throwing.
//
// n.b. Technically we can't handle all of these in userland code, but
// we'll list 'em all for good measure
if ($errno & (\E_ERROR | \E_PARSE | \E_CORE_ERROR | \E_COMPILE_ERROR | \E_USER_ERROR | \E_RECOVERABLE_ERROR)) {
ErrorException::throwException($errno, $errstr, $errfile, $errline);
}
// When errors are suppressed, the error_reporting value will differ
// from when we started executing. In that case, we won't log errors.
$errorsSuppressed = $this->errorReporting !== null && $this->errorReporting !== \error_reporting();
// Otherwise log it and continue.
if ($errno & \error_reporting() || (!$errorsSuppressed && ($errno & $this->config->errorLoggingLevel()))) {
$this->writeException(new ErrorException($errstr, 0, $errno, $errfile, $errline));
}
}
/**
* Format a value for display.
*
* @see Presenter::present
*
* @param mixed $val
*
* @return string Formatted value
*/
protected function presentValue($val): string
{
return $this->config->getPresenter()->present($val);
}
/**
* Get a command (if one exists) for the current input string.
*
* @param string $input
*
* @return BaseCommand|null
*/
protected function getCommand(string $input)
{
$input = new StringInput($input);
if ($name = $input->getFirstArgument()) {
return $this->get($name);
}
}
/**
* Check whether a command is set for the current input string.
*
* @param string $input
*
* @return bool True if the shell has a command for the given input
*/
protected function hasCommand(string $input): bool
{
if (\preg_match('/([^\s]+?)(?:\s|$)/A', \ltrim($input), $match)) {
return $this->has($match[1]);
}
return false;
}
/**
* Get the current input prompt.
*
* @return string|null
*/
protected function getPrompt()
{
if ($this->output->isQuiet()) {
return null;
}
$theme = $this->config->theme();
if ($this->hasCode()) {
return $theme->bufferPrompt();
}
return $theme->prompt();
}
/**
* Read a line of user input.
*
* This will return a line from the input buffer (if any exist). Otherwise,
* it will ask the user for input.
*
* If readline is enabled, this delegates to readline. Otherwise, it's an
* ugly `fgets` call.
*
* @param bool $interactive
*
* @return string|false One line of user input
*/
protected function readline(bool $interactive = true)
{
$prompt = $this->config->theme()->replayPrompt();
if (!empty($this->inputBuffer)) {
$line = \array_shift($this->inputBuffer);
if (!$line instanceof SilentInput) {
$this->output->writeln(\sprintf('<whisper>%s</whisper><aside>%s</aside>', $prompt, OutputFormatter::escape($line)));
}
return $line;
}
$bracketedPaste = $interactive && $this->config->useBracketedPaste();
if ($bracketedPaste) {
\printf("\e[?2004h"); // Enable bracketed paste
}
$line = $this->readline->readline($this->getPrompt());
if ($bracketedPaste) {
\printf("\e[?2004l"); // ... and disable it again
}
return $line;
}
/**
* Get the shell output header.
*/
protected function getHeader(): string
{
return \sprintf('<whisper>%s by Justin Hileman</whisper>', self::getVersionHeader($this->config->useUnicode()));
}
/**
* Get the current version of Psy Shell.
*
* @deprecated call self::getVersionHeader instead
*/
public function getVersion(): string
{
@\trigger_error('`getVersion` is deprecated; call `self::getVersionHeader` instead.', \E_USER_DEPRECATED);
return self::getVersionHeader($this->config->useUnicode());
}
/**
* Get a pretty header including the current version of Psy Shell.
*
* @param bool $useUnicode
*/
public static function getVersionHeader(bool $useUnicode = false): string
{
$separator = $useUnicode ? '—' : '-';
return \sprintf('Psy Shell %s (PHP %s %s %s)', self::VERSION, \PHP_VERSION, $separator, \PHP_SAPI);
}
/**
* Get a PHP manual database instance.
*
* @return \PDO|null
*/
public function getManualDb()
{
return $this->config->getManualDb();
}
/**
* Initialize tab completion matchers.
*
* If tab completion is enabled this adds tab completion matchers to the
* auto completer and sets context if needed.
*/
protected function initializeTabCompletion()
{
if (!$this->config->useTabCompletion()) {
return;
}
$this->autoCompleter = $this->config->getAutoCompleter();
// auto completer needs shell to be linked to configuration because of
// the context aware matchers
$this->addMatchersToAutoCompleter($this->getDefaultMatchers());
$this->addMatchersToAutoCompleter($this->matchers);
$this->autoCompleter->activate();
}
/**
* Add matchers to the auto completer, setting context if needed.
*
* @param array $matchers
*/
private function addMatchersToAutoCompleter(array $matchers)
{
foreach ($matchers as $matcher) {
if ($matcher instanceof ContextAware) {
$matcher->setContext($this->context);
}
$this->autoCompleter->addMatcher($matcher);
}
}
/**
* @todo Implement prompt to start update
*
* @return void|string
*/
protected function writeVersionInfo()
{
if (\PHP_SAPI !== 'cli') {
return;
}
try {
$client = $this->config->getChecker();
if (!$client->isLatest()) {
$this->output->writeln(\sprintf('<whisper>New version is available at psysh.org/psysh (current: %s, latest: %s)</whisper>', self::VERSION, $client->getLatest()));
}
} catch (\InvalidArgumentException $e) {
$this->output->writeln($e->getMessage());
}
}
/**
* Write a startup message if set.
*/
protected function writeStartupMessage()
{
$message = $this->config->getStartupMessage();
if ($message !== null && $message !== '') {
$this->output->writeln($message);
}
}
}