-
-
Notifications
You must be signed in to change notification settings - Fork 829
/
UnparsePostMentions.php
95 lines (79 loc) · 2.67 KB
/
UnparsePostMentions.php
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
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Mentions\Formatter;
use s9e\TextFormatter\Utils;
use Symfony\Contracts\Translation\TranslatorInterface;
class UnparsePostMentions
{
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
/**
* Configure rendering for user mentions.
*
* @param string $xml
* @param mixed $context
* @return string $xml to be unparsed
*/
public function __invoke($context, string $xml)
{
$xml = $this->updatePostMentionTags($context, $xml);
$xml = $this->unparsePostMentionTags($xml);
return $xml;
}
/**
* Updates XML post mention tags before unparsing so that unparsing uses new display names.
*
* @param mixed $context
* @param string $xml : Parsed text.
* @return string $xml : Updated XML tags;
*/
protected function updatePostMentionTags($context, string $xml): string
{
$post = $context;
return Utils::replaceAttributes($xml, 'POSTMENTION', function ($attributes) use ($post) {
$post = $post->mentionsPosts->find($attributes['id']);
if ($post && $post->user) {
$attributes['displayname'] = $post->user->display_name;
}
if (! $post) {
$attributes['displayname'] = $this->translator->trans('flarum-mentions.forum.post_mention.deleted_text');
}
if ($post && ! $post->user) {
$attributes['displayname'] = $this->translator->trans('core.lib.username.deleted_text');
}
if (strpos($attributes['displayname'], '"#') !== false) {
$attributes['displayname'] = preg_replace('/"#[a-z]{0,3}[0-9]+/', '_', $attributes['displayname']);
}
return $attributes;
});
}
/**
* Transforms post mention tags from XML to raw unparsed content with updated format and display name.
*
* @param string $xml : Parsed text.
* @return string : Unparsed text.
*/
protected function unparsePostMentionTags(string $xml): string
{
$tagName = 'POSTMENTION';
if (strpos($xml, $tagName) === false) {
return $xml;
}
return preg_replace(
'/<'.preg_quote($tagName).'\b[^>]*(?=\bdisplayname="(.*)")[^>]*(?=\bid="([0-9]+)")[^>]*>@[^<]+<\/'.preg_quote($tagName).'>/U',
'@"$1"#p$2',
$xml
);
}
}