You are here

class AddServices in TacJS 8.6

Same name and namespace in other branches
  1. 8.3 src/Form/Steps/AddServices.php \Drupal\tacjs\Form\Steps\AddServices
  2. 8.4 src/Form/Steps/AddServices.php \Drupal\tacjs\Form\Steps\AddServices
  3. 8.5 src/Form/Steps/AddServices.php \Drupal\tacjs\Form\Steps\AddServices

Class AddServices.

@package Drupal\tacjs\Form

Hierarchy

Expanded class hierarchy of AddServices

1 string reference to 'AddServices'
tacjs.routing.yml in ./tacjs.routing.yml
tacjs.routing.yml

File

src/Form/Steps/AddServices.php, line 15

Namespace

Drupal\tacjs\Form\Steps
View source
class AddServices extends ConfigFormBase {

  /**
   * The tarteaucitron.js services.
   *
   * @var array
   */
  protected $content;

  /**
   * Constructs a new AddServices.
   *
   */
  public function __construct() {
    $this->content = $this
      ->getContent();
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('tacjs.settings');
    $form['services'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this
        ->t('Add Services'),
      '#title_display' => 'invisible',
    ];
    foreach ($this->content as $type => $services) {
      $form['service']['type_' . $type] = [
        '#type' => 'details',
        '#title' => Unicode::ucfirst($type),
        '#group' => 'services',
      ];
      foreach ($services as $service => $value) {
        $form['service']['type_' . $type]['service_' . $service . '_status'] = [
          '#type' => 'checkbox',
          '#title' => $value['about']['name'],
          '#default_value' => $config
            ->get('services.' . $service . '.status'),
        ];
        $form['service']['type_' . $type]['details_' . $service] = [
          '#type' => 'fieldset',
          '#title' => 'Configuration',
          '#states' => [
            'visible' => [
              ':input[name="service_' . $service . '_status"]' => [
                'checked' => TRUE,
              ],
            ],
          ],
        ];
        $form['service']['type_' . $type]['details_' . $service]['service_' . $service . '_readMore'] = [
          '#type' => 'textarea',
          '#title' => $this
            ->t('More info'),
          '#default_value' => $config
            ->get('services.' . $service . '.readMore'),
        ];
        $form['service']['type_' . $type]['details_' . $service]['service_' . $service . '_needConsent'] = [
          '#type' => 'checkbox',
          '#title' => $this
            ->t('Need consent'),
          '#default_value' => $config
            ->get('services.' . $service . '.needConsent'),
        ];
        if (preg_match_all('/tarteaucitron.user.([A-z]+)[\\s]+=[\\s]+[\\]?[\\"]?[\']?###([^.]+)###/m', $value['code']['js'] ?: (is_array($value['code']['html']) ? '' : $value['code']['html']), $match)) {
          for ($i = 0; $i < count($match[1]); $i++) {
            $form['service']['type_' . $type]['details_' . $service]['user_' . $match[1][$i]] = [
              '#type' => 'textfield',
              '#title' => $match[1][$i],
              '#default_value' => $config
                ->get('user.' . $match[1][$i]),
              '#title_display' => 'invisible',
              '#maxlength' => 255,
              '#attributes' => [
                'placeholder' => $match[2][$i],
              ],
            ];
          }
        }
      }
    }

    // Workaround for #3170835: Uncaught TypeError null user
    // See https://github.com/AmauriC/tarteaucitron.js/pull/394
    $form['service']['type_analytic']['user_multiplegtagUa']['#attributes']['placeholder'] = 'UA-XXXXXXXX-X, UA-XXXXXXXX-X, UA-XXXXXXXX-X';

    // Workaround for #3204238: Uncaught TypeError null user
    // See https://www.drupal.org/project/tacjs/issues/3204238
    $form['service']['type_api']['user_googleFonts']['#attributes']['placeholder'] = 'My Font, My Other:300,700';
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    foreach ($this->content as $type => $services) {
      foreach ($services as $service => $value) {
        $form_state
          ->setValue('service_' . $service . '_status', $form_state
          ->getValue('service_' . $service . '_status') ? TRUE : FALSE);
        $form_state
          ->setValue('service_' . $service . '_needConsent', $form_state
          ->getValue('service_' . $service . '_needConsent') ? TRUE : FALSE);
        if (preg_match_all('/tarteaucitron.user.([A-z]+)[\\s]+=[\\s]+[\\]?[\\"]?[\']?###([^.]+)###/m', $value['code']['js'] ?: (is_array($value['code']['html']) ? '' : $value['code']['html']), $match)) {
          for ($i = 0; $i < count($match[1]); $i++) {
            $form_state
              ->setValue('user_' . $match[1][$i], $form_state
              ->getValue('user_' . $match[1][$i]) ?: NULL);
          }
        }
      }
    }
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('tacjs.settings');
    foreach ($this->content as $type => $services) {
      foreach ($services as $service => $value) {
        $config
          ->set('services.' . $service, [
          "status" => $form_state
            ->getValue('service_' . $service . '_status'),
          "needConsent" => $form_state
            ->getValue('service_' . $service . '_needConsent'),
          "readMore" => $form_state
            ->getValue('service_' . $service . '_readMore'),
          "readmoreLink" => $form_state
            ->getValue('service_' . $service . '_readmoreLink'),
        ]);
        if (preg_match_all('/tarteaucitron.user.([A-z]+)[\\s]+=[\\s]+[\\]?[\\"]?[\']?###([^.]+)###/m', $value['code']['js'] ?: (is_array($value['code']['html']) ? '' : $value['code']['html']), $match)) {
          for ($i = 0; $i < count($match[1]); $i++) {
            if ($form_state
              ->getValue('user_' . $match[1][$i])) {
              $config
                ->set('user.' . $match[1][$i], $form_state
                ->getValue('user_' . $match[1][$i]));
            }
            else {
              $config
                ->clear('user.' . $match[1][$i]);
            }
          }
        }
      }
    }
    $config
      ->save();
    parent::submitForm($form, $form_state);
  }

  /**
   * Helper function for the tacjs.add_services form.
   *
   * Default tarteaucitron.js services.
   *
   * You can copy content directly from the following URL:
   * https://opt-out.ferank.eu/json.php
   *
   * @return array
   */
  protected function getContent() {

    // Get the module base path.
    $relative_path = dirname(__DIR__, 3);

    // Get the content.json file from the base path.
    $content_json_path = $relative_path . '/assets/data/content.json';

    // Load file content.
    $content_json = file_get_contents($content_json_path);
    return Json::decode($content_json);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AddServices::$content protected property The tarteaucitron.js services.
AddServices::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
AddServices::getContent protected function Helper function for the tacjs.add_services form.
AddServices::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
AddServices::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AddServices::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
AddServices::validateForm public function Form validation handler. Overrides FormBase::validateForm
AddServices::__construct public function Constructs a new AddServices. Overrides ConfigFormBase::__construct
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
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.
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.