You are here

class SyntaxHighlighterSettingsForm in Syntax Highlighter 8

Configure Syntax Highlighter settings.

Hierarchy

Expanded class hierarchy of SyntaxHighlighterSettingsForm

1 string reference to 'SyntaxHighlighterSettingsForm'
syntaxhighlighter.routing.yml in ./syntaxhighlighter.routing.yml
syntaxhighlighter.routing.yml

File

src/Form/SyntaxHighlighterSettingsForm.php, line 12

Namespace

Drupal\syntaxhighlighter\Form
View source
class SyntaxHighlighterSettingsForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'syntaxhighlighter_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'syntaxhighlighter.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('syntaxhighlighter.settings');
    $path = libraries_get_path('syntaxhighlighter');
    if (!$path) {
      drupal_set_message(t('The syntaxhighlighter javascript library is not found. Consult <a href=":readme">README.txt</a> for help on how to install it, then <a href=":reload">reload</a> this page.', [
        ':readme' => Url::fromUri('internal:/' . drupal_get_path('module', 'syntaxhighlighter') . '/README.txt')
          ->toString(),
        ':reload' => Url::FromRoute('syntaxhighlighter.settings.form')
          ->toString(),
      ]), 'error');
      return [];
    }

    // Group options to individually select SyntaxHighlighter brushes or to
    // autoload brushes.
    $form['syntaxhighlighter_brush_loading_options'] = [
      '#type' => 'fieldset',
      '#title' => t('SyntaxHighlighter brush loading configuration'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    $autoloader_available = file_exists($path . '/scripts/shAutoloader.js');
    $files = file_scan_directory($path . '/scripts', '/shBrush.*\\.js/');
    foreach ($files as $file) {
      $lang_options[$file->filename] = substr($file->name, 7);
    }
    ksort($lang_options);
    $form['syntaxhighlighter_brush_loading_options']['syntaxhighlighter_enabled_languages'] = [
      '#type' => 'checkboxes',
      '#title' => t('Enabled languages'),
      '#options' => $lang_options,
      '#default_value' => $config
        ->get('enabled_languages'),
      '#description' => t('Only the selected languages will be enabled and its corresponding required Javascript brush files loaded.') . ($autoloader_available ? ' ' . t('If you enable "Use autoloader" below, then the brushes are dynamically loaded on demand.') : ''),
      '#multicolumn' => [
        'width' => 3,
      ],
    ];
    if ($autoloader_available) {
      $form['syntaxhighlighter_brush_loading_options']['syntaxhighlighter_use_autoloader'] = [
        '#type' => 'checkbox',
        '#title' => t('Use autoloader'),
        '#default_value' => $config
          ->get('use_autoloader'),
        '#attached' => [
          'library' => 'syntaxhighlighter/check_all_languages',
        ],
      ];
    }
    else {
      $config
        ->set('use_autoloader', FALSE);
      $form['syntaxhighlighter_brush_loading_options']['syntaxhighlighter_use_autoloader'] = [
        '#type' => 'checkbox',
        '#title' => t('Use autoloader'),
        '#default_value' => FALSE,
        '#attributes' => [
          'disabled' => 'disabled',
        ],
        '#description' => t('Autoloader is not available, update to the latest version of the SyntaxHighlighter javascript library to get this functionality.'),
      ];
    }

    // Group SyntaxHighlighter theme, tag, and legacy support library options.
    $form['syntaxhighlighter_libconfig'] = [
      '#type' => 'fieldset',
      '#title' => t('SyntaxHighlighter library configuration'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    $files = file_scan_directory($path . '/styles', '/shTheme.*\\.css/', [
      'nomask' => '/(\\.\\.?|CVS|shThemeDefault.css)$/',
    ]);
    foreach ($files as $file) {
      $theme_options[$file->filename] = substr($file->name, 7);
    }
    ksort($theme_options);
    $theme_options = array_merge([
      'shThemeDefault.css' => 'Default',
    ], $theme_options);
    $form['syntaxhighlighter_libconfig']['syntaxhighlighter_theme'] = [
      '#type' => 'radios',
      '#title' => t('Theme'),
      '#description' => t('Choose a syntax highlight theme.'),
      '#options' => $theme_options,
      '#default_value' => $config
        ->get('theme'),
      '#multicolumn' => [
        'width' => 2,
      ],
    ];
    $form['syntaxhighlighter_libconfig']['syntaxhighlighter_tagname'] = [
      '#type' => 'textfield',
      '#title' => t('Tag name'),
      '#required' => TRUE,
      '#description' => t('Use different tag to markup code.'),
      '#default_value' => $config
        ->get('tagname'),
      '#size' => 10,
    ];
    $form['syntaxhighlighter_libconfig']['syntaxhighlighter_legacy_mode'] = [
      '#type' => 'radios',
      '#title' => t('Legacy mode'),
      '#description' => t('Enable pre-2.0 style markup support.'),
      '#options' => [
        t('Disabled'),
        t('Enabled'),
      ],
      '#default_value' => $config
        ->get('legacy_mode'),
    ];

    // Group SyntaxHighlighter JS/CSS code injection options.
    $form['syntaxhighlighter_inject_settings'] = [
      '#type' => 'fieldset',
      '#title' => t('SyntaxHighlighter js/css code inject settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    $user = \Drupal::currentUser();
    $has_php_access = $user
      ->hasPermission(SYNTAXHIGHLIGHTER_PHP_PERMISSION);
    if ((!$has_php_access || !function_exists('php_eval')) && $config
      ->get('inject') == SYNTAXHIGHLIGHTER_INJECT_PHP) {
      $form['syntaxhighlighter_inject'] = [
        '#type' => 'value',
        '#value' => SYNTAXHIGHLIGHTER_INJECT_PHP,
      ];
      $form['syntaxhighlighter_pages'] = [
        '#type' => 'value',
        '#value' => $config
          ->get('pages'),
      ];
      if (!$has_php_access) {
        $permissions = \Drupal::service('user.permissions')
          ->getPermissions();
        $messages[] = t('You do not have the "%permission" permission to change these settings.', [
          '%permission' => $permissions[SYNTAXHIGHLIGHTER_PHP_PERMISSION]['title'],
        ]);
      }
      if (!function_exists('php_eval')) {
        $messages[] = t('The "%module_name" module is disabled, re-enable the module to change these settings. Because the "%module_name" module is disabled, syntax highlighting is effectively disabled on every page.', [
          '%module_name' => t('PHP filter'),
        ]);
      }
      $items = [
        'items' => $messages,
        'type' => 'ul',
        'attributes' => [
          'class' => [
            'messages',
            'warning',
          ],
        ],
      ];
      $form['syntaxhighlighter_inject_settings']['syntaxhighlighter_messages'] = [
        '#type' => 'markup',
        '#markup' => theme('item_list', $items),
      ];
    }
    else {
      $options = [
        SYNTAXHIGHLIGHTER_INJECT_EXCEPT_LISTED => t('Inject on all pages except those listed'),
        SYNTAXHIGHLIGHTER_INJECT_IF_LISTED => t('Inject on only the listed pages'),
      ];
      $description = t("Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", [
        '%blog' => 'blog',
        '%blog-wildcard' => 'blog/*',
        '%front' => '<front>',
      ]);
      $title = t('Pages');
      if ($has_php_access && function_exists('php_eval')) {
        $options[SYNTAXHIGHLIGHTER_INJECT_PHP] = t('Inject if the following PHP code returns <code>TRUE</code> (PHP-mode, experts only)');
        $description .= ' ' . t('If the PHP-mode is chosen, enter PHP code between %php. Note that executing incorrect PHP-code can break your Drupal site.', [
          '%php' => '<?php ?>',
        ]);
        $title = t('Pages or PHP code');
      }
      else {

        // Show some friendly info message if PHP is not available because...
        if (!$has_php_access && !function_exists('php_eval')) {
          $permissions = \Drupal::service('user.permissions')
            ->getPermissions();
          $php_info_message = t('You need to have the "%permission" permission and enable the "%module_name" module to use PHP code here.', [
            '%permission' => $permissions[SYNTAXHIGHLIGHTER_PHP_PERMISSION]['title'],
            '%module_name' => t('PHP filter'),
          ]);
        }
        elseif (!$has_php_access) {
          $permissions = \Drupal::service('user.permissions')
            ->getPermissions();
          $php_info_message = t('You need to have the "%permission" permission to use PHP code here.', [
            '%permission' => $permissions[SYNTAXHIGHLIGHTER_PHP_PERMISSION]['title'],
          ]);
        }
        elseif (!function_exists('php_eval')) {
          $php_info_message = t('Enable the "%module_name" module to use PHP code here.', [
            '%module_name' => t('PHP filter'),
          ]);
        }
      }
      $form['syntaxhighlighter_inject_settings']['syntaxhighlighter_inject'] = [
        '#type' => 'radios',
        '#title' => t('Inject js/css code on specific pages'),
        '#options' => $options,
        '#default_value' => $config
          ->get('inject'),
      ];
      if (isset($php_info_message)) {
        $form['syntaxhighlighter_inject_settings']['syntaxhighlighter_inject']['#description'] = $php_info_message;
      }
      $form['syntaxhighlighter_inject_settings']['syntaxhighlighter_pages'] = [
        '#type' => 'textarea',
        '#title' => '<span class="element-invisible">' . $title . '</span>',
        '#default_value' => $config
          ->get('pages'),
        '#description' => $description,
      ];
    }
    $form['syntaxhighlighter_default_expressions'] = [
      '#type' => 'textarea',
      '#title' => t('Default expressions'),
      '#default_value' => $config
        ->get('default_expressions'),
      '#description' => t('Enter syntaxhihglighter default settings as javascript expressions, e.g. <code>@example</code>. To turn off clipboardSwf, use <code>@swfoff</code>. See the <a href=":link">syntaxhighlighter js lib doc page</a> for details. Note: these default settings affect the entire site unless they are overridden locally.', [
        '@example' => 'SyntaxHighlighter.defaults[\'auto-links\'] = true; SyntaxHighlighter.defaults[\'gutter\'] = false;',
        '@swfoff' => 'SyntaxHighlighter.config.clipboardSwf = undefined;',
        ':link' => 'http://alexgorbatchev.com/SyntaxHighlighter/',
      ]),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('syntaxhighlighter.settings');
    $enabled_languages = array_keys(array_filter($form_state
      ->getValue('syntaxhighlighter_enabled_languages')));
    $config
      ->set('enabled_languages', $enabled_languages);
    $config
      ->set('use_autoloader', $form_state
      ->getValue('syntaxhighlighter_use_autoloader'));
    $config
      ->set('theme', $form_state
      ->getValue('syntaxhighlighter_theme'));
    $config
      ->set('tagname', $form_state
      ->getValue('syntaxhighlighter_tagname'));
    $config
      ->set('legacy_mode', $form_state
      ->getValue('syntaxhighlighter_legacy_mode'));
    $config
      ->set('inject', $form_state
      ->getValue('syntaxhighlighter_inject'));
    $config
      ->set('pages', $form_state
      ->getValue('syntaxhighlighter_pages'));
    $config
      ->set('default_expressions', $form_state
      ->getValue('syntaxhighlighter_default_expressions'));
    $config
      ->save();
    _syntaxhighlighter_setup_autoloader_script($config);
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.
SyntaxHighlighterSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SyntaxHighlighterSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SyntaxHighlighterSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SyntaxHighlighterSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.