You are here

class DataPolicyAgreement in Data Policy 8

Class DataPolicyAgreement.

Hierarchy

Expanded class hierarchy of DataPolicyAgreement

1 string reference to 'DataPolicyAgreement'
data_policy.routing.yml in ./data_policy.routing.yml
data_policy.routing.yml

File

src/Form/DataPolicyAgreement.php, line 20

Namespace

Drupal\data_policy\Form
View source
class DataPolicyAgreement extends FormBase {

  /**
   * The Data Policy consent manager.
   *
   * @var \Drupal\data_policy\DataPolicyConsentManagerInterface
   */
  protected $dataPolicyConsentManager;

  /**
   * The redirect destination helper.
   *
   * @var \Drupal\Core\Routing\RedirectDestinationInterface
   */
  protected $destination;

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * DataPolicyAgreement constructor.
   *
   * @param \Drupal\data_policy\DataPolicyConsentManagerInterface $data_policy_manager
   *   The Data Policy consent manager.
   * @param \Drupal\Core\Routing\RedirectDestinationInterface $destination
   *   The redirect destination helper.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   */
  public function __construct(DataPolicyConsentManagerInterface $data_policy_manager, RedirectDestinationInterface $destination, DateFormatterInterface $date_formatter) {
    $this->dataPolicyConsentManager = $data_policy_manager;
    $this->destination = $destination;
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('data_policy.manager'), $container
      ->get('redirect.destination'), $container
      ->get('date.formatter'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->dataPolicyConsentManager
      ->addCheckbox($form);
    $this->dataPolicyConsentManager
      ->saveConsent($this
      ->currentUser()
      ->id(), 'visit');

    // Add a message that the data policy was updated.
    $entity_ids = $this->dataPolicyConsentManager
      ->getEntityIdsFromConsentText();
    $revisions = $this->dataPolicyConsentManager
      ->getRevisionsByEntityIds($entity_ids);
    $timestamps = array_map(function (DataPolicyInterface $revision) {
      return $revision
        ->getChangedTime();
    }, $revisions);
    $timestamp = max($timestamps);
    $date = $this->dateFormatter
      ->format($timestamp, 'html_date');
    $form['date'] = [
      '#theme' => 'status_messages',
      '#message_list' => [
        'info' => [
          [
            '#type' => 'html_tag',
            '#tag' => 'strong',
            '#value' => $this
              ->t('Our data policy has been updated on %date', [
              '%date' => $date,
            ]),
          ],
        ],
      ],
      '#weight' => -2,
    ];
    if (!empty($this
      ->config('data_policy.data_policy')
      ->get('enforce_consent'))) {
      $form['data_policy']['#weight'] = 1;
      $link = Link::createFromRoute($this
        ->t('the account cancellation'), 'entity.user.cancel_form', [
        'user' => $this
          ->currentUser()
          ->id(),
      ]);
      $form['not_agree'] = [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this
          ->t('Agreement to the data policy is required for continue using this platform. If you do not agree with the data policy, you will be guided to @url process.', [
          '@url' => $link
            ->toString(),
        ]),
        '#theme_wrappers' => [
          'form_element',
        ],
        '#weight' => -1,
      ];
    }
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValue('data_policy');
    $result = [];
    foreach ($values as $name => $value) {
      $result[$name] = [
        'value' => $value,
        'required' => $form['account']['data_policy'][$name]['#required'],
        'entity_id' => (int) filter_var($name, FILTER_SANITIZE_NUMBER_INT),
        'state' => !empty($values[$name]),
      ];
    }
    $this->dataPolicyConsentManager
      ->saveConsent($this
      ->currentUser()
      ->id(), 'submit', $result);
    foreach ($result as $item) {

      // If the user does not agree and it is enforced, we will redirect to
      // the cancel account page.
      if ($item['required'] && !$item['value']) {
        $this
          ->getRequest()->query
          ->remove('destination');
        $form_state
          ->setRedirect('entity.user.cancel_form', [
          'user' => $this
            ->currentUser()
            ->id(),
        ]);
      }
    }

    // If the user agrees or does not agree (but it is not enforced), check if
    // we should redirect to the front page.
    if ($this->destination
      ->get() === '/data-policy-agreement') {
      $form_state
        ->setRedirect('<front>');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $errors = $form_state
      ->getErrors();
    if (!empty($errors)) {
      $form_state
        ->clearErrors();
      foreach ($errors as $id => $error) {

        /** @var \Drupal\Core\StringTranslation\TranslatableMarkup $g */
        if (strpos($id, 'data_policy') !== FALSE) {
          $name = Markup::create($error
            ->getArguments()['@name']);
          $form_state
            ->setErrorByName($id, t('@name field is required.', [
            '@name' => $name,
          ]));
          continue;
        }
        $form_state
          ->setErrorByName($id, $error);
      }
    }
    parent::validateForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DataPolicyAgreement::$dataPolicyConsentManager protected property The Data Policy consent manager.
DataPolicyAgreement::$dateFormatter protected property The date formatter service.
DataPolicyAgreement::$destination protected property The redirect destination helper.
DataPolicyAgreement::buildForm public function Form constructor. Overrides FormInterface::buildForm
DataPolicyAgreement::create public static function Instantiates a new instance of this class. Overrides FormBase::create
DataPolicyAgreement::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DataPolicyAgreement::submitForm public function Form submission handler. Overrides FormInterface::submitForm
DataPolicyAgreement::validateForm public function Form validation handler. Overrides FormBase::validateForm
DataPolicyAgreement::__construct public function DataPolicyAgreement constructor.
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::config protected function Retrieves a configuration object.
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.