Debian Codegraph @

vendor/wikimedia/shellbox/src/ShellParser/ShellSyntaxError.php

raw
1 <?php
2
3 namespace Shellbox\ShellParser;
4
5 use Shellbox\ShellboxError;
6 use Wikimedia\WikiPEG\Location;
7
8 /**
9 * Exception class for shell command syntax errors. By default the message uses
10 * multiple lines to show the exact location of the syntax error.
11 */
12 class ShellSyntaxError extends ShellboxError {
13 /** @var string */
14 private $originalMessage;
15 /** @var Location */
16 private $location;
17 /** @var string */
18 private $input;
19 /** @var bool */
20 private $contextEnabled;
21
22 /**
23 * @internal
24 * @param string $message The message from the PEG
25 * @param Location $location The error location
26 * @param string $input The complete input text
27 */
28 public function __construct( $message, Location $location, $input ) {
29 parent::__construct( $message );
30 $this->originalMessage = $message;
31 $this->location = $location;
32 $this->input = $input;
33 $this->contextEnabled = true;
34 $this->updateMessage();
35 }
36
37 /**
38 * Enable multi-line context
39 */
40 public function enableContext() {
41 $this->contextEnabled = true;
42 $this->updateMessage();
43 }
44
45 /**
46 * Disable multi-line context
47 */
48 public function disableContext() {
49 $this->contextEnabled = false;
50 $this->updateMessage();
51 }
52
53 /**
54 * Update the message (stored in the parent) according to the contextEnabled
55 * setting.
56 */
57 private function updateMessage() {
58 if ( !$this->contextEnabled ) {
59 $this->message = $this->originalMessage;
60 return;
61 }
62 $lines = explode( "\n", $this->input );
63 $line = $lines[$this->location->line - 1] ?? '';
64 $this->message = $this->originalMessage . "\n" .
65 $line . "\n" .
66 str_repeat( ' ', $this->location->column - 1 ) . '^';
67 }
68 }