You are here

protected function StylesCombo::generateStylesSetSetting in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/ckeditor/src/Plugin/CKEditorPlugin/StylesCombo.php \Drupal\ckeditor\Plugin\CKEditorPlugin\StylesCombo::generateStylesSetSetting()
  2. 9 core/modules/ckeditor/src/Plugin/CKEditorPlugin/StylesCombo.php \Drupal\ckeditor\Plugin\CKEditorPlugin\StylesCombo::generateStylesSetSetting()

Builds the "stylesSet" configuration part of the CKEditor JS settings.

Parameters

string $styles: The "styles" setting.

Return value

array|false An array containing the "stylesSet" configuration, or FALSE when the syntax is invalid.

See also

getConfig()

File

core/modules/ckeditor/src/Plugin/CKEditorPlugin/StylesCombo.php, line 125

Class

StylesCombo
Defines the "stylescombo" plugin.

Namespace

Drupal\ckeditor\Plugin\CKEditorPlugin

Code

protected function generateStylesSetSetting($styles) {
  $styles_set = [];

  // Early-return when empty.
  $styles = trim($styles);
  if (empty($styles)) {
    return $styles_set;
  }
  $styles = str_replace([
    "\r\n",
    "\r",
  ], "\n", $styles);
  foreach (explode("\n", $styles) as $style) {
    $style = trim($style);

    // Ignore empty lines in between non-empty lines.
    if (empty($style)) {
      continue;
    }

    // Validate syntax: element[.class...]|label pattern expected.
    if (!preg_match('@^ *[a-zA-Z0-9-]+ *(\\.[a-zA-Z0-9_-]+ *)*\\| *.+ *$@', $style)) {
      return FALSE;
    }

    // Parse.
    [
      $selector,
      $label,
    ] = explode('|', $style);
    $classes = explode('.', $selector);
    $element = array_shift($classes);

    // Build the data structure CKEditor's stylescombo plugin expects.
    // @see https://ckeditor.com/docs/ckeditor4/latest/guide/dev_howtos_styles.html
    $configured_style = [
      'name' => trim($label),
      'element' => trim($element),
    ];
    if (!empty($classes)) {
      $configured_style['attributes'] = [
        'class' => implode(' ', array_map('trim', $classes)),
      ];
    }
    $styles_set[] = $configured_style;
  }
  return $styles_set;
}