You are here

class Markdown in Markdown 3.0.x

Same name in this branch
  1. 3.0.x src/Markdown.php \Drupal\markdown\Markdown
  2. 3.0.x src/Plugin/Filter/Markdown.php \Drupal\markdown\Plugin\Filter\Markdown
Same name and namespace in other branches
  1. 8 src/Plugin/Filter/Markdown.php \Drupal\markdown\Plugin\Filter\Markdown

Provides a filter for Markdown.

Plugin annotation


@Filter(
  id = "markdown",
  title = @Translation("Markdown"),
  description = @Translation("Allows content to be submitted using Markdown, a simple plain-text syntax that is filtered into valid HTML."),
  type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
  weight = -15,
  settings = {
    "parser" = "thephpleague/commonmark",
    "parser_settings" = {},
  },
)

Hierarchy

Expanded class hierarchy of Markdown

2 string references to 'Markdown'
markdown.info.yml in ./markdown.info.yml
markdown.info.yml
markdown_requirements in ./markdown.install
Implements hook_requirements().

File

src/Plugin/Filter/Markdown.php, line 31

Namespace

Drupal\markdown\Plugin\Filter
View source
class Markdown extends FilterBase implements MarkdownFilterInterface {
  use MarkdownStatesTrait;

  /**
   * The Markdown parser as set by the filter.
   *
   * @var \Drupal\markdown\Plugin\Markdown\MarkdownParserInterface
   */
  protected $parser;

