You are here

public function AtAutolinker::parse in Markdown 3.0.x

File

src/Plugin/Markdown/Extension/AtAutolinker.php, line 83

Class

AtAutolinker
Plugin annotation @MarkdownExtension( id = "at_autolinker", label = @Translation("@ Autolinker"), installed = TRUE, description = @Translation("Automatically link commonly used references that come after an at character (@) without having to…

Namespace

Drupal\markdown\Plugin\Markdown\Extension

Code

public function parse(InlineParserContext $inline_context) : bool {
  $cursor = $inline_context
    ->getCursor();

  // The @ symbol must not have any other characters immediately prior.
  $previous_char = $cursor
    ->peek(-1);
  if ($previous_char !== NULL && $previous_char !== ' ') {

    // peek() doesn't modify the cursor, so no need to restore state first.
    return FALSE;
  }

  // Save the cursor state in case we need to rewind and bail.
  $previous_state = $cursor
    ->saveState();

  // Advance past the @ symbol to keep parsing simpler.
  $cursor
    ->advance();

  // Parse the handle.
  $text = $cursor
    ->match('/^[^\\s]+/');
  $url = '';
  $title = '';
  $type = $this
    ->getSetting('type');
  if ($type === 'user') {
    $users = \Drupal::entityTypeManager()
      ->getStorage('user');

    /** @var \Drupal\user\UserInterface $user */
    $user = is_numeric($text) ? $users
      ->load($text) : $users
      ->loadByProperties([
      'name' => $text,
    ]);
    if ($user && $user
      ->id()) {
      $url = $user
        ->toUrl('canonical', [
        'absolute' => TRUE,
      ])
        ->toString();
      $title = $this
        ->t('View user profile.');
      $text = $this
        ->getSetting('format_username') ? $user
        ->getDisplayName() : $user
        ->getAccountName();
    }
    else {
      $text = FALSE;
    }
  }
  elseif ($type === 'url' && ($url = $this
    ->getSetting('url')) && strpos($url, '[text]') !== FALSE) {
    $url = str_replace('[text]', $text, $url);
  }
  else {
    $text = FALSE;
  }

  // Regex failed to match; this isn't a valid @ handle.
  if (empty($text) || empty($url)) {
    $cursor
      ->restoreState($previous_state);
    return FALSE;
  }
  $inline_context
    ->getContainer()
    ->appendChild(new Link($url, '@' . $text, $title));
  return TRUE;
}