You are here

class Settings in Avatar Kit 8

Configure avatar kit settings.

Hierarchy

Expanded class hierarchy of Settings

2 string references to 'Settings'
avatars.routing.yml in ./avatars.routing.yml
avatars.routing.yml
Settings::buildForm in src/Form/Settings.php
Form constructor.

File

src/Form/Settings.php, line 17

Namespace

Drupal\avatars\Form
View source
class Settings extends ConfigFormBase {

  /**
   * The avatar generator plugin manager.
   *
   * @var \Drupal\avatars\AvatarGeneratorPluginManagerInterface
   */
  protected $avatarGenerator;

  /**
   * Constructs a \Drupal\system\ConfigFormBase object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\avatars\AvatarGeneratorPluginManagerInterface $avatar_generator
   *   The avatar generator plugin manager.
   */
  public function __construct(ConfigFactoryInterface $config_factory, AvatarGeneratorPluginManagerInterface $avatar_generator) {
    parent::__construct($config_factory);
    $this->avatarGenerator = $avatar_generator;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $config = $this
      ->config('avatars.settings');

    // Define table.
    $headers = [
      'label' => $this
        ->t('Avatar Generator'),
      'type' => $this
        ->t('Type'),
      'plugin' => $this
        ->t('Plugin'),
      'settings' => $this
        ->t('Settings'),
      'enabled' => [
        'data' => $this
          ->t('Enabled'),
        'class' => [
          'checkbox',
        ],
      ],
      'weight' => $this
        ->t('Weight'),
      'operations' => $this
        ->t('Operations'),
    ];
    $form['avatar_generators_help'] = [
      '#prefix' => '<p>',
      '#markup' => $this
        ->t('A list of avatar generators to try for each user in order of preference.'),
      '#suffix' => '</p>',
    ];
    $form['avatar_generators'] = [
      '#type' => 'table',
      '#header' => $headers,
      '#empty' => $this
        ->t('No avatar generators found.'),
      '#attributes' => [
        'id' => 'avatar-generators',
      ],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'generator-weight',
        ],
      ],
    ];

    /** @var \Drupal\avatars\AvatarGeneratorInterface[] $instances */
    $instances = AvatarGenerator::loadMultiple();
    uasort($instances, '\\Drupal\\avatars\\Entity\\AvatarGenerator::sort');
    foreach ($instances as $instance) {
      $form['avatar_generators'][$instance
        ->id()] = [];
      $row =& $form['avatar_generators'][$instance
        ->id()];
      $row['#attributes']['class'][] = 'draggable';
      $definition = $instance
        ->getPlugin()
        ->getPluginDefinition();
      $row['label']['#markup'] = $instance
        ->label();
      $row['type']['#markup'] = $definition['dynamic'] ? $this
        ->t('Dynamic') : $this
        ->t('Static');
      $row['plugin']['#markup'] = $definition['label'];
      $row['settings'] = $instance
        ->getPlugin()
        ->settingsSummary();
      $row['enabled'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Enabled'),
        '#title_display' => 'invisible',
        '#default_value' => $instance
          ->status(),
        '#wrapper_attributes' => [
          'class' => [
            'checkbox',
          ],
        ],
      ];
      $row['weight'] = [
        '#type' => 'weight',
        '#title' => $this
          ->t('Weight'),
        '#title_display' => 'invisible',
        '#default_value' => $instance
          ->getWeight(),
        '#attributes' => [
          'class' => [
            'generator-weight',
          ],
        ],
      ];
      $operations = [];
      if ($instance
        ->access('update')) {
        $operations['edit'] = [
          'title' => $this
            ->t('Edit'),
          'weight' => 10,
          'url' => $instance
            ->toUrl('edit-form'),
        ];
      }
      if ($instance
        ->access('delete')) {
        $operations['delete'] = [
          'title' => $this
            ->t('Delete'),
          'weight' => 100,
          'url' => $instance
            ->toUrl('delete-form'),
        ];
      }
      $row['operations'] = [
        '#type' => 'operations',
        '#links' => $operations,
      ];
    }
    $form['refresh_interval']['#tree'] = TRUE;
    $intervals = $config
      ->get('refresh_interval');
    $form['refresh_interval']['dynamic'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Dynamic lifetime'),
      '#description' => $this
        ->t('How long dynamic avatars are cached before allowing refresh.'),
      '#default_value' => $intervals['dynamic'],
      '#step' => 60,
      '#min' => 0,
      '#field_suffix' => $this
        ->t('seconds'),
    ];

    /*
     * Keep unused avatars on file system (will use up more disk space)
     * Avatars must be purged manually if you change this settings.
     * Expire unused static avatars (will use up more network bandwidth)
     * */
    $form['refresh_interval']['static'] = [
      '#type' => 'unlimited_number',
      '#title' => $this
        ->t('Static lifetime'),
      '#description' => $this
        ->t('How long static avatars are cached. Only applies to avatars which are not the users preference.'),
      '#default_value' => $intervals['static'] < 1 ? UnlimitedNumber::UNLIMITED : $intervals['static'],
      '#step' => 60,
      '#min' => 60,
      '#field_suffix' => $this
        ->t('seconds'),
      '#options' => [
        'unlimited' => $this
          ->t('Never delete'),
        'limited' => $this
          ->t('Delete after'),
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('avatars.settings');

    // Generators are already sorted correctly.
    foreach ($form_state
      ->getValue('avatar_generators') as $id => $row) {

      /** @var \Drupal\avatars\AvatarGeneratorInterface $avatar_generator */
      $avatar_generator = AvatarGenerator::load($id);
      $avatar_generator
        ->setStatus($row['enabled'])
        ->setWeight($row['weight'])
        ->save();
    }
    Cache::invalidateTags([
      'avatar_preview',
    ]);
    $intervals = $form_state
      ->getValue('refresh_interval');
    if ($intervals['static'] == UnlimitedNumber::UNLIMITED) {
      $intervals['static'] = 0;
    }
    $config
      ->set('refresh_interval', [
      'dynamic' => $intervals['dynamic'],
      'static' => $intervals['static'],
    ]);
    $config
      ->save();
    $this
      ->messenger()
      ->addStatus(t('Settings saved.'));
  }

}

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.
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.
Settings::$avatarGenerator protected property The avatar generator plugin manager.
Settings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
Settings::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
Settings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
Settings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
Settings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
Settings::__construct public function Constructs a \Drupal\system\ConfigFormBase object. Overrides ConfigFormBase::__construct
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.