  /**
   * The Markdown Parser Manager service.
   *
   * @var \Drupal\markdown\MarkdownParserManager
   */
  protected $parserManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->parserManager = \Drupal::service('plugin.manager.markdown.parser');
  }

  /**
   * {@inheritdoc}
   */
  public function getSetting($name, $default = NULL) {
    $settings = $this
      ->getSettings();
    return isset($settings[$name]) ? $settings[$name] : $default;
  }

  /**
   * {@inheritdoc}
   */
  public function getSettings() {
    return $this->settings;
  }

  /**
   * {@inheritdoc}
   */
  public function getParser() {
    if (!isset($this->parser)) {
      $this->parser = $this->parserManager
        ->createInstance($this
        ->getSetting('parser', 'thephpleague/commonmark'), [
        'filter' => $this,
      ]);
    }
    return $this->parser;
  }

  /**
   * {@inheritdoc}
   */
  public function getParserSetting($name, $default = NULL) {
    $settings = $this
      ->getParserSettings();
    return isset($settings[$name]) ? $settings[$name] : $default;
  }

  /**
   * {@inheritdoc}
   */
  public function getParserSettings() {
    return $this
      ->getSetting('parser_settings', []);
  }

  /**
   * {@inheritdoc}
   */
  public function isEnabled() {
    return !!$this->status;
  }

  /**
   * {@inheritdoc}
   *
   * @todo Refactor before release.
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $parents = $form['#parents'];
    $defaultParser = $form_state
      ->getValue(array_merge($parents, [
      'parser',
    ]), $this
      ->getParser()
      ->getPluginId());
    if ($labels = $this->parserManager
      ->getLabels()) {
      $id = Html::getUniqueId('markdown-parser-ajax');

      // Build a wrapper for the ajax response.
      $form['ajax'] = [
        '#type' => 'container',
        '#attributes' => [
          'id' => $id,
        ],
        '#parents' => $parents,
      ];
      $form['ajax']['parser'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Parser'),
        '#options' => $labels,
        '#default_value' => $defaultParser,
        '#ajax' => [
          'callback' => [
            $this,
            'ajaxChangeParser',
          ],
          'event' => 'change',
          'wrapper' => $id,
        ],
      ];
    }
    else {
      $form['ajax']['parser'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('No Markdown Parsers Found'),
        '#description' => $this
          ->t('Visit the <a href=":system.status">@system.status</a> page for more details.', [
          '@system.status' => $this
            ->t('Status report'),
          ':system.status' => \Drupal::urlGenerator()
            ->generate('system.status'),
        ]),
      ];
    }
    if ($defaultParser && ($parser = $this->parserManager
      ->createInstance($defaultParser, [
      'filter' => $this,
    ])) && $parser instanceof ExtensibleMarkdownParserInterface && ($extensions = $parser
      ->getExtensions())) {

      // @todo Add parser specific settings.
      $form['ajax']['parser_settings'] = [
        '#type' => 'fieldset',
        '#title' => $this
          ->t('Extensions'),
      ];

      // Add any specific extension settings.
      $form['ajax']['parser_settings']['extensions'] = [
        '#type' => 'container',
      ];
      foreach ($extensions as $pluginId => $extension) {

        // Extension Details.
        $form['ajax']['parser_settings']['extensions'][$pluginId] = [
          '#type' => 'details',
          '#title' => ($url = $extension
            ->getUrl()) ? Link::fromTextAndUrl($extension
            ->getLabel(), $url) : $extension
            ->getLabel(),
          '#description' => $extension
            ->getDescription(),
          '#open' => $extension
            ->isEnabled(),
          '#array_parents' => array_merge($parents, [
            'parser_settings',
            'extensions',
          ]),
        ];

        // Extension enabled checkbox.
        $form['ajax']['parser_settings']['extensions'][$pluginId]['enabled'] = [
          '#type' => 'checkbox',
          '#title' => $this
            ->t('Enabled'),
          '#default_value' => $extension
            ->isEnabled(),
        ];

        // Extension settings.
        $selector = $this
          ->getSatesSelector(array_merge($parents, [
          'parser_settings',
          'extensions',
          $pluginId,
        ]), 'enabled');
        $form['ajax']['parser_settings']['extensions'][$pluginId]['settings'] = [
          '#type' => 'container',
          '#states' => [
            'visible' => [
              $selector => [
                'checked' => TRUE,
              ],
            ],
          ],
        ];
        $form['ajax']['parser_settings']['extensions'][$pluginId]['settings'] = $extension
          ->settingsForm($form['ajax']['parser_settings']['extensions'][$pluginId]['settings'], $form_state, $this);
      }
    }
    return $form;
  }

  /**
   * The AJAX callback used to return the parser ajax wrapper.
   */
  public function ajaxChangeParser(array $form, FormStateInterface $form_state) {
    $parents = $form_state
      ->getTriggeringElement()['#array_parents'];
    array_pop($parents);
    return NestedArray::getValue($form, $parents);
  }
  public static function processTextFormat(&$element, FormStateInterface $form_state, &$complete_form) {
    $formats = filter_formats();

    /** @var \Drupal\filter\FilterFormatInterface $format */
    $format = isset($formats[$element['#format']]) ? $formats[$element['#format']] : FALSE;
    if ($format && ($markdown = $format
      ->filters('markdown')) && $markdown instanceof MarkdownFilterInterface && $markdown
      ->isEnabled()) {
      $element['format']['help']['about'] = [
        '#type' => 'link',
        '#title' => t('@iconStyling with Markdown is supported', [
          // Shamelessly copied from GitHub's Octicon icon set.
          // @todo Revisit this?
          // @see https://github.com/primer/octicons/blob/master/lib/svg/markdown.svg
          '@icon' => new FormattableMarkup('<svg class="octicon octicon-markdown v-align-bottom" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true" style="fill: currentColor;margin-right: 5px;vertical-align: text-bottom;"><path fill-rule="evenodd" d="M14.85 3H1.15C.52 3 0 3.52 0 4.15v7.69C0 12.48.52 13 1.15 13h13.69c.64 0 1.15-.52 1.15-1.15v-7.7C16 3.52 15.48 3 14.85 3zM9 11H7V8L5.5 9.92 4 8v3H2V5h2l1.5 2L7 5h2v6zm2.99.5L9.5 8H11V5h2v3h1.5l-2.51 3.5z"></path></svg>', []),
        ]),
        '#url' => Url::fromRoute('filter.tips_all')
          ->setOptions([
          'attributes' => [
            'class' => [
              'markdown',
            ],
            'target' => '_blank',
          ],
        ]),
      ];
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {

    // Only use the parser to process the text if it's not empty.
    if (!empty($text)) {
      $language = \Drupal::languageManager()
        ->getLanguage($langcode);
      $markdown = $this
        ->getParser()
        ->parse($text, $language);

      // Enable all tags, let other filters (i.e. filter_html) handle that.
      $text = $markdown
        ->setAllowedTags(TRUE)
        ->getHtml();
    }
    return new FilterProcessResult($text);
  }

  /**
   * {@inheritdoc}
   */
  public function tips($long = FALSE) {
    return $this
      ->getParser()
      ->tips($long);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FilterBase::$provider public property The name of the provider that owns this filter.
FilterBase::$settings public property An associative array containing the configured settings of this filter.
FilterBase::$status public property A Boolean indicating whether this filter is enabled.
FilterBase::$weight public property The weight of this filter compared to others in a filter collection.
FilterBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 1
FilterBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration
FilterBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
FilterBase::getDescription public function Returns the administrative description for this filter plugin. Overrides FilterInterface::getDescription
FilterBase::getHTMLRestrictions public function Returns HTML allowed by this filter's configuration. Overrides FilterInterface::getHTMLRestrictions 4
FilterBase::getLabel public function Returns the administrative label for this filter plugin. Overrides FilterInterface::getLabel
FilterBase::getType public function Returns the processing type of this filter plugin. Overrides FilterInterface::getType
FilterBase::prepare public function Prepares the text for processing. Overrides FilterInterface::prepare
FilterBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 1
FilterInterface::TYPE_HTML_RESTRICTOR constant HTML tag and attribute restricting filters to prevent XSS attacks.
FilterInterface::TYPE_MARKUP_LANGUAGE constant Non-HTML markup language filters that generate HTML.
FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE constant Irreversible transformation filters.
FilterInterface::TYPE_TRANSFORM_REVERSIBLE constant Reversible transformation filters.
Markdown::$parser protected property The Markdown parser as set by the filter.
Markdown::$parserManager protected property The Markdown Parser Manager service.
Markdown::ajaxChangeParser public function The AJAX callback used to return the parser ajax wrapper.
Markdown::getParser public function Retrieves the MarkdownParser plugin for this filter. Overrides MarkdownFilterInterface::getParser
Markdown::getParserSetting public function Retrieves a specific parser setting. Overrides MarkdownFilterInterface::getParserSetting
Markdown::getParserSettings public function Retrieves all parser specific settings. Overrides MarkdownFilterInterface::getParserSettings
Markdown::getSetting public function Retrieves a specific setting. Overrides MarkdownFilterInterface::getSetting
Markdown::getSettings public function Retrieves all settings. Overrides MarkdownFilterInterface::getSettings
Markdown::isEnabled public function Indicates whether the filter is enabled or not. Overrides MarkdownFilterInterface::isEnabled
Markdown::process public function Performs the filter processing. Overrides FilterInterface::process
Markdown::processTextFormat public static function
Markdown::settingsForm public function @todo Refactor before release. Overrides FilterBase::settingsForm
Markdown::tips public function Generates a filter's tip. Overrides FilterBase::tips
Markdown::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides FilterBase::__construct
MarkdownStatesTrait::getElementParents protected static function Retrieves the ancestry of the extension in a form/render array.
MarkdownStatesTrait::getSatesSelector protected static function Retrieves a states selector to use based on the form/render array parents.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.