66
77use Colors \Color ;
88use PhpSchool \Terminal \Terminal ;
9+ use Throwable ;
910
1011/**
1112 * Console output interface
@@ -22,10 +23,16 @@ class StdOutput implements OutputInterface
2223 */
2324 private $ terminal ;
2425
25- public function __construct (Color $ color , Terminal $ terminal )
26+ /**
27+ * @var string
28+ */
29+ private $ workshopBasePath ;
30+
31+ public function __construct (Color $ color , Terminal $ terminal , string $ workshopBasePath = '' )
2632 {
2733 $ this ->color = $ color ;
2834 $ this ->terminal = $ terminal ;
35+ $ this ->workshopBasePath = $ workshopBasePath ;
2936 }
3037
3138 /**
@@ -41,6 +48,51 @@ public function printError(string $error): void
4148 echo "\n" ;
4249 }
4350
51+ /**
52+ * @param Throwable $exception
53+ */
54+ public function printException (Throwable $ exception ): void
55+ {
56+ $ message = $ exception ->getMessage ();
57+ if (strpos ($ message , $ this ->workshopBasePath ) !== null ) {
58+ $ message = str_replace ($ this ->workshopBasePath , '' , $ message );
59+ }
60+
61+ $ file = $ exception ->getFile ();
62+ if (strpos ($ file , $ this ->workshopBasePath ) !== null ) {
63+ $ file = str_replace ($ this ->workshopBasePath , '' , $ file );
64+ }
65+
66+ $ lines = [
67+ sprintf ("In %s line %d: " , $ file , $ exception ->getLine ()),
68+ sprintf ("[%s (%s)]: " , get_class ($ exception ), $ exception ->getCode ()),
69+ '' ,
70+ $ message
71+ ];
72+
73+ $ length = max (array_map ('strlen ' , $ lines )) + 2 ;
74+ $ this ->emptyLine ();
75+ $ this ->writeLine (' ' . $ this ->color ->__invoke (str_repeat (' ' , $ length ))->bg_red ());
76+
77+ foreach ($ lines as $ line ) {
78+ $ line = str_pad ($ line , $ length - 2 , ' ' , STR_PAD_RIGHT );
79+ $ this ->writeLine (' ' . $ this ->color ->__invoke (" $ line " )->bg_red ()->white ()->bold ());
80+ }
81+
82+ $ this ->writeLine (' ' . $ this ->color ->__invoke (str_repeat (' ' , $ length ))->bg_red ());
83+ $ this ->emptyLine ();
84+
85+ $ this ->writeLine (
86+ implode (
87+ "\n" ,
88+ array_map (function ($ l ) {
89+ return " $ l " ;
90+ },
91+ explode ("\n" , $ exception ->getTraceAsString ()))
92+ )
93+ );
94+ }
95+
4496 /**
4597 * Write a title section. Should be decorated in a way which makes
4698 * the title stand out.
0 commit comments