subscriptions-2.0.x-dev/src/Form/ConfigForm.php
src/Form/ConfigForm.php
<?php
namespace Drupal\subscriptions\Form;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\Query\QueryException;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines a settings form for the Subscriptions module.
*/
class ConfigForm extends ConfigFormBase {
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The subscription type plugin manager service.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $pluginManager;
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames(): array {
return ['subscriptions.settings'];
}
/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'subscriptions_settings';
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('entity_type.manager'),
$container->get('plugin.manager.subscriptions.subscription_type'),
);
}
/**
* Constructor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* @param \Drupal\Component\Plugin\PluginManagerInterface $plugin_manager
* The subscription type plugin manager service.
*/
public function __construct(
ConfigFactoryInterface $config_factory,
EntityTypeManagerInterface $entity_type_manager,
PluginManagerInterface $plugin_manager
) {
parent::__construct($config_factory);
$this->entityTypeManager = $entity_type_manager;
$this->pluginManager = $plugin_manager;
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
$form['#title'] = $this->t('Subscriptions');
$form['links_container'] = [
'#type' => 'fieldset',
'#title' => $this->t('Links'),
];
$form['links_container']['links'] = [
'#theme' => 'item_list',
'#items' => [],
];
$form['links_container']['links']['#items']['permissions'] = [
'#type' => 'link',
'#title' => $this->t('Permissions'),
'#url' => Url::fromRoute('user.admin_permissions'),
];
$form['links_container']['links']['#items']['bulk'] = [
'#type' => 'link',
'#title' => $this->t('Bulk subscribing/unsubscribing'),
'#url' => Url::fromRoute('entity.user.collection'),
];
$form['links_container']['links']['#items']['cron'] = [
'#type' => 'link',
'#title' => $this->t('Run cron manually'),
'#url' => Url::fromRoute('system.run_cron'),
'#options' => [
'query' => [
'destination' => Url::fromRoute('subscriptions.config')->toString(),
],
],
];
$form['links_container']['links']['#items']['my_subscriptions'] = [
'#type' => 'link',
'#title' => $this->t('My subscriptions'),
'#url' => Url::fromRoute('subscriptions.user_subscriptions', ['user' => $this->currentUser()->id()]),
];
// Build the subscription type counts table.
$form['table'] = [
'#type' => 'table',
'#header' => [
$this->t('Subscription type'),
$this->t('Count'),
],
'#rows' => [],
'#empty' => $this->t('No subscriptions found.'),
];
// Try to get subscription counts from the database.
try {
$subscription_storage = $this->entityTypeManager->getStorage('subscription');
$query = $subscription_storage->getAggregateQuery()
->groupBy('type')
->aggregate('sid', 'count');
$results = $query->execute();
// Key the results by type.
$results = array_combine(array_column($results, 'type'), array_values($results));
}
// Catch plugin or query exceptions.
catch (InvalidPluginDefinitionException | PluginNotFoundException | QueryException $exception) {
// Set the query results to an empty array.
$results = [];
// Display an error message to the user.
$this->messenger()->addError($this->t('An error has occurred while loading subscriptions.'));
// Log the exception.
$this->logger('subscriptions')->critical('@type was thrown while loading the Subscription entity type storage plugin: @message', [
'@type' => get_class($exception),
'@message' => $exception->getMessage(),
]);
}
// Get the subscription type plugin definitions.
$plugin_definitions = $this->pluginManager->getDefinitions();
// Build a list of all subscription types using the plugin list keys and
// query result keys.
$subscription_type_id_list = array_merge(array_keys($plugin_definitions), array_keys($results));
$subscription_type_id_list = array_unique($subscription_type_id_list);
// Sort the list.
natcasesort($subscription_type_id_list);
// Build each table row.
foreach ($subscription_type_id_list as $subscription_type_id) {
$form['table'][$subscription_type_id]['type'] = [
'#type' => 'item',
'#markup' => '',
];
// If the plugin definition exists, use its label.
if (!empty($plugin_definitions[$subscription_type_id])) {
$form['table'][$subscription_type_id]['type']['#markup'] = $plugin_definitions[$subscription_type_id]['label'];
}
// If the plugin definition does not exist, display an error in place of
// the label, and add an error class to the row.
else {
$form['table'][$subscription_type_id]['type']['#markup'] = $this->t('Subscription type plugin %type could not be found!', [
'%type' => $subscription_type_id,
]);
$form['table'][$subscription_type_id]['#attributes']['class'][] = 'color-error';
}
// Get the subscription type count, or default to 0.
$form['table'][$subscription_type_id]['count'] = [
'#type' => 'item',
'#markup' => $results[$subscription_type_id]['sid_count'] ?? 0,
];
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
// Set values from the form.
$form_state->cleanValues();
$config = $this->config('subscriptions.settings');
$config->save();
}
}
