Repository navigation
Expand file tree
/
Copy pathTextDocumentBuilder.php
More file actions
122 lines (95 loc) · 2.87 KB
/
Copy pathTextDocumentBuilder.php
File metadata and controls
122 lines (95 loc) · 2.87 KB
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
<?php
namespace Phpactor\TextDocument;
use Phpactor\TextDocument\Exception\TextDocumentNotFound;
use RuntimeException;
use Symfony\Component\Filesystem\Path;
final class TextDocumentBuilder
{
private ?TextDocumentUri $uri = null;
private ?TextDocumentLanguage $language = null;
private function __construct(private string $text)
{
}
public static function create(string $text): self
{
return new self($text);
}
public static function fromUri(string $uri, ?string $language = null): self
{
$uri = TextDocumentUri::fromString($uri);
if (!file_exists($uri)) {
throw new TextDocumentNotFound(sprintf(
'Text Document not found at URI "%s"',
$uri
));
}
if (!is_readable($uri)) {
throw new RuntimeException(sprintf(
'Could not read file at URI "%s"',
$uri
));
}
if (null === $language) {
$language = Path::getExtension((string) $uri);
}
$contents = file_get_contents($uri);
if (false === $contents) {
throw new RuntimeException(sprintf(
'Could not read file at URI "%s"',
$uri
));
}
$new = new self($contents);
$new->uri = $uri;
$new->language = TextDocumentLanguage::fromString($language);
return $new;
}
public static function fromTextDocument(TextDocument $document): self
{
$new = new self($document->__toString());
$new->uri = $document->uri();
$new->language = $document->language();
return $new;
}
public function uri(string $uri): self
{
$this->uri = TextDocumentUri::fromString($uri);
return $this;
}
public function language(string $language): self
{
$this->language = TextDocumentLanguage::fromString($language);
return $this;
}
public function text(string $text): self
{
$this->text = $text;
return $this;
}
public function build(): TextDocument
{
return new StandardTextDocument(
$this->language ?? TextDocumentLanguage::undefined(),
$this->text,
$this->uri
);
}
/**
* @deprecated this method encourages the creation of documents without the URI.
*/
public static function fromUnknown(TextDocument|string $sourceCode): TextDocument
{
if ($sourceCode instanceof TextDocument) {
return $sourceCode;
}
return self::create($sourceCode)->build();
}
public static function empty(): TextDocument
{
return self::create('')->build();
}
public static function fromPathAndString(string $path, string $string): TextDocument
{
return self::create($string)->uri($path)->build();
}
}