You are here

class ContentLinksForm in General Data Protection Regulation 8

Same name and namespace in other branches
  1. 8.2 src/Form/ContentLinksForm.php \Drupal\gdpr\Form\ContentLinksForm
  2. 3.0.x src/Form/ContentLinksForm.php \Drupal\gdpr\Form\ContentLinksForm

Class ContentLinksForm.

@package Drupal\gdpr\Form

Hierarchy

Expanded class hierarchy of ContentLinksForm

See also

\Drupal\link\Plugin\Field\FieldType\LinkItem

\Drupal\link\Plugin\Field\FieldWidget\LinkWidget

1 file declares its use of ContentLinksForm
gdpr.module in ./gdpr.module
Module file.
1 string reference to 'ContentLinksForm'
gdpr.routing.yml in ./gdpr.routing.yml
gdpr.routing.yml

File

src/Form/ContentLinksForm.php, line 19

Namespace

Drupal\gdpr\Form
View source
class ContentLinksForm extends ConfigFormBase {
  const GDPR_CONTENT_CONF_KEY = 'gdpr.content_mapping';

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('language_manager'));
  }

  /**
   * ContentLinksForm constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory.
   * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
   *   The language manager.
   */
  public function __construct(ConfigFactoryInterface $configFactory, LanguageManagerInterface $languageManager) {
    parent::__construct($configFactory);
    $this->languageManager = $languageManager;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      static::GDPR_CONTENT_CONF_KEY,
    ];
  }

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

  /**
   * Return an array of the required content labels keyed by machine name.
   *
   * @return array
   *   The required content.
   */
  public static function requiredContentList() {
    return [
      'privacy_policy' => t('Privacy policy'),
      'terms_of_use' => t('Terms of use'),
      'about_us' => t('About us'),
      'impressum' => t('Impressum'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#tree'] = TRUE;
    $form['description'] = [
      '#markup' => $this
        ->t('Enter internal paths e.g <strong>@internal_path</strong> or full URLs e.g <strong>@full_url</strong>', [
        '@internal_path' => '/privacy-policy',
        '@full_url' => 'https://www.example.com/termsofservice.pdf',
      ]),
    ];
    $form['links'] = [
      '#type' => 'container',
    ];
    $urls = $this
      ->loadUrls();

    /** @var \Drupal\Core\Language\LanguageInterface $language */
    foreach ($this->languageManager
      ->getLanguages() as $langCode => $language) {
      $form['links'][$langCode] = [
        '#type' => 'details',
        '#title' => $language
          ->getName(),
      ];
      foreach (static::requiredContentList() as $key => $label) {
        $form['links'][$langCode][$key] = [
          '#type' => 'textfield',
          '#title' => $label,
          '#process_default_value' => FALSE,
          '#element_validate' => [
            [
              static::class,
              'validateUriElement',
            ],
          ],
          '#default_value' => isset($urls[$langCode][$key]) ? $urls[$langCode][$key] : NULL,
        ];
      }
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->hasValue('links')) {

      /** @var array $links */
      $links = $form_state
        ->getValue('links', []);
      $config = $this->configFactory
        ->getEditable(static::GDPR_CONTENT_CONF_KEY);
      $config
        ->set('links', $links)
        ->save();
    }
    parent::submitForm($form, $form_state);
  }

  /**
   * Load the stored URLs as displayable strings.
   *
   * @return array
   *   The loaded URLs.
   */
  protected function loadUrls() {
    $config = $this
      ->config(static::GDPR_CONTENT_CONF_KEY)
      ->get('links');
    if (NULL === $config || !\is_array($config)) {
      $config = [];
    }
    foreach ($config as $langCode => $links) {
      foreach ($links as $key => $link) {
        $config[$langCode][$key] = static::getUriAsDisplayableString($link);
      }
    }
    return $config;
  }

  /**
   * Gets the URI without the 'internal:' or 'entity:' scheme.
   *
   * The following two forms of URIs are transformed:
   * - 'entity:' URIs: to entity autocomplete ("label (entity id)") strings;
   * - 'internal:' URIs: the scheme is stripped.
   *
   * This method is the inverse of ::getUserEnteredStringAsUri().
   *
   * @param string $uri
   *   The URI to get the displayable string for.
   *
   * @return string
   *   The displayable URI.
   *
   * @see static::getUserEnteredStringAsUri()
   */
  protected static function getUriAsDisplayableString($uri) {
    $scheme = \parse_url($uri, PHP_URL_SCHEME);

    // By default, the displayable string is the URI.
    $displayableString = $uri;

    // A different displayable string may be chosen in case of the 'internal:'
    // or 'entity:' built-in schemes.
    if ($scheme === 'internal') {
      $uriReference = \explode(':', $uri, 2)[1];

      // @todo '<front>' is valid input for BC reasons, may be removed by
      //   https://www.drupal.org/node/2421941
      $path = \parse_url($uri, PHP_URL_PATH);
      if ($path === '/') {
        $uriReference = '<front>' . \substr($uriReference, 1);
      }
      $displayableString = $uriReference;
    }
    return $displayableString;
  }

  /**
   * Form element validation handler for the 'uri' element.
   *
   * Disallows saving inaccessible or untrusted URLs.
   */
  public static function validateUriElement($element, FormStateInterface $form_state, $form) {
    $uri = static::getUserEnteredStringAsUri($element['#value']);
    $form_state
      ->setValueForElement($element, $uri);

    // If getUserEnteredStringAsUri() mapped the entered value to a 'internal:'
    // URI , ensure the raw value begins with '/', '?' or '#'.
    // @todo '<front>' is valid input for BC reasons, may be removed by
    //   https://www.drupal.org/node/2421941
    if (\parse_url($uri, PHP_URL_SCHEME) === 'internal' && 0 !== strpos($element['#value'], '<front>') && !\in_array($element['#value'][0], [
      '/',
      '?',
      '#',
    ], TRUE)) {
      $form_state
        ->setError($element, t('Manually entered paths should start with /, ? or #.'));
      return;
    }
  }

  /**
   * Gets the user-entered string as a URI.
   *
   * The following two forms of input are mapped to URIs:
   * - entity autocomplete ("label (entity id)") strings: to 'entity:' URIs;
   * - strings without a detectable scheme: to 'internal:' URIs.
   *
   * This method is the inverse of ::getUriAsDisplayableString().
   *
   * @param string $string
   *   The user-entered string.
   *
   * @return string
   *   The URI, if a non-empty $uri was passed.
   *
   * @see static::getUriAsDisplayableString()
   */
  protected static function getUserEnteredStringAsUri($string) {

    // By default, assume the entered string is an URI.
    $uri = $string;
    if (!empty($string) && \parse_url($string, PHP_URL_SCHEME) === NULL) {

      // @todo '<front>' is valid input for BC reasons, may be removed by
      //   https://www.drupal.org/node/2421941
      // - '<front>' -> '/'
      // - '<front>#foo' -> '/#foo'
      if (\strpos($string, '<front>') === 0) {
        $string = '/' . \substr($string, \strlen('<front>'));
      }
      $uri = 'internal:' . $string;
    }
    return $uri;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
ContentLinksForm::$languageManager protected property The language manager.
ContentLinksForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
ContentLinksForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
ContentLinksForm::GDPR_CONTENT_CONF_KEY constant
ContentLinksForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
ContentLinksForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ContentLinksForm::getUriAsDisplayableString protected static function Gets the URI without the 'internal:' or 'entity:' scheme.
ContentLinksForm::getUserEnteredStringAsUri protected static function Gets the user-entered string as a URI.
ContentLinksForm::loadUrls protected function Load the stored URLs as displayable strings.
ContentLinksForm::requiredContentList public static function Return an array of the required content labels keyed by machine name.
ContentLinksForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
ContentLinksForm::validateUriElement public static function Form element validation handler for the 'uri' element.
ContentLinksForm::__construct public function ContentLinksForm constructor. Overrides ConfigFormBase::__construct
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.
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.