3 final class PhabricatorHandleRemarkupRule
extends PhutilRemarkupRule
{
5 const KEY_RULE_HANDLE
= 'rule.handle';
6 const KEY_RULE_HANDLE_ORIGINAL
= 'rule.handle.original';
8 public function apply($text) {
9 return preg_replace_callback(
10 '/{(PHID-[a-zA-Z0-9-]*)}/',
11 array($this, 'markupHandle'),
15 public function markupHandle(array $matches) {
16 $engine = $this->getEngine();
17 $viewer = $engine->getConfig('viewer');
19 if (!$this->isFlatText($matches[0])) {
23 $phid_type = phid_get_type($matches[1]);
24 if ($phid_type == PhabricatorPHIDConstants
::PHID_TYPE_UNKNOWN
) {
28 $token = $engine->storeText($matches[0]);
29 if ($engine->isTextMode()) {
33 $original_key = self
::KEY_RULE_HANDLE_ORIGINAL
;
34 $original = $engine->getTextMetadata($original_key, array());
35 $original[$token] = $matches[0];
36 $engine->setTextMetadata($original_key, $original);
38 $metadata_key = self
::KEY_RULE_HANDLE
;
39 $metadata = $engine->getTextMetadata($metadata_key, array());
41 if (empty($metadata[$phid])) {
42 $metadata[$phid] = array();
44 $metadata[$phid][] = $token;
45 $engine->setTextMetadata($metadata_key, $metadata);
50 public function didMarkupText() {
51 $engine = $this->getEngine();
53 $metadata_key = self
::KEY_RULE_HANDLE
;
55 $metadata = $engine->getTextMetadata($metadata_key, array());
56 if (empty($metadata)) {
57 // No mentions, or we already processed them.
61 $original_key = self
::KEY_RULE_HANDLE_ORIGINAL
;
62 $original = $engine->getTextMetadata($original_key, array());
64 $phids = array_keys($metadata);
66 $handles = id(new PhabricatorHandleQuery())
67 ->setViewer($this->getEngine()->getConfig('viewer'))
71 foreach ($metadata as $phid => $tokens) {
72 $handle = idx($handles, $phid);
74 if ($handle->isComplete()) {
75 if ($engine->isHTMLMailMode()) {
76 $href = $handle->getURI();
77 $href = PhabricatorEnv
::getProductionURI($href);
84 border-color: #f1f7ff;
86 background-color: #f1f7ff;
87 border: 1px solid transparent;
92 $handle->getLinkName());
94 $link = $handle->renderTag();
95 $link->setPHID($phid);
97 foreach ($tokens as $token) {
98 $engine->overwriteStoredText($token, $link);
101 foreach ($tokens as $token) {
102 $engine->overwriteStoredText($token, idx($original, $token));
107 $engine->setTextMetadata($metadata_key, array());