This repository was archived by the owner on Mar 6, 2022. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathSourceCode.php
More file actions
92 lines (73 loc) · 2.01 KB
/
Copy pathSourceCode.php
File metadata and controls
92 lines (73 loc) · 2.01 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
<?php
namespace Phpactor\CodeTransform\Domain;
use RuntimeException;
use Webmozart\PathUtil\Path;
final class SourceCode
{
/**
* @var string
*/
private $code;
/**
* @var string
*/
private $path;
private function __construct(string $code, string $path = null)
{
$this->code = $code;
if ($path && false === Path::isAbsolute($path)) {
throw new \RuntimeException(sprintf(
'Path "%s" must be absolute',
$path
));
}
$this->path = $path ? Path::canonicalize($path) : null;
}
public static function fromString(string $code): SourceCode
{
return new self($code);
}
public static function fromStringAndPath(string $code, string $path = null): SourceCode
{
return new self($code, $path);
}
public function __toString()
{
return $this->code;
}
public function withSource(string $code): SourceCode
{
return new self($code, $this->path);
}
public function withPath(string $path): SourceCode
{
return new self($this->code, $path);
}
public function path()
{
return $this->path;
}
public function extractSelection(int $offsetStart, int $offsetEnd)
{
return substr($this->code, $offsetStart, $offsetEnd - $offsetStart);
}
public function replaceSelection(string $replacement, int $offsetStart, int $offsetEnd): SourceCode
{
$start = substr($this->code, 0, $offsetStart);
$end = substr($this->code, $offsetEnd);
return self::withSource($start . $replacement . $end);
}
public static function fromUnknown($code)
{
if ($code instanceof SourceCode) {
return $code;
}
if (is_string($code)) {
return self::fromString($code);
}
throw new RuntimeException(sprintf(
'Do not know how to create source code object from "%s"',
gettype($code)
));
}
}