-
-
Notifications
You must be signed in to change notification settings - Fork 441
Expand file tree
/
Copy pathNewLine.php
More file actions
97 lines (80 loc) · 2.4 KB
/
Copy pathNewLine.php
File metadata and controls
97 lines (80 loc) · 2.4 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
<?php
declare(strict_types=1);
namespace Rector\FileFormatter\ValueObject;
use Nette\Utils\Strings;
use const PHP_EOL;
use Rector\FileFormatter\Exception\InvalidNewLineStringException;
use Stringable;
/**
* @see \Rector\Tests\FileFormatter\ValueObject\NewLineTest
*/
final class NewLine implements Stringable
{
/**
* @var string
*/
final public const LINE_FEED = 'lf';
/**
* @var string
*/
final public const CARRIAGE_RETURN = 'cr';
/**
* @var string
*/
final public const CARRIAGE_RETURN_LINE_FEED = 'crlf';
/**
* @var array<string, string>
*/
private const ALLOWED_END_OF_LINE = [
self::LINE_FEED => "\n",
self::CARRIAGE_RETURN => "\r",
self::CARRIAGE_RETURN_LINE_FEED => "\r\n",
];
/**
* @see https://regex101.com/r/icaBBp/1
* @var string
*/
private const NEWLINE_REGEX = '#(?P<newLine>\r\n|\n|\r)#';
/**
* @see https://regex101.com/r/WrY9ZW/1/
* @var string
*/
private const VALID_NEWLINE_REGEX = '#^(?>\r\n|\n|\r)$#';
private function __construct(
private readonly string $string
) {
}
public function __toString(): string
{
return $this->string;
}
public static function fromSingleCharacter(string $content): self
{
$matches = Strings::match($content, self::VALID_NEWLINE_REGEX);
if ($matches === null) {
throw InvalidNewLineStringException::fromString($content);
}
return new self($content);
}
public static function fromContent(string $content): self
{
$match = Strings::match($content, self::NEWLINE_REGEX);
if (isset($match['newLine'])) {
return self::fromSingleCharacter($match['newLine']);
}
return self::fromSingleCharacter(PHP_EOL);
}
public static function fromEditorConfig(string $endOfLine): self
{
if (! array_key_exists($endOfLine, self::ALLOWED_END_OF_LINE)) {
$allowedEndOfLineValues = array_keys(self::ALLOWED_END_OF_LINE);
$message = sprintf(
'The endOfLine "%s" is not allowed. Allowed are "%s"',
$endOfLine,
implode(',', $allowedEndOfLineValues)
);
throw InvalidNewLineStringException::create($message);
}
return self::fromSingleCharacter(self::ALLOWED_END_OF_LINE[$endOfLine]);
}
}