Debian Codegraph @

vendor/symfony/yaml/Exception/ParseException.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Yaml\Exception;
13
14 /**
15 * Exception class thrown when an error occurs during parsing.
16 *
17 * @author Fabien Potencier <[email protected]>
18 */
19 class ParseException extends RuntimeException
20 {
21 /**
22 * @param string $rawMessage The error message
23 * @param int $parsedLine The line where the error occurred
24 * @param string|null $snippet The snippet of code near the problem
25 * @param string|null $parsedFile The file name where the error occurred
26 */
27 public function __construct(
28 private string $rawMessage,
29 private int $parsedLine = -1,
30 private ?string $snippet = null,
31 private ?string $parsedFile = null,
32 ?\Throwable $previous = null,
33 ) {
34 $this->updateRepr();
35
36 parent::__construct($this->message, 0, $previous);
37 }
38
39 /**
40 * Gets the snippet of code near the error.
41 */
42 public function getSnippet(): string
43 {
44 return $this->snippet;
45 }
46
47 /**
48 * Sets the snippet of code near the error.
49 */
50 public function setSnippet(string $snippet): void
51 {
52 $this->snippet = $snippet;
53
54 $this->updateRepr();
55 }
56
57 /**
58 * Gets the filename where the error occurred.
59 *
60 * This method returns null if a string is parsed.
61 */
62 public function getParsedFile(): string
63 {
64 return $this->parsedFile;
65 }
66
67 /**
68 * Sets the filename where the error occurred.
69 */
70 public function setParsedFile(string $parsedFile): void
71 {
72 $this->parsedFile = $parsedFile;
73
74 $this->updateRepr();
75 }
76
77 /**
78 * Gets the line where the error occurred.
79 */
80 public function getParsedLine(): int
81 {
82 return $this->parsedLine;
83 }
84
85 /**
86 * Sets the line where the error occurred.
87 */
88 public function setParsedLine(int $parsedLine): void
89 {
90 $this->parsedLine = $parsedLine;
91
92 $this->updateRepr();
93 }
94
95 private function updateRepr(): void
96 {
97 $this->message = $this->rawMessage;
98
99 $dot = false;
100 if (str_ends_with($this->message, '.')) {
101 $this->message = substr($this->message, 0, -1);
102 $dot = true;
103 }
104
105 if (null !== $this->parsedFile) {
106 $this->message .= \sprintf(' in %s', json_encode($this->parsedFile, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE));
107 }
108
109 if ($this->parsedLine >= 0) {
110 $this->message .= \sprintf(' at line %d', $this->parsedLine);
111 }
112
113 if ($this->snippet) {
114 $this->message .= \sprintf(' (near "%s")', $this->snippet);
115 }
116
117 if ($dot) {
118 $this->message .= '.';
119 }
120 }
121 }