forked from Skillshare/formatphp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomDescriptorParser.php
More file actions
61 lines (49 loc) · 1.72 KB
/
CustomDescriptorParser.php
File metadata and controls
61 lines (49 loc) · 1.72 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
<?php
declare(strict_types=1);
namespace FormatPHP\Test\Extractor;
use FormatPHP\Descriptor;
use FormatPHP\DescriptorCollection;
use FormatPHP\Extractor\MessageExtractorOptions;
use FormatPHP\Extractor\Parser\DescriptorParserInterface;
use FormatPHP\Extractor\Parser\ParserError;
use FormatPHP\Extractor\Parser\ParserErrorCollection;
use function file_get_contents;
use function preg_match_all;
use function sprintf;
use function strlen;
use function trim;
class CustomDescriptorParser implements DescriptorParserInterface
{
public function __invoke(
string $filePath,
MessageExtractorOptions $options,
ParserErrorCollection $errors
): DescriptorCollection {
$descriptors = new DescriptorCollection();
$contents = (string) file_get_contents($filePath);
preg_match_all(
'/{{#formatMessage *\|? *(?<id>[a-z0-9\-_]*)}}(?<defaultMessage>.*){{\/formatMessage}}/i',
$contents,
$matches,
);
foreach ($matches['id'] as $index => $id) {
if (strlen(trim($id)) === 0) {
$errors[] = new ParserError(
sprintf('Missing "id" in "%s"', $matches[0][$index]),
$filePath,
);
continue;
}
$defaultMessage = $matches['defaultMessage'][$index] ?? '';
if (strlen(trim($defaultMessage)) === 0) {
$errors[] = new ParserError(
sprintf('Missing "defaultMessage" in "%s"', $matches[0][$index]),
$filePath,
);
continue;
}
$descriptors[] = new Descriptor($id, $defaultMessage);
}
return $descriptors;
}
}