You are here

class NodeViewCountSettingsForm in Node view count 8

Configure nodeviewcount settings.

Hierarchy

Expanded class hierarchy of NodeViewCountSettingsForm

1 string reference to 'NodeViewCountSettingsForm'
nodeviewcount.routing.yml in ./nodeviewcount.routing.yml
nodeviewcount.routing.yml

File

src/Form/NodeViewCountSettingsForm.php, line 18

Namespace

Drupal\nodeviewcount\Form
View source
class NodeViewCountSettingsForm extends ConfigFormBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity display repository.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
   */
  protected $entityDisplayRepository;

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

  /**
   * The cache tags invalidator.
   *
   * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
   */
  protected $cacheTagsInvalidator;

  /**
   * Constructs a NodeViewCountSettingsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
   *   The entity display repository.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator
   *   The cache tags invalidator.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, EntityDisplayRepositoryInterface $entity_display_repository, DateFormatterInterface $date_formatter, CacheTagsInvalidatorInterface $cache_tags_invalidator) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entity_type_manager;
    $this->entityDisplayRepository = $entity_display_repository;
    $this->dateFormatter = $date_formatter;
    $this->cacheTagsInvalidator = $cache_tags_invalidator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('entity_type.manager'), $container
      ->get('entity_display.repository'), $container
      ->get('date.formatter'), $container
      ->get('cache_tags.invalidator'));
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('nodeviewcount.settings');
    $form['node_types'] = [
      '#title' => $this
        ->t('Node types'),
      '#description' => $this
        ->t('Choose content types to count views.'),
      '#type' => 'checkboxes',
      '#options' => $this
        ->getNodeTypesOptions(),
      '#default_value' => $config
        ->get('node_types'),
    ];
    $form['view_modes'] = [
      '#title' => $this
        ->t('View modes'),
      '#description' => $this
        ->t('Choose node view modes to count views.'),
      '#type' => 'checkboxes',
      '#options' => $this
        ->getNodeViewModesOptions(),
      '#default_value' => $config
        ->get('view_modes'),
    ];
    $form['user_roles'] = [
      '#title' => $this
        ->t('User roles'),
      '#description' => $this
        ->t('Choose user roles for counting node views.'),
      '#type' => 'checkboxes',
      '#options' => $this
        ->getRoleNamesOptions($config
        ->get('excluded_user_roles')),
      '#default_value' => $config
        ->get('user_roles'),
    ];
    $form['excluded_user_roles'] = [
      '#title' => $this
        ->t('Excluded user roles'),
      '#description' => $this
        ->t('Choose user roles which will be excluded from node views counting.'),
      '#type' => 'checkboxes',
      '#options' => $this
        ->getRoleNamesOptions($config
        ->get('user_roles')),
      '#default_value' => $config
        ->get('excluded_user_roles'),
    ];
    $form['logs_life_time'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Discard node views logs older than'),
      '#default_value' => $config
        ->get('logs_life_time'),
      '#options' => $this
        ->getLogsLifeTimeOptions(),
      '#description' => $this
        ->t('Older log entries will be automatically discarded, (Requires a correctly configured <a href="@cron">cron maintenance task</a>.). Pick Never if you dont want logs to be deleted.', [
        '@cron' => Url::fromRoute('system.status')
          ->toString(),
      ]),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * Get all possible node type names.
   *
   * Data returned in format applicable for '#options' key of form element.
   * Keys are ids of node types, values are labels (human readable names)
   * of node types.
   *
   * @return array
   *   All possible node type names for nodes.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  private function getNodeTypesOptions() {
    $node_types_options = [];

    /** @var \Drupal\node\NodeTypeInterface[] $node_types */
    $node_types = $this->entityTypeManager
      ->getStorage('node_type')
      ->loadMultiple();
    foreach ($node_types as $node_id => $node_type) {
      $node_types_options[$node_id] = $node_type
        ->label();
    }
    return $node_types_options;
  }

  /**
   * Get all possible view mode names for nodes.
   *
   * Data returned in format applicable for '#options' key of form element.
   * Keys are ids of view modes, values are labels (human readable names)
   * of view modes.
   *
   * @return array
   *   All possible view mode names for nodes.
   */
  private function getNodeViewModesOptions() {
    $view_modes_options = [];
    $view_modes = $this->entityDisplayRepository
      ->getViewModes('node');
    foreach ($view_modes as $view_mode_id => $view_mode) {
      $view_modes_options[$view_mode_id] = $view_mode['label'];
    }
    return $view_modes_options;
  }

  /**
   * Get user role names that are not in excluded user roles.
   *
   * Data returned in format applicable for '#options' key of form element.
   * Keys are ids of role names, values are labels (human readable names)
   * of roles.
   *
   * @param array $excluded_user_roles
   *   Excluded user roles.
   *
   * @return array
   *   User role names that are not in excluded user roles.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  private function getRoleNamesOptions(array $excluded_user_roles) {
    $roles_options = [];

    /** @var \Drupal\user\RoleInterface[] $roles */
    $roles = $this->entityTypeManager
      ->getStorage('user_role')
      ->loadMultiple();
    foreach ($roles as $role_id => $role) {
      if (!in_array($role_id, $excluded_user_roles)) {
        $roles_options[$role_id] = $role
          ->label();
      }
    }
    return $roles_options;
  }

  /**
   * Get logs lifetime options.
   *
   * Data returned in format applicable for '#options' key of form element.
   * Keys are time intervals in ms, values are human readable time spans.
   *
   * @return array
   *   Logs lifetime options.
   */
  private function getLogsLifeTimeOptions() {
    $life_time_options = [
      0 => $this
        ->t('Never'),
    ];
    $time_intervals = [
      86400,
      604800,
      1209600,
      2592000,
      15552000,
      31536000,
    ];
    foreach ($time_intervals as $time_interval) {
      $life_time_options[$time_interval] = $this->dateFormatter
        ->formatInterval($time_interval);
    }
    return $life_time_options;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $counting_user_roles = array_filter($form_state
      ->getValue('user_roles'));
    $excluded_user_roles = array_filter($form_state
      ->getValue('excluded_user_roles'));
    foreach ($counting_user_roles as $key => $couting_user_role) {
      if ($couting_user_role) {
        unset($excluded_user_roles[$key]);
      }
    }
    $this
      ->config('nodeviewcount.settings')
      ->set('node_types', array_keys(array_filter($form_state
      ->getValue('node_types'))))
      ->set('view_modes', array_keys(array_filter($form_state
      ->getValue('view_modes'))))
      ->set('user_roles', array_keys($counting_user_roles))
      ->set('excluded_user_roles', array_keys($excluded_user_roles))
      ->set('logs_life_time', (int) $form_state
      ->getValue('logs_life_time'))
      ->save(TRUE);
    $this->cacheTagsInvalidator
      ->invalidateTags([
      'node_view',
    ]);
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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.
NodeViewCountSettingsForm::$cacheTagsInvalidator protected property The cache tags invalidator.
NodeViewCountSettingsForm::$dateFormatter protected property The date formatter service.
NodeViewCountSettingsForm::$entityDisplayRepository protected property The entity display repository.
NodeViewCountSettingsForm::$entityTypeManager protected property The entity type manager.
NodeViewCountSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
NodeViewCountSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
NodeViewCountSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
NodeViewCountSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
NodeViewCountSettingsForm::getLogsLifeTimeOptions private function Get logs lifetime options.
NodeViewCountSettingsForm::getNodeTypesOptions private function Get all possible node type names.
NodeViewCountSettingsForm::getNodeViewModesOptions private function Get all possible view mode names for nodes.
NodeViewCountSettingsForm::getRoleNamesOptions private function Get user role names that are not in excluded user roles.
NodeViewCountSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
NodeViewCountSettingsForm::__construct public function Constructs a NodeViewCountSettingsForm object. Overrides ConfigFormBase::__construct
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.