Repository navigation
Expand file tree
/
Copy pathMentions.php
More file actions
69 lines (57 loc) · 2.55 KB
/
Copy pathMentions.php
File metadata and controls
69 lines (57 loc) · 2.55 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
<?php
declare(strict_types=1);
namespace App\Services;
final readonly class Mentions
{
private const string Pattern = '/(?<![\p{L}\p{N}_.\/@-])@([A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38})(?![A-Za-z0-9_@\/-]|\.[A-Za-z0-9])/u';
public function __construct(private CodeSpans $codeSpans)
{
//
}
/**
* Finds the GitHub handles mentioned as "@handle" in the text, lowercased and once each, in order. A mention
* can't follow a letter, digit, "_", ".", "/", "@" or "-" (so emails are not mentions), and can't run into a path
* or a domain (so "@inertiajs/react" and "@vue.js" are not mentions either), and a mention in code doesn't count
* (so "@Override" or "@param" never notify anyone). Keep the rules in sync with
* resources/js/lib/mentions.ts.
*
* @return list<string>
*/
public function handles(string $text): array
{
if (! str_contains($text, '@')) {
return [];
}
preg_match_all(self::Pattern, $this->codeSpans->withoutCode($text), $matches);
return array_values(array_unique(array_map(strtolower(...), $matches[1])));
}
/**
* Finds where each "@handle" is in the text, by the same rules and also skipping code, so a client can link it
* to the profile like the web does. The handle keeps its case, and the offset and length count characters in
* the whole text and include the "@". The kind says whether it mentions one of the given organizations, by
* lowercase handle, or anyone else.
*
* @param array<string, string> $organizations
* @return list<array{handle: string, offset: int, length: int, kind: 'user'|'organization'}>
*/
public function positions(string $text, array $organizations = []): array
{
$positions = [];
$offset = 0;
foreach ($this->codeSpans->split($text) as $index => $part) {
if ($index % 2 === 0) {
preg_match_all(self::Pattern, $part, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
foreach ($matches as $match) {
$positions[] = [
'handle' => $match[1][0],
'offset' => $offset + mb_strlen(mb_strcut($part, 0, $match[0][1])),
'length' => mb_strlen($match[0][0]),
'kind' => array_key_exists(mb_strtolower($match[1][0]), $organizations) ? 'organization' : 'user',
];
}
}
$offset += mb_strlen($part);
}
return $positions;
}
}