You are here

class SettingsController in Popup Maker - All popup types 8

Settings Controller to the popup maker module.

Hierarchy

Expanded class hierarchy of SettingsController

1 string reference to 'SettingsController'
popup_maker.services.yml in ./popup_maker.services.yml
popup_maker.services.yml
1 service uses SettingsController
popup_maker.settings_controller in ./popup_maker.services.yml
Drupal\popup_maker\Controller\SettingsController

File

src/Controller/SettingsController.php, line 19

Namespace

Drupal\popup_maker\Controller
View source
class SettingsController extends ControllerBase {

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The Config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * Popup Maker's website URL.
   *
   * @var string $popupMakerServiceURL
   */
  const POPUP_MAKER_SERVICE_URL = 'https://popupmaker.com/';

  /**
   * Popup Maker controller constructor.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   Stores runtime messages.
   * @param \Drupal\Core\Config\ConfigFactory $configFactory
   *   The config factory.
   * @param \Drupal\Core\Entity\EntityManager $entityManager
   *   Provides an interface for entity type managers.
   * @param \Drupal\Core\Entity\EntityTypeManager $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrfTokenGenerator
   *   Returns the CSRF token manager service.
   * @param \GuzzleHttp\Client $httpClient
   *   The HTTP client.
   * @param \Drupal\Core\Logger\LoggerChannelFactory $logger
   *   The Braintree Cashier logger channel.
   */
  public function __construct(MessengerInterface $messenger, ConfigFactory $configFactory, EntityManager $entityManager, EntityTypeManager $entityTypeManager, CsrfTokenGenerator $csrfTokenGenerator, Client $httpClient, LoggerChannelFactory $logger) {
    $this->messenger = $messenger;
    $this->configFactory = $configFactory;
    $this->entityManager = $entityManager;
    $this->entityTypeManager = $entityTypeManager;
    $this->csrfToken = $csrfTokenGenerator;
    $this->httpClient = $httpClient;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('messenger'), $container
      ->get('config.factory'), $container
      ->get('entity.manager'), $container
      ->get('entity_type.manager'), $container
      ->get('csrf_token'), $container
      ->get('http_client'), $container
      ->get('logger.factory'));
  }

  /**
   * Editing popup settings.
   */
  public function editPopupSettings() {
    $config = $this->configFactory
      ->get('popup_maker.settings');
    $settings = [
      'api_key' => $config
        ->get('api_key'),
      'popups' => $config
        ->get('popups'),
      'user' => $config
        ->get('user'),
      'popupSettings' => $config
        ->get('popupSettings'),
    ];
    $contentTypes = $this->entityManager
      ->getStorage('node_type')
      ->loadMultiple();
    $displayRules = [];
    if (!empty($contentTypes)) {
      foreach ($contentTypes as $key => $contentType) {
        $displayRules[$key] = [];
        $nodes = $this->entityTypeManager
          ->getListBuilder('node')
          ->getStorage()
          ->loadByProperties([
          'type' => $key,
        ]);
        foreach ($nodes as $node) {
          $displayRules[$key][$node
            ->id()] = $node
            ->getTitle();
        }
      }
    }
    return [
      '#theme' => 'popup_maker_settings',
      '#settings' => $settings,
      '#edit' => TRUE,
      '#editingPopupId' => (int) $_GET['id'],
      '#displayRules' => $displayRules,
      '#token' => $this->csrfToken
        ->get('popup_maker_api_key'),
      '#attached' => [
        'library' => [
          'popup_maker/popup_maker_admin',
        ],
      ],
    ];
  }

  /**
   * Functio to show the popup maker.
   */
  public function show() {
    $config = $this->configFactory
      ->get('popup_maker.settings');
    $settings = [
      'api_key' => $config
        ->get('api_key'),
      'popups' => $config
        ->get('popups'),
      'user' => $config
        ->get('user'),
      'popupSettings' => $config
        ->get('popupSettings'),
    ];
    return [
      '#theme' => 'popup_maker_settings',
      '#settings' => $settings,
      '#token' => $this->csrfToken
        ->get('popup_maker_api_key'),
      '#attached' => [
        'library' => [
          'popup_maker/popup_maker_admin',
        ],
      ],
    ];
  }

  /**
   * To update the popup.
   */
  public function updatePopup() {
    $id = $_POST['id'];
    $config = $this->configFactory
      ->getEditable('popup_maker.settings');
    $popupSettings = $config
      ->get('popupSettings');
    $popupSettings[$id]['displayOptions'] = $_POST['sgpm_rules'];
    $config
      ->set('popupSettings', $popupSettings)
      ->save();
    return $this
      ->redirect('popup_maker.settings.edit_popup_settings', [
      'id' => $id,
    ]);
  }

  /**
   * To refresh the popups.
   */
  public function refreshPopups() {
    $config = $this->configFactory
      ->get('popup_maker.settings');
    if ($this
      ->refreshData($config
      ->get('api_key'))) {
      $this->messenger
        ->addStatus('Popups list refreshed successfully');
    }
    return $this
      ->redirect('popup_maker.settings');
  }

  /**
   * To ypdate the API key.
   */
  public function updateApiKey() {
    if (!isset($_POST['sgpm-api-key-submit'])) {
      $this->messenger
        ->addError('Invalid request');
      return FALSE;
    }
    if (!$this->csrfToken
      ->validate($_POST['_csrf_token'], 'popup_maker_api_key')) {
      $this->messenger
        ->addError('Could not validate the security token');
      return FALSE;
    }
    if ($this
      ->refreshData($_POST['sgpm-api-key'])) {
      $this->configFactory
        ->getEditable('popup_maker.settings')
        ->set('api_key', $_POST['sgpm-api-key'])
        ->save();
      $this->messenger
        ->addStatus('New api key saved successfully');
    }
    return $this
      ->redirect('popup_maker.settings');
  }

  /**
   * To update the status of popup.
   */
  public function updateStatus() {
    if (isset($_POST['sgpm-disable-popup'])) {
      $this
        ->disablePopup();
    }
    if (isset($_POST['sgpm-enable-popup'])) {
      $this
        ->enablePopup();
    }
    return $this
      ->redirect('popup_maker.settings');
  }

  /**
   * To refresh the data of popup.
   */
  public function refreshData($apiKey) {
    if (empty($apiKey)) {
      $this->messenger
        ->addError('Api Key is required to connect to the service');
      return FALSE;
    }
    $data = [
      'apiKey' => $apiKey,
      'appname' => 'Drupal',
    ];
    $client = $this->httpClient;
    try {
      $request = $client
        ->post(SettingsController::POPUP_MAKER_SERVICE_URL . 'app/connect', [
        'form_params' => $data,
      ]);
      $data = json_decode($request
        ->getBody(), TRUE);
    } catch (RequestException $e) {
      $this->logger
        ->get('popup_maker')
        ->error($e);
      return FALSE;
    }
    $config = $this->configFactory
      ->getEditable('popup_maker.settings');
    if (!isset($data['isAuthenticate']) || !$data['isAuthenticate']) {
      $this->messenger
        ->addError('Please, provide a valid Api Key');
      return FALSE;
    }
    $config
      ->set('popups', array_reverse($data['popups'], TRUE))
      ->set('user', $data['user'])
      ->save();
    $popupSettings = $config
      ->get('popupSettings');
    if (empty($popupSettings)) {
      $popupSettings = [];
    }
    foreach ($data['popups'] as $popupId => $popup) {
      if (!isset($popupSettings[$popupId])) {
        $popupSettings[$popupId] = [
          'enabled' => 0,
          'displayOptions' => [],
        ];
      }
    }
    $config
      ->set('popupSettings', $popupSettings)
      ->save();
    $this->messenger
      ->addStatus('Data imported from service successfully');
    return TRUE;
  }

  /**
   * To disable the popup.
   */
  public function disablePopup() {
    if (!isset($_POST['id'])) {
      $this->messenger
        ->addError('Parameter "id" is required to disable a popup');
      return FALSE;
    }
    $id = abs(intval($_POST['id']));
    if ($id != $_POST['id']) {
      $this->messenger
        ->addError('Parameter "id" must be non negative integer');
      return FALSE;
    }
    $config = $this->configFactory
      ->getEditable('popup_maker.settings');
    $popupSettings = $config
      ->get('popupSettings');
    if (empty($popupSettings)) {
      $popupSettings = [];
    }
    if (!isset($popupSettings[$_POST['id']])) {
      $popupSettings[$_POST['id']] = [];
    }
    $popupSettings[$_POST['id']]['enabled'] = 0;
    $config
      ->set('popupSettings', $popupSettings)
      ->save();
    $this->messenger
      ->addStatus('Popup Disabled successfully');
  }

  /**
   * To enable the popup.
   */
  public function enablePopup() {
    if (!isset($_POST['id'])) {
      $this->messenger
        ->addError('Parameter "id" is required to disable a popup');
      return FALSE;
    }
    $id = abs(intval($_POST['id']));
    if ($id != $_POST['id']) {
      $this->messenger
        ->addError('Parameter "id" must be non negative integer');
      return FALSE;
    }
    $config = $this->configFactory
      ->getEditable('popup_maker.settings');
    $popupSettings = $config
      ->get('popupSettings');
    if (empty($popupSettings)) {
      $popupSettings = [];
    }
    if (!isset($popupSettings[$_POST['id']])) {
      $popupSettings[$_POST['id']] = [];
    }
    $popupSettings[$_POST['id']]['enabled'] = 1;
    $config
      ->set('popupSettings', $popupSettings)
      ->save();
    $this->messenger
      ->addStatus('Popup Enabled successfully');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
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 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.
SettingsController::$configFactory protected property The Config factory. Overrides ControllerBase::$configFactory
SettingsController::$entityManager protected property The entity manager. Overrides ControllerBase::$entityManager
SettingsController::$messenger protected property The Messenger service. Overrides MessengerTrait::$messenger
SettingsController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
SettingsController::disablePopup public function To disable the popup.
SettingsController::editPopupSettings public function Editing popup settings.
SettingsController::enablePopup public function To enable the popup.
SettingsController::POPUP_MAKER_SERVICE_URL constant Popup Maker's website URL.
SettingsController::refreshData public function To refresh the data of popup.
SettingsController::refreshPopups public function To refresh the popups.
SettingsController::show public function Functio to show the popup maker.
SettingsController::updateApiKey public function To ypdate the API key.
SettingsController::updatePopup public function To update the popup.
SettingsController::updateStatus public function To update the status of popup.
SettingsController::__construct public function Popup Maker controller constructor.
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.