-
Notifications
You must be signed in to change notification settings - Fork 4
/
Sage.php
1090 lines (948 loc) · 43.1 KB
/
Sage.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
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
<?php
/*
* Sage is a zero-setup PHP debugging assistant. It provides insightful data about variables and program flow.
*
* https://github.com/php-sage/sage
*
* The MIT License (MIT)
*
* Copyright (c) 2013 Rokas Sleinius ([email protected]) and contributors:
* (https://github.com/php-sage/sage/contributors)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
if (defined('SAGE_DIR')) {
return;
}
define('SAGE_DIR', dirname(__FILE__) . '/');
require SAGE_DIR . 'inc/SageVariableData.php';
require SAGE_DIR . 'inc/SageTraceStep.php';
require SAGE_DIR . 'inc/SageParser.php';
require SAGE_DIR . 'inc/SageHelper.php';
require SAGE_DIR . 'inc/shorthands.inc.php';
require SAGE_DIR . 'decorators/SageDecoratorsInterface.php';
require SAGE_DIR . 'decorators/SageDecoratorsRich.php';
require SAGE_DIR . 'decorators/SageDecoratorsPlain.php';
require SAGE_DIR . 'parsers/SageParserInterface.php';
class Sage
{
private static $_initialized = false;
private static $_enabledMode = true;
private static $_openedOutput;
/*
* ██████╗ ██████╗ ███╗ ██╗███████╗██╗ ██████╗ ██╗ ██╗██████╗ █████╗ ████████╗██╗ ██████╗ ███╗ ██╗
* ██╔════╝██╔═══██╗████╗ ██║██╔════╝██║██╔════╝ ██║ ██║██╔══██╗██╔══██╗╚══██╔══╝██║██╔═══██╗████╗ ██║
* ██║ ██║ ██║██╔██╗ ██║█████╗ ██║██║ ███╗██║ ██║██████╔╝███████║ ██║ ██║██║ ██║██╔██╗ ██║
* ██║ ██║ ██║██║╚██╗██║██╔══╝ ██║██║ ██║██║ ██║██╔══██╗██╔══██║ ██║ ██║██║ ██║██║╚██╗██║
* ╚██████╗╚██████╔╝██║ ╚████║██║ ██║╚██████╔╝╚██████╔╝██║ ██║██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║
* ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
*
* ASCII ART: patorjk.com/software/taag/#p=display&h=1&v=2&c=c&f=ANSI Shadow&t=
*/
/**
* @var string makes visible source file paths clickable to open your editor.
*
* Pre-defined values:
* 'sublime' => 'subl://open?url=file://%file&line=%line',
* 'textmate' => 'txmt://open?url=file://%file&line=%line',
* 'emacs' => 'emacs://open?url=file://%file&line=%line',
* 'macvim' => 'mvim://open/?url=file://%file&line=%line',
* 'phpstorm' => 'phpstorm://open?file=%file&line=%line',
* 'phpstorm-remote' => 'http://localhost:63342/api/file/%file:%line',
* 'idea' => 'idea://open?file=%file&line=%line',
* 'vscode' => 'vscode://file/%file:%line',
* 'vscode-insiders' => 'vscode-insiders://file/%file:%line',
* 'vscode-remote' => 'vscode://vscode-remote/%file:%line',
* 'vscode-insiders-remote' => 'vscode-insiders://vscode-remote/%file:%line',
* 'vscodium' => 'vscodium://file/%file:%line',
* 'atom' => 'atom://core/open/file?filename=%file&line=%line',
* 'nova' => 'nova://core/open/file?filename=%file&line=%line',
* 'netbeans' => 'netbeans://open/?f=%file:%line',
* 'xdebug' => 'xdebug://%file@%line'
*
* Or pass a custom string where %fileileileileileile should be replaced with full file path, %line with line number
* to create a custom link. Set to null to disable linking.
*
* Example:
* // works with for PHPStorm and IDE Remote Control Plugin
* Sage::$editor = 'phpstorm-remote';
* Example:
* // same result as above, but explicitly defined
* Sage::$editor = 'http://localhost:63342/api/file/f:%line';
*
* Default:
* ini_get('xdebug.file_link_format') ?: 'phpstorm-remote'
*
*/
public static $editor;
/**
* @var string the full path (not URL) to your project folder on your remote dev server, be this Homestead, Docker,
* or in the cloud.
*
* Default:
* null
*/
public static $fileLinkServerPath;
/**
* @var string the full path (not URL) to your project on your local machine, the way your IDE or editor accesses
* the files.
*
* Default:
* null
*/
public static $fileLinkLocalPath;
/**
* @var bool whether to display where Sage was called from
*
* Default:
* true
*/
public static $displayCalledFrom;
/**
* @var int max array/object levels to go deep, set to zero/false to disable
*
* Default:
* 7
*/
public static $maxLevels;
/**
* @var string theme for rich view
*
* Example:
* Sage::$theme = Sage::THEME_ORIGINAL;
* Sage::$theme = Sage::THEME_LIGHT;
* Sage::$theme = Sage::THEME_SOLARIZED;
* Sage::$theme = Sage::THEME_SOLARIZED_DARK;
*
* Default:
* Sage::THEME_ORIGINAL
*/
public static $theme;
/**
* @var bool draw rich output already expanded without having to click
*
* Default:
* false
*/
public static $expandedByDefault;
/**
* @var bool enable detection when running in command line and adjust output format accordingly.
*
* Default:
* true
*/
public static $cliDetection;
/**
* @var bool in addition to above setting, enable detection when Sage is run in *UNIX* command line.
* Attempts to add coloring, but if seen as plain text, the color information is visible as gibberish
*
* Default:
* true
*/
public static $cliColors;
/**
* @var array possible alternative char encodings in order of probability,
*
* Default:
* array(
* 'UTF-8',
* 'Windows-1252', // Western; includes iso-8859-1, replace this with windows-1251 if you use Russian
* 'euc-jp', // Japanese
* );
*/
public static $charEncodings;
/**
* @var bool|string Sage returns output instead of echo.
*
* If true, the return has scripts+css always included, if set to a string, only first time per "group".
*
* Default:
* false
*/
public static $returnOutput;
/**
* @var string Write output to this file instead of echoing it. If it ends in `.html` forces output in html mode.
*
* Default:
* false
*/
public static $outputFile;
/**
* @var array Add new custom Sage wrapper names. Needed for nice backtraces, variable name detection and modifiers.
*
* [!] Use notation `Class::method` for methods.
*
* Example:
* function doom_dump($args)
* {
* echo "DOOOM!";
* d(...func_get_args());
* }
* Sage::$aliases = 'doom_dump';
*
* Default:
* array()
*/
public static $aliases = array();
/*
* ██╗ ██╗██╗██████╗
* ██║ ██║██║██╔══██╗
* ██║ █╗ ██║██║██████╔╝
* ██║███╗██║██║██╔═══╝
* ╚███╔███╔╝██║██║
* ╚══╝╚══╝ ╚═╝╚═╝
*/
/**
* @var string[] Patterns of filename paths. Keys don't matter, but you can use them to unset a particular entry.
*/
public static $traceBlacklist = array(
'vendor' => '#\/vendor\/#',
'middleware' => '#\/Middleware\/#'
);
public static $classNameBlacklist = array(
'illuminate' => '/^Illuminate(?!.*(?:Exception|Collection))/'
// 'symfony' => '/^Symfony/'
);
public static $keysBlacklist = array();
public static $minimumTraceStepsToShowFull = 1;
/** @var class-string<SageParser>[] */
public static $enabledParsers = array(
'SageParsersSmarty' => true,
'SageParsersSplFileInfo' => true,
'SageParsersClosure' => true,
'SageParsersEloquent' => true,
'SageParsersDateTime' => true,
'SageParsersSplObjectStorage' => true,
'SageParsersTimestamp' => true,
'SageParsersFilePath' => true,
// above this line are only those parsers that $replacesAllOtherParsers
// now we run the blacklist
'SageParsersBlacklist' => true,
// all the rest
'SageParsersXml' => true,
'SageParsersObjectIterateable' => true,
'SageParsersClassStatics' => true,
'SageParsersColor' => true,
'SageParsersJson' => true,
'SageParsersClassName' => true,
'SageParsersMicrotime' => true,
);
public static function saveState($state = array())
{
$rich = new SageDecoratorsRich();
$plain = new SageDecoratorsPlain();
if (func_num_args()) {
self::$_enabledMode = $state['enabled'];
self::$editor = $state['editor'];
self::$fileLinkServerPath = $state['fileLinkServerPath'];
self::$fileLinkLocalPath = $state['fileLinkLocalPath'];
self::$displayCalledFrom = $state['displayCalledFrom'];
self::$maxLevels = $state['maxLevels'];
self::$theme = $state['theme'];
self::$expandedByDefault = $state['expandedByDefault'];
self::$cliDetection = $state['cliDetection'];
self::$cliColors = $state['cliColors'];
self::$charEncodings = $state['charEncodings'];
self::$returnOutput = $state['returnOutput'];
self::$outputFile = $state['outputFile'];
self::$aliases = $state['aliases'];
self::$traceBlacklist = $state['traceBlacklist'];
self::$classNameBlacklist = $state['classNameBlacklist'];
self::$enabledParsers = $state['enabledParsers'];
$rich->setAssetsNeeded($state['SageDecoratorsRich::firstRun']);
$plain->setAssetsNeeded($state['SageDecoratorsPlain::firstRun']);
return;
}
return array(
'enabled' => self::$_enabledMode,
'editor' => self::$editor,
'fileLinkServerPath' => self::$fileLinkServerPath,
'fileLinkLocalPath' => self::$fileLinkLocalPath,
'displayCalledFrom' => self::$displayCalledFrom,
'maxLevels' => self::$maxLevels,
'theme' => self::$theme,
'expandedByDefault' => self::$expandedByDefault,
'cliDetection' => self::$cliDetection,
'cliColors' => self::$cliColors,
'charEncodings' => self::$charEncodings,
'returnOutput' => self::$returnOutput,
'outputFile' => self::$outputFile,
'aliases' => self::$aliases,
'traceBlacklist' => self::$traceBlacklist,
'classNameBlacklist' => self::$classNameBlacklist,
'enabledParsers' => self::$enabledParsers,
'SageDecoratorsRich::firstRun' => $rich->areAssetsNeeded(),
'SageDecoratorsPlain::firstRun' => $plain->areAssetsNeeded()
);
}
/**
* @var bool there are multiple ways to direct sage to display "simpler" view than current mode (e.g. Rich -> PLain)
* todo must be private
*/
public static $simplifyDisplay = false;
/*
* ██████╗ ██████╗ ███╗ ██╗███████╗████████╗ █████╗ ███╗ ██╗████████╗███████╗
* ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗████╗ ██║╚══██╔══╝██╔════╝
* ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ███████║██╔██╗ ██║ ██║ ███████╗
* ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██║██║╚██╗██║ ██║ ╚════██║
* ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║██║ ╚████║ ██║ ███████║
* ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝
*
*/
const MODE_RICH = 'r';
const MODE_TEXT_ONLY = 'w';
const MODE_CLI = 'c';
const MODE_PLAIN = 'p';
const THEME_ORIGINAL = 'original';
const THEME_LIGHT = 'aante-light';
const THEME_ORIGINAL_LIGHT = 'original-light';
const THEME_SOLARIZED_DARK = 'solarized-dark';
const THEME_SOLARIZED = 'solarized';
/*
* ███████╗███╗ ██╗ █████╗ ██████╗ ██╗ ███████╗██████╗
* ██╔════╝████╗ ██║██╔══██╗██╔══██╗██║ ██╔════╝██╔══██╗
* █████╗ ██╔██╗ ██║███████║██████╔╝██║ █████╗ ██║ ██║
* ██╔══╝ ██║╚██╗██║██╔══██║██╔══██╗██║ ██╔══╝ ██║ ██║
* ███████╗██║ ╚████║██║ ██║██████╔╝███████╗███████╗██████╔╝
* ╚══════╝╚═╝ ╚═══╝╚═╝ ╚═╝╚═════╝ ╚══════╝╚══════╝╚═════╝
*/
/**
* Enables or disables Sage, and forces display mode. Also returns currently active mode.
*
* @param mixed $forceMode
* null or void - return current mode
* false - disable Sage
* true - enable Sage and allow it to auto-detect the best formatting
* Sage::MODE_* - enable and force selected mode:
* - Sage::MODE_RICH Rich Text HTML
* - Sage::MODE_PLAIN Plain-view, HTML formatted output
* - Sage::MODE_CLI Console-formatted colored output
* - Sage::MODE_TEXT_ONLY Non-escaped plain text mode
*
* @return mixed previously set value
*/
public static function enabled($forceMode = null)
{
// act both as a setter...
if (isset($forceMode)) {
$before = self::$_enabledMode;
self::$_enabledMode = $forceMode;
return $before;
}
// ...and a getter
return self::$_enabledMode;
}
/*
* ████████╗██████╗ █████╗ ██████╗███████╗ ██╗██████╗ ██╗ ██╗███╗ ███╗██████╗
* ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██╔════╝ ██╔╝██╔══██╗██║ ██║████╗ ████║██╔══██╗
* ██║ ██████╔╝███████║██║ █████╗ ██╔╝ ██║ ██║██║ ██║██╔████╔██║██████╔╝
* ██║ ██╔══██╗██╔══██║██║ ██╔══╝ ██╔╝ ██║ ██║██║ ██║██║╚██╔╝██║██╔═══╝
* ██║ ██║ ██║██║ ██║╚██████╗███████╗██╔╝ ██████╔╝╚██████╔╝██║ ╚═╝ ██║██║
* ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝
*
*/
/**
* Prints a debug backtrace, same as `sage(1)`.
*
* Skip trace arguments and only see the paths - `sage(2)`
*
* @param array $trace [OPTIONAL] you can pass your own trace, otherwise, `debug_backtrace` will be called
*
* @return mixed
*/
public static function trace($trace = null)
{
if ($trace === null) {
$trace = SageHelper::php53orLater() ? debug_backtrace(true) : debug_backtrace();
}
return self::dump($trace);
}
/**
* Dump information about variables, accepts any number of parameters, supports prefix-modifiers:
*
* ```
* |-------|----------------------------------------------|
* | | Example: `+ saged('magic');` |
* |-------|----------------------------------------------|
* | ! | Dump ignoring depth limits for large objects |
* | print | Puts output into current DIR as sage.html |
* | ~ | Simplifies sage output (rich->html->plain) |
* | - | Clean up any output before dumping |
* | + | Expand all nodes (in rich view) |
* | @ | Return output instead of displaying it |
* |-------|----------------------------------------------|
* ```
*
* Modifiers are supported by all dump wrapper functions, including Sage::trace(). Combinations possible.
*
* -----
* Shorthand to display debug_backtrace():
* Sage::dump( 1 );
* Sage::dump( debug_backtrace() ); // must be single parameter!
*
* @param mixed $data
*
* @return string|int returns 5463 (Sage in l33tspeak) if disabled
*
* Explanation for the magic number in return:
* The return value has to be an int otherwise modifiers throw typesafe warinings, eg if we return null:
*
* ~d(); // TypeError: Cannot perform bitwise not on null
*
* It's not zero because it doesn't matter and if you find this somewhere in your logs or something - you know who
* to blame :))
*/
public static function dump($data = null)
{
try {
$params = func_get_args();
return call_user_func_array(array('Sage', 'doDump'), $params);
} catch (Throwable $e) {
} catch (Exception $e) {
}
return 5463;
}
public static function doDump($data = null)
{
$enabledMode = self::enabled();
if (! $enabledMode) {
return 5463;
}
self::_init();
list($names, $modifiers, $callee, $previousCaller, $miniTrace) = self::_getCalleeInfo();
// auto-detect mode if not explicitly set
if ($enabledMode === true) {
if (! empty($modifiers) && strpos($modifiers, 'print') !== false && isset($callee['file'])) {
$newMode = self::MODE_RICH;
} elseif (self::$outputFile && substr(self::$outputFile, -5) === '.html') {
$newMode = self::MODE_RICH;
} else {
$newMode = PHP_SAPI === 'cli' && self::$cliDetection === true
? self::MODE_CLI
: self::MODE_RICH;
}
if (self::$simplifyDisplay) {
switch ($newMode) {
case self::MODE_RICH:
$newMode = self::MODE_PLAIN;
break;
case self::MODE_CLI:
$newMode = self::MODE_TEXT_ONLY;
break;
}
}
if (! empty($modifiers) && strpos($modifiers, '~') !== false) {
switch ($newMode) {
case self::MODE_RICH:
$newMode = self::MODE_PLAIN;
break;
case self::MODE_PLAIN:
case self::MODE_CLI:
$newMode = self::MODE_TEXT_ONLY;
break;
}
}
self::enabled($newMode);
}
$decoratorClass = self::enabled() === self::MODE_RICH ? 'SageDecoratorsRich' : 'SageDecoratorsPlain';
/** @var SageDecoratorsPlain|SageDecoratorsRich $decorator */
$decorator = new $decoratorClass();
$firstRunOldValue = $decorator->areAssetsNeeded();
// process modifiers: @, +, !, ~ and -
if (! empty($modifiers) && strpos($modifiers, '-') !== false) {
$decorator->setAssetsNeeded(true);
while (ob_get_level()) {
ob_end_clean();
}
}
if (! empty($modifiers) && strpos($modifiers, '+') !== false) {
$expandedByDefaultOldValue = self::$expandedByDefault;
self::$expandedByDefault = true;
}
if (! empty($modifiers) && strpos($modifiers, '!') !== false) {
/*if (strpos($modifiers, '!!') !== false) {
$oldClassNameBlacklist = self::$classNameBlacklist = array();
$oldTraceBlacklist = self::$traceBlacklist = array();
$oldEnabledParsers = self::$enabledParsers;
self::$classNameBlacklist = array();
self::$traceBlacklist = array();
if (($key = array_search('SageParsersEloquent', self::$enabledParsers)) !== false) {
unset(self::$enabledParsers[$key]);
}
} else {*/
$maxLevelsOldValue = self::$maxLevels;
self::$maxLevels = false;
/*}*/
}
if (! empty($modifiers) && strpos($modifiers, '@') !== false) {
$returnOldValue = self::$returnOutput;
self::$returnOutput = true;
}
if (self::$returnOutput) {
if (self::$returnOutput === true) {
$decorator->setAssetsNeeded(true);
} elseif (! isset(self::$_openedOutput[self::$returnOutput])) {
$decorator->setAssetsNeeded(true);
self::$_openedOutput[self::$returnOutput] = true;
}
}
if (! empty($modifiers) && strpos($modifiers, 'print') !== false && isset($callee['file'])) {
$outputFileOldValue = self::$outputFile;
self::$outputFile = dirname($callee['file']) . '/sage.html';
}
if (self::$outputFile && ! isset(self::$_openedOutput[self::$outputFile])) {
$firstRunOldValue = $decorator->areAssetsNeeded();
$decorator->setAssetsNeeded(true);
}
$trace = false;
$lightTrace = false;
if (func_num_args() === 1) {
if ($names === array('1') && $data === 1) {
// Sage::dump(1) shorthand
$trace = SageHelper::php53orLater() ? debug_backtrace(true) : debug_backtrace();
} elseif ($names === array('2') && $data === 2) {
// Sage::dump(2) shorthand todo: create Sage::traceWithoutArgs()
$lightTrace = true;
$trace = debug_backtrace();
} elseif (is_array($data)) {
$trace = $data; // test if the single parameter is result of debug_backtrace()
}
}
if ($trace) {
$trace = self::_parseTrace($trace);
}
$output = '';
if ($decorator->areAssetsNeeded()) {
$output .= $decorator->init();
}
$output .= $decorator->wrapStart();
if ($trace) {
$output .= $decorator->decorateTrace($trace, $lightTrace);
} else {
if (func_num_args() === 0) {
SageParser::reset();
$tmp = microtime();
$varData = SageParser::process($tmp, '');
$varData->type = null;
$varData->name = 'Sage called with no arguments';
$varData->value = null;
$varData->size = null;
if (! empty($callee['function'])) {
if (! empty($callee['class']) && ! empty($callee['type'])) {
$name = $callee['class'] . $callee['type'] . $callee['function'];
} else {
$name = $callee['function'];
}
$varData->name = $name . '( no parameters )';
}
$output .= $decorator->decorate($varData);
} else {
foreach (func_get_args() as $k => $argument) {
SageParser::reset();
// when the dump arguments take long to generate output, user might have changed the file and
// Sage might not parse the arguments correctly, so check if names are set and while the
// displayed names might be wrong, at least don't throw an error
$output .= $decorator->decorate(
SageParser::process($argument, empty($names[$k]) ? '???' : $names[$k])
);
}
}
}
$output .= $decorator->wrapEnd($callee, $miniTrace, $previousCaller);
// now restore all on-the-fly settings and return
if (self::$outputFile) {
try {
if (! isset(self::$_openedOutput[self::$outputFile])) {
self::$_openedOutput[self::$outputFile] = fopen(self::$outputFile, 'w');
$decorator->setAssetsNeeded($firstRunOldValue);
}
fwrite(self::$_openedOutput[self::$outputFile], $output);
echo 'Sage -> ' . self::$outputFile . PHP_EOL;
} catch (Throwable $e) {
self::$outputFile = null;
$output .= "Error: Sage can't write file to " . self::$outputFile;
} catch (Exception $e) {
self::$outputFile = null;
$output .= "Error: Sage can't write file to " . self::$outputFile;
}
}
self::enabled($enabledMode);
$decorator->setAssetsNeeded(false);
if (! empty($modifiers)) {
if (strpos($modifiers, '~') !== false) {
$decorator->setAssetsNeeded($firstRunOldValue);
}
if (strpos($modifiers, '+') !== false) {
self::$expandedByDefault = $expandedByDefaultOldValue;
}
if (isset($maxLevelsOldValue)) {
self::$maxLevels = $maxLevelsOldValue;
}
if (! empty($modifiers) && strpos($modifiers, 'print') !== false && isset($callee['file'])) {
self::$outputFile = $outputFileOldValue;
return 5463;
}
if (strpos($modifiers, '@') !== false) {
self::$returnOutput = $returnOldValue;
$decorator->setAssetsNeeded($firstRunOldValue);
return $output;
}
}
if (self::$returnOutput) {
return $output;
}
if (self::$outputFile) {
return 5463;
}
echo $output;
return 5463;
}
public static function showEloquentQueries()
{
// maintain PHP5.1+ compatibility
if (SageHelper::php53orLater()) {
self::$aliases[] = __CLASS__ . '::' . __FUNCTION__;
require SAGE_DIR . 'inc/eloquentListener.inc.php';
}
}
/*
* ██████╗ ██████╗ ██╗██╗ ██╗ █████╗ ████████╗███████╗
* ██╔══██╗██╔══██╗██║██║ ██║██╔══██╗╚══██╔══╝██╔════╝
* ██████╔╝██████╔╝██║██║ ██║███████║ ██║ █████╗
* ██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██╔══██║ ██║ ██╔══╝
* ██║ ██║ ██║██║ ╚████╔╝ ██║ ██║ ██║ ███████╗
* ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝
*
*/
/**
* returns parameter names that the function was passed, as well as any predefined symbols before function
* call (modifiers)
*
* @return array{$parameters, $modifier, $callee, $previousCaller}
*/
private static function _getCalleeInfo()
{
$trace = debug_backtrace();
$previousCaller = array();
$miniTrace = array();
$prevStep = array();
$insideTemplateDetected = null;
// go from back of trace forward to find first occurrence of call to Sage or its wrappers
while ($step = array_pop($trace)) {
if (SageHelper::stepIsInternal($step)) {
$previousCaller = $prevStep;
break;
}
if (
isset($step['args'][0])
&& is_string($step['args'][0])
&& substr($step['args'][0], -strlen('.blade.php')) === '.blade.php'
) {
$insideTemplateDetected = $step['args'][0];
}
if (isset($step['file'], $step['line'])) {
unset($step['object'], $step['args']);
array_unshift($miniTrace, $step);
}
$prevStep = $step;
}
$callee = $step;
if (! isset($callee['file']) || ! is_readable($callee['file'])) {
return array(null, null, $callee, $previousCaller, $miniTrace);
}
SageHelper::detectProjectRoot($callee['file']);
// open the file and read it up to the position where the function call expression ended
// TODO since PHP 8.2 backtrace reports the lineno of the function/method name!
// https://github.com/php/php-src/pull/8818
// $file = new SplFileObject($callee['file']);
// do {
// $file->seek($callee['line']);
// $contents = $file->current(); // $contents would hold the data from line x
//
// } while (! $file->eof());
$file = fopen($callee['file'], 'r');
$line = 0;
$source = '';
while (($row = fgets($file)) !== false) {
if (++$line > $callee['line']) {
break;
}
$source .= $row;
}
fclose($file);
$source = self::_removeAllButCode($source);
if (empty($callee['class'])) {
$codePattern = $callee['function'];
} else {
$codePattern = "\w+\x07*" . $callee['type'] . "\x07*" . $callee['function'];
}
// get the position of the last call to the function
preg_match_all(
"
/
# beginning of statement
[\x07{(]
# search for modifiers (group 1)
([print\x07-+!@~]*)?
# spaces
\x07*
# possibly a namespace symbol
\\\\?
# spaces again
\x07*
# main call to Sage
({$codePattern})
# spaces everywhere
\x07*
# find the character where Sage's opening bracket resides (group 3)
(\\()
/ix",
$source,
$matches,
PREG_OFFSET_CAPTURE
);
$modifiers = end($matches[1]);
$callToSage = end($matches[2]);
$bracket = end($matches[3]);
if (empty($callToSage)) {
// if a wrapper is misconfigured, don't display the whole file as variable name
return array(array(), $modifiers, $callee, $previousCaller, $miniTrace);
}
$modifiers = str_replace("\x07", '', $modifiers[0]);
$paramsString = preg_replace("[\x07+]", ' ', substr($source, $bracket[1] + 1));
// we now have a string like this:
// <parameters passed>); <the rest of the last read line>
// remove everything in brackets and quotes, we don't need nested statements nor literal strings which would
// complicate separating individual arguments
$c = strlen($paramsString);
$inString = $escaped = $openedBracket = $closingBracket = false;
$i = 0;
$inBrackets = 0;
$openedBrackets = array();
$bracketPairs = array('(' => ')', '[' => ']', '{' => '}');
while ($i < $c) {
$letter = $paramsString[$i];
if (! $inString) {
if ($letter === '\'' || $letter === '"') {
$inString = $letter;
} elseif ($letter === '(' || $letter === '[' || $letter === '{') {
$inBrackets++;
$openedBrackets[] = $openedBracket = $letter;
$closingBracket = $bracketPairs[$letter];
} elseif ($inBrackets && $letter === $closingBracket) {
$inBrackets--;
array_pop($openedBrackets);
$openedBracket = end($openedBrackets);
if ($openedBracket) {
$closingBracket = $bracketPairs[$openedBracket];
}
} elseif (! $inBrackets && $letter === ')') {
$paramsString = substr($paramsString, 0, $i);
break;
}
} elseif ($letter === $inString && ! $escaped) {
$inString = false;
}
// replace whatever was inside quotes or brackets with untypeable characters, we don't
// need that info.
if ($inBrackets > 0) {
if ($inBrackets > 1 || $letter !== $openedBracket) {
$paramsString[$i] = "\x07";
}
}
if ($inString) {
if ($letter !== $inString || $escaped) {
$paramsString[$i] = "\x07";
}
}
$escaped = ! $escaped && ($letter === '\\');
$i++;
}
$names = explode(',', preg_replace("[\x07+]", '...', $paramsString));
$names = array_map('trim', $names);
if ($insideTemplateDetected) {
$callee['file'] = $insideTemplateDetected;
$callee['line'] = null;
}
return array($names, $modifiers, $callee, $previousCaller, $miniTrace);
}
/**
* removes comments and zaps whitespace & < ?php tags from php code, makes for easier further parsing
*
* @param string $source
*
* @return string
*/
private static function _removeAllButCode($source)
{
$commentTokens = array(
T_COMMENT => true,
T_INLINE_HTML => true,
T_DOC_COMMENT => true,
);
$whiteSpaceTokens = array(
T_WHITESPACE => true,
T_CLOSE_TAG => true,
T_OPEN_TAG => true,
T_OPEN_TAG_WITH_ECHO => true,
);
$cleanedSource = '';
foreach (token_get_all($source) as $token) {
if (is_array($token)) {
if (isset($commentTokens[$token[0]])) {
continue;
}
if (isset($whiteSpaceTokens[$token[0]])) {
$token = "\x07";
} else {
$token = $token[1];
}
} elseif ($token === ';') {
$token = "\x07";
}
$cleanedSource .= $token;
}
return $cleanedSource;
}
private static function _parseTrace($data)
{
$trace = array();
$traceFields = array('file', 'line', 'args', 'class');
$fileFound = false; // file element must exist in one of the steps
$lastStep = array();
// validate whether a trace was indeed passed
foreach ($data as $step) {
if (! is_array($step) || ! isset($step['function'])) {
return false;
}
if (! $fileFound && isset($step['file']) && file_exists($step['file'])) {
$fileFound = true;
}
$valid = false;
foreach ($traceFields as $element) {
if (isset($step[$element])) {
$valid = true;
break;
}
}
if (! $valid) {
return false;
}
if ($step['function'] === 'spl_autoload_call') { // meaningless
continue;
}
// also modify it in the same go
if (SageHelper::stepIsInternal($step)) {
// take first step from the top that is not inside Sage already
if (isset($step['file'], $step['line'])) {
$lastStep = array(
'file' => $step['file'],
'line' => $step['line'],
'function' => '',
);
}
continue;
}
$trace[] = $step;
}
if (! $fileFound) {
return false;
}
if ($lastStep) {
array_unshift($trace, $lastStep);
}
// now parse the trace into a usable format