You are here

public static function Style::parseStylesFormValue in Drupal 10

Parses the line-based (for form) style configuration.

@internal This method is public only to allow the CKEditor 4 to 5 upgrade path to reuse this logic. Mark this private in https://www.drupal.org/i/3239012.

Parameters

string $form_value: A string containing >=1 lines with on each line a CSS selector targeting 1 tag with >=1 classes, a pipe symbol and a label. An example of a single line: `p.foo.bar|Foo bar paragraph`.

Return value

array The parsed equivalent: a list of arrays with each containing:

  • label: the label after the pipe symbol, with whitespace trimmed
  • element: the CKEditor 5 element equivalent of the tag + classes

See also

\Drupal\ckeditor5\Plugin\CKEditor4To5Upgrade\Core::mapCKEditor4SettingsToCKEditor5Configuration()

1 call to Style::parseStylesFormValue()
Core::mapCKEditor4SettingsToCKEditor5Configuration in core/modules/ckeditor5/src/Plugin/CKEditor4To5Upgrade/Core.php

File

core/modules/ckeditor5/src/Plugin/CKEditor5Plugin/Style.php, line 106

Class

Style
CKEditor 5 Style plugin configuration.

Namespace

Drupal\ckeditor5\Plugin\CKEditor5Plugin

Code

public static function parseStylesFormValue(string $form_value) : array {
  $unparseable_lines = [];
  $lines = explode("\n", $form_value);
  $styles = [];
  foreach ($lines as $index => $line) {
    if (empty(trim($line))) {
      continue;
    }

    // Parse the line.
    [
      $selector,
      $label,
    ] = array_map('trim', explode('|', $line));

    // Validate the selector.
    $selector_matches = [];

    // @see https://www.w3.org/TR/CSS2/syndata.html#:~:text=In%20CSS%2C%20identifiers%20(including%20element,hyphen%20followed%20by%20a%20digit
    if (!preg_match('/^([a-z][0-9a-zA-Z\\-]*)((\\.[a-zA-Z0-9\\x{00A0}-\\x{FFFF}\\-_]+)+)$/u', $selector, $selector_matches)) {
      $unparseable_lines[$index + 1] = $line;
      continue;
    }

    // Parse selector into tag + classes and normalize.
    $tag = $selector_matches[1];
    $classes = array_filter(explode('.', $selector_matches[2]));
    $normalized = HTMLRestrictions::fromString(sprintf('<%s class="%s">', $tag, implode(' ', $classes)));
    $styles[] = [
      'label' => $label,
      'element' => $normalized
        ->toCKEditor5ElementsArray()[0],
    ];
  }
  return [
    $styles,
    $unparseable_lines,
  ];
}