You are here

class PhpMarkdown in Markdown 8.2

Support for PHP Markdown by Michel Fortin.

Plugin annotation


@MarkdownAllowedHtml(
  id = "php-markdown",
)
@MarkdownParser(
  id = "php-markdown",
  label = @Translation("PHP Markdown"),
  description = @Translation("Parser for Markdown."),
  weight = 31,
  libraries = {
    @ComposerPackage(
      id = "michelf/php-markdown",
      object = "\Michelf\Markdown",
      url = "https://michelf.ca/projects/php-markdown",
    ),
  }
)

Hierarchy

Expanded class hierarchy of PhpMarkdown

File

src/Plugin/Markdown/PhpMarkdown/PhpMarkdown.php, line 33

Namespace

Drupal\markdown\Plugin\Markdown\PhpMarkdown
View source
class PhpMarkdown extends BaseParser implements AllowedHtmlInterface, SettingsInterface {
  use ParserAllowedHtmlTrait;

  /**
   * The PHP Markdown class to use.
   *
   * @var string
   */
  protected static $phpMarkdownClass = '\\Michelf\\Markdown';

  /**
   * The PHP Markdown instance.
   *
   * @var \Michelf\Markdown
   */
  protected $phpMarkdown;

  /**
   * {@inheritdoc}
   */
  public function __sleep() {
    unset($this->phpMarkdown);
    return parent::__sleep();
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings($pluginDefinition) {

    /* @var \Drupal\markdown\Annotation\InstallablePlugin $pluginDefinition */
    return [
      'empty_element_suffix' => ' />',
      'enhanced_ordered_list' => FALSE,
      'hard_wrap' => FALSE,
      'no_entities' => FALSE,
      'no_markup' => FALSE,
      'predef_titles' => [],
      'predef_urls' => [],
      'tab_width' => 4,
    ] + parent::defaultSettings($pluginDefinition);
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $element, FormStateInterface $form_state) {

    /** @var \Drupal\markdown\Form\SubformStateInterface $form_state */
    $element = parent::buildConfigurationForm($element, $form_state);
    $element += $this
      ->createSettingElement('enhanced_ordered_list', [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enhanced Ordered List'),
      '#description' => $this
        ->t('Enabling this allows ordered list to start with a number different from 1.'),
    ], $form_state);
    $element += $this
      ->createSettingElement('hard_wrap', [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Hard Wrap'),
      '#description' => $this
        ->t('Enabling this will change line breaks into <code>&lt;br /&gt;</code> when the context allows it. When disabled, following the standard Markdown syntax these newlines are ignored unless they a preceded by two spaces.'),
    ], $form_state);
    $element += $this
      ->createSettingElement('no_entities', [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('No Entities'),
      '#description' => $this
        ->t('Enabling this will prevent HTML entities (such as <code>&lt;</code>) from being passed verbatim in the output as it is the standard with Markdown. Instead, the HTML output will be <code>&amp;tl;</code> and once shown in shown the browser it will match perfectly what was written.'),
    ], $form_state);
    $this
      ->renderStrategyDisabledSettingState($form_state, $element['no_entities']);
    $element += $this
      ->createSettingElement('no_markup', [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('No Markup'),
      '#description' => $this
        ->t('Enabling this will prevent HTML tags from the input from being passed to the output.'),
    ], $form_state);
    $this
      ->renderStrategyDisabledSettingState($form_state, $element['no_markup']);
    $element += $this
      ->createSettingElement('empty_element_suffix', [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Empty Element Suffix'),
      '#description' => $this
        ->t('This is the string used to close tags for HTML elements with no content such as <code>&lt;br&gt;</code> and <code>&lt;hr&gt;</code>. The default value creates XML-style empty element tags which are also valid in HTML 5.'),
    ], $form_state);
    $element += $this
      ->createSettingElement('tab_width', [
      '#type' => 'number',
      '#title' => $this
        ->t('Tab Width'),
      '#description' => $this
        ->t('The width of a tab character on input. Changing this will affect how many spaces a tab character represents.<br>NOTE: Keep in mind that when the Markdown syntax spec says "four spaces or one tab", it actually means "four spaces after tabs are expanded to spaces". So this to <code>8</code> will make the parser treat a tab character as two levels of indentation.'),
      '#min' => 4,
      '#max' => 32,
    ], $form_state);
    $element['predefined'] = [
      '#weight' => 10,
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('Predefined'),
      '#parents' => $form_state
        ->createParents(),
    ];
    $element['predefined'] += $this
      ->createSettingElement('predef_urls', [
      '#type' => 'textarea',
      '#title' => $this
        ->t('URLs'),
      '#description' => $this
        ->t('A predefined key|value pipe list of URLs, where the key is the value left of a pipe (<code>|</code>) and the URL is to the right of it; only one key|value pipe item per line.<br>For example, adding the following <code>example|http://www.example.com</code> allows the following in markdown <code>[click here][example]</code> to be parsed and replaced with <code>&lt;a href="http://www.example.com"&gt;click here&lt;/a&gt;</code>.'),
    ], $form_state, '\\Drupal\\markdown\\Util\\KeyValuePipeConverter::denormalize');
    $element['predefined'] += $this
      ->createSettingElement('predef_titles', [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Titles'),
      '#description' => $this
        ->t('A predefined key|value pipe list of titles, where the key is the value left of a pipe (<code>|</code>) and the URL is to the right of it; only one key|value pipe item per line.<br>The key must match a corresponding key in Predefined URLs and the value will be used to set the link title attribute.'),
    ], $form_state, '\\Drupal\\markdown\\Util\\KeyValuePipeConverter::denormalize');
    $form_state
      ->addElementState($element['predefined']['predef_titles'], 'disabled', 'predef_urls', [
      'value' => '',
    ]);
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  protected function convertToHtml($markdown, LanguageInterface $language = NULL) {
    return $this
      ->getPhpMarkdown()
      ->transform($markdown);
  }

  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    $configuration = parent::getConfiguration();

    // Normalize settings from a key|value string into an associative array.
    foreach ([
      'predef_titles',
      'predef_urls',
    ] as $name) {
      if (isset($configuration['settings'][$name])) {
        $configuration['settings'][$name] = KeyValuePipeConverter::normalize($configuration['settings'][$name]);
      }
    }
    return $configuration;
  }

  /**
   * Retrieves the PHP Markdown parser.
   *
   * @return \Michelf\Markdown
   *   A PHP Markdown parser.
   */
  public function getPhpMarkdown() {
    if (!$this->phpMarkdown) {
      $this->phpMarkdown = new static::$phpMarkdownClass();
      $settings = $this
        ->getSettings();

      // Unless the render strategy is set to "none", force the
      // following settings to be disabled.
      if ($this
        ->getRenderStrategy() !== static::NONE) {
        $settings['no_entities'] = FALSE;
        $settings['no_markup'] = FALSE;
      }

      // Set settings.
      foreach ($this
        ->getSettings() as $name => $value) {
        if ($this
          ->settingExists($name)) {
          $this->phpMarkdown->{$name} = $value;
        }
      }
    }
    return $this->phpMarkdown;
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {

    // Normalize settings from a key|value string into an associative array.
    foreach ([
      'predef_titles',
      'predef_urls',
    ] as $name) {
      if (isset($configuration['settings'][$name])) {
        $configuration['settings'][$name] = KeyValuePipeConverter::normalize($configuration['settings'][$name]);
      }
    }
    return parent::setConfiguration($configuration);
  }

  /**
   * Indicates whether the setting exists.
   *
   * @param string $name
   *   The setting name.
   *
   * @return bool
   *   TRUE or FALSE
   */
  public function settingExists($name) {
    return property_exists(static::$phpMarkdownClass, $name);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AnnotatedPluginBase::$originalPluginId protected property The original plugin_id that was called, not a fallback identifier.
AnnotatedPluginBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
AnnotatedPluginBase::getConfigurationOverrides public function Retrieves the configuration overrides for the plugin. Overrides AnnotatedPluginInterface::getConfigurationOverrides
AnnotatedPluginBase::getDescription public function Retrieves the description of the plugin, if set. Overrides AnnotatedPluginInterface::getDescription
AnnotatedPluginBase::getOriginalPluginId public function Retrieves the original plugin identifier. Overrides AnnotatedPluginInterface::getOriginalPluginId
AnnotatedPluginBase::getProvider public function Returns the provider (extension name) of the plugin. Overrides AnnotatedPluginInterface::getProvider
AnnotatedPluginBase::getWeight public function Returns the weight of the plugin (used for sorting). Overrides AnnotatedPluginInterface::getWeight
AnnotatedPluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct
AnnotatedPluginBase::__toString public function
BaseParser::$enabled protected property
BaseParser::getAllowedHtml Deprecated public function Overrides RenderStrategyInterface::getAllowedHtml
BaseParser::getAllowedHtmlPlugins public function Retrieves the allowed HTML plugins relevant to the object. Overrides RenderStrategyInterface::getAllowedHtmlPlugins
BaseParser::getConfigurationSortOrder protected function Determines the configuration sort order by weight. Overrides InstallablePluginBase::getConfigurationSortOrder 1
BaseParser::getContext protected function Builds context around a markdown parser's hierarchy filter format chain.
BaseParser::getCustomAllowedHtml public function Retrieves the custom (user provided) allowed HTML. Overrides RenderStrategyInterface::getCustomAllowedHtml
BaseParser::getRenderStrategy public function Retrieves the render strategy to use. Overrides RenderStrategyInterface::getRenderStrategy
BaseParser::parse public function Parses markdown into HTML. Overrides ParserInterface::parse
BaseParser::renderStrategyDisabledSetting protected function A description explaining why a setting is disabled due to render strategy.
BaseParser::renderStrategyDisabledSettingState protected function Adds a conditional state for a setting element based on render strategy.
BaseParser::validateSettings public static function Validates parser settings.
CacheableDependencyTrait::$cacheContexts protected property Cache contexts.
CacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
CacheableDependencyTrait::$cacheTags protected property Cache tags.
CacheableDependencyTrait::getCacheContexts public function 3
CacheableDependencyTrait::getCacheMaxAge public function 3
CacheableDependencyTrait::getCacheTags public function 3
CacheableDependencyTrait::setCacheability protected function Sets cacheability; useful for value object constructors.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
EnabledPluginTrait::enabledByDefault public function 1
EnabledPluginTrait::isEnabled public function
FilterAwareTrait::$filter protected property A Filter plugin.
FilterAwareTrait::getFilter public function
FilterAwareTrait::setFilter public function
InstallablePluginBase::$config protected property The config for this plugin.
InstallablePluginBase::buildLibrary public function Builds a display for a library. Overrides InstallablePluginInterface::buildLibrary
InstallablePluginBase::buildStatus public function Builds a display status based on the current state of the plugin. Overrides InstallablePluginInterface::buildStatus
InstallablePluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
InstallablePluginBase::config public function Retrieves the config instance for this plugin. Overrides InstallablePluginInterface::config
InstallablePluginBase::createConfig protected static function
InstallablePluginBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides AnnotatedPluginBase::defaultConfiguration 1
InstallablePluginBase::getAvailableInstalls public function Retrieves available installs.
InstallablePluginBase::getConfigurationName protected function Returns the configuration name for the plugin.
InstallablePluginBase::getContainer public function Retrieves the container.
InstallablePluginBase::getDeprecated public function Retrieves the deprecation message, if any. Overrides InstallablePluginInterface::getDeprecated
InstallablePluginBase::getExperimental public function Retrieves the experimental message. Overrides InstallablePluginInterface::getExperimental
InstallablePluginBase::getInstalledId public function Retrieves the composer package name of the installable library, if any. Overrides InstallablePluginInterface::getInstalledId
InstallablePluginBase::getInstalledLibrary public function Retrieves the installed library used by the plugin. Overrides InstallablePluginInterface::getInstalledLibrary
InstallablePluginBase::getLabel public function Displays the human-readable label of the plugin. Overrides AnnotatedPluginBase::getLabel
InstallablePluginBase::getLink public function Retrieves the plugin as a link using its label and URL. Overrides InstallablePluginInterface::getLink
InstallablePluginBase::getObject public function @TODO: Refactor to use variadic parameters. Overrides InstallablePluginInterface::getObject
InstallablePluginBase::getObjectClass public function Retrieves the class name of the object defined by the installed library. Overrides InstallablePluginInterface::getObjectClass
InstallablePluginBase::getPluginDependencies protected function 1
InstallablePluginBase::getPreferredLibrary public function Retrieves the preferred library of the plugin. Overrides InstallablePluginInterface::getPreferredLibrary
InstallablePluginBase::getSortedConfiguration public function Retrieves the configuration for the plugin, but sorted. Overrides InstallablePluginInterface::getSortedConfiguration
InstallablePluginBase::getUrl public function Retrieves the URL of the plugin, if set. Overrides InstallablePluginInterface::getUrl
InstallablePluginBase::getVersion public function The current version of the plugin. Overrides InstallablePluginInterface::getVersion
InstallablePluginBase::getVersionConstraint public function
InstallablePluginBase::hasMultipleLibraries public function Indicates whether plugin has multiple installs to check. Overrides InstallablePluginInterface::hasMultipleLibraries
InstallablePluginBase::isInstalled public function Indicates whether the plugin is installed. Overrides InstallablePluginInterface::isInstalled
InstallablePluginBase::isPreferred public function Indicates whether the plugin is using the preferred library. Overrides InstallablePluginInterface::isPreferred
InstallablePluginBase::isPreferredLibraryInstalled public function Indicates whether the preferred library is installed. Overrides InstallablePluginInterface::isPreferredLibraryInstalled
InstallablePluginBase::showInUi public function Indicates whether the plugin should be shown in the UI. Overrides InstallablePluginInterface::showInUi
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
MoreInfoTrait::moreInfo protected function Appends existing content with a "More Info" link.
ParserAllowedHtmlTrait::allowedHtmlTags public function 1
PhpMarkdown::$phpMarkdown protected property The PHP Markdown instance.
PhpMarkdown::$phpMarkdownClass protected static property The PHP Markdown class to use. 1
PhpMarkdown::buildConfigurationForm public function Form constructor. Overrides BaseParser::buildConfigurationForm 1
PhpMarkdown::convertToHtml protected function Converts Markdown into HTML. Overrides BaseParser::convertToHtml
PhpMarkdown::defaultSettings public static function Provides the default settings for the plugin. Overrides SettingsTrait::defaultSettings 1
PhpMarkdown::getConfiguration public function Gets this plugin's configuration. Overrides BaseParser::getConfiguration 1
PhpMarkdown::getPhpMarkdown public function Retrieves the PHP Markdown parser.
PhpMarkdown::setConfiguration public function Sets the configuration for this plugin instance. Overrides InstallablePluginBase::setConfiguration 1
PhpMarkdown::settingExists public function Indicates whether the setting exists. Overrides SettingsTrait::settingExists
PhpMarkdown::__sleep public function Overrides DependencySerializationTrait::__sleep
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 3
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.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance.
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance. Aliased as: getPluginDependenciesTrait
PluginDependencyTrait::moduleHandler protected function Wraps the module handler.
PluginDependencyTrait::themeHandler protected function Wraps the theme handler.
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
RendererTrait::$renderer protected static property The Renderer service.
RendererTrait::renderer protected function Retrieves the Renderer service.
RenderStrategyInterface::DOCUMENTATION_URL constant The documentation URL for further explaining render strategies.
RenderStrategyInterface::ESCAPE_INPUT constant Strategy used to escape HTML input prior to parsing markdown.
RenderStrategyInterface::FILTER_OUTPUT constant Strategy used to filter the output of parsed markdown.
RenderStrategyInterface::MARKDOWN_XSS_URL Deprecated constant The URL for explaining Markdown and XSS; render strategies.
RenderStrategyInterface::NONE constant No render strategy.
RenderStrategyInterface::STRIP_INPUT constant Strategy used to remove HTML input prior to parsing markdown.
SettingsTrait::createSettingElement protected function Creates a setting element.
SettingsTrait::getDefaultSetting public function
SettingsTrait::getSetting public function
SettingsTrait::getSettingOverrides public function
SettingsTrait::getSettings public function
SettingsTrait::settingsKey public function 6
SettingsTrait::submitConfigurationForm public function
SettingsTrait::validateConfigurationForm public function 2
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.