|
1
|
|
|
<?php namespace Tarsana\Command\Console; |
|
2
|
|
|
|
|
3
|
|
|
use Tarsana\Syntax\ArraySyntax; |
|
4
|
|
|
use Tarsana\Syntax\Exceptions\ParseException; |
|
5
|
|
|
use Tarsana\Syntax\ObjectSyntax; |
|
6
|
|
|
use Tarsana\Syntax\Syntax; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Transforms an exception to a string to be shown on the console. |
|
10
|
|
|
*/ |
|
11
|
|
|
class ExceptionPrinter { |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Converts the given exception to a string. |
|
15
|
|
|
* |
|
16
|
|
|
* @param \Exception $e |
|
17
|
|
|
* @return string |
|
18
|
|
|
*/ |
|
19
|
|
|
public function print(\Exception $e) : string |
|
20
|
|
|
{ |
|
21
|
|
|
if ($e instanceof ParseException) |
|
22
|
|
|
return $this->printParseException($e); |
|
23
|
|
|
|
|
24
|
|
|
return "<error>{$e}</error>"; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Converts a parse exception to a string. |
|
29
|
|
|
* |
|
30
|
|
|
* @param Tarsana\Syntax\Exceptions\ParseException $e |
|
31
|
|
|
* @return string |
|
32
|
|
|
*/ |
|
33
|
|
|
public function printParseException(ParseException $e) : string |
|
34
|
|
|
{ |
|
35
|
|
|
$syntax = $e->syntax(); |
|
36
|
|
|
$error = ''; |
|
37
|
|
|
if ($syntax instanceof ObjectSyntax) { |
|
38
|
|
|
$i = $e->extra(); |
|
39
|
|
|
if ($i['type'] == 'invalid-field') |
|
40
|
|
|
$error = "{$i['field']} is invalid!"; |
|
41
|
|
|
if ($i['type'] == 'missing-field') |
|
42
|
|
|
$error = "{$i['field']} is missing!"; |
|
43
|
|
|
if ($i['type'] == 'additional-items') { |
|
44
|
|
|
$items = implode(', ', $i['items']); |
|
45
|
|
|
$error = "additional items {$items}"; |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
$syntax = $this->printSyntax($e->syntax()); |
|
49
|
|
|
|
|
50
|
|
|
$output = "<reset>Failed to parse <warn>'{$e->input()}'</warn> as <info>{$syntax}</info>"; |
|
51
|
|
|
if ('' != $error) |
|
52
|
|
|
$output .= " <error>{$error}</error>"; |
|
53
|
|
|
|
|
54
|
|
|
$previous = $e->previous(); |
|
55
|
|
|
if ($previous) { |
|
56
|
|
|
$output .= '<br>' . $this->printParseException($previous); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
return $output; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
protected function printSyntax(Syntax $s, bool $short = false) : string |
|
63
|
|
|
{ |
|
64
|
|
|
if ($s instanceof ObjectSyntax) { |
|
65
|
|
|
if ($short) return 'object'; |
|
66
|
|
|
return implode($s->separator(), array_keys($s->fields())); |
|
67
|
|
|
} |
|
68
|
|
|
if ($s instanceof ArraySyntax) { |
|
69
|
|
|
if ($short) return 'array'; |
|
70
|
|
|
return $this->printSyntax($s->syntax()).$s->separator().'...'; |
|
71
|
|
|
} |
|
72
|
|
|
return (string) $s; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|