You are here

class DashboardController in Opigno dashboard 3.x

Same name and namespace in other branches
  1. 8 src/Controller/DashboardController.php \Drupal\opigno_dashboard\Controller\DashboardController

Controller for all the actions of the Learning Path manager app.

Hierarchy

Expanded class hierarchy of DashboardController

File

src/Controller/DashboardController.php, line 23

Namespace

Drupal\opigno_dashboard\Controller
View source
class DashboardController extends ControllerBase {

  /**
   * The block service.
   *
   * @var \Drupal\opigno_dashboard\BlockServiceInterface
   */
  protected $blockService;

  /**
   * The database connection manager.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * The users entity query.
   *
   * @var \Drupal\Core\Entity\Query\QueryInterface|null
   */
  protected $userEntityQuery = NULL;

  /**
   * DashboardController constructor.
   *
   * @param \Drupal\opigno_dashboard\BlockServiceInterface $block_service
   *   Opigno dashboard blocks service.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user account.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   */
  public function __construct(BlockServiceInterface $block_service, AccountInterface $account, MessengerInterface $messenger, Connection $database, ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager) {
    $this->blockService = $block_service;
    $this->currentUser = $account;
    $this->messenger = $messenger;
    $this->database = $database;
    $this->configFactory = $config_factory;
    try {
      $this->userEntityQuery = $entity_type_manager
        ->getStorage('user')
        ->getQuery();
    } catch (PluginNotFoundException|InvalidPluginDefinitionException $e) {
      watchdog_exception('opigno_dashboard_exception', $e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('opigno_dashboard.block'), $container
      ->get('current_user'), $container
      ->get('messenger'), $container
      ->get('database'), $container
      ->get('config.factory'), $container
      ->get('entity_type.manager'));
  }

  /**
   * Get the default blocks.
   *
   * @return array
   *   The default blocks.
   */
  public function dashboardDefaultBlocks() {
    return [];
  }

  /**
   * Returns positioning.
   *
   * @param int|string|null $uid
   *   The user ID to get the positioning for.
   * @param bool $default
   *   Should the default positioning be used or not.
   * @param bool $user_default
   *   Should the user default positioning be used or not.
   *
   * @return array|\Symfony\Component\HttpFoundation\JsonResponse
   *   Blocks positioning.
   */
  public function getPositioning($uid = NULL, bool $default = FALSE, bool $user_default = FALSE) {
    return $this->blockService
      ->getPositioning($uid, $default, $user_default);
  }

  /**
   * Sets the positioning.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request object.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The response.
   */
  public function setPositioning(Request $request) : JsonResponse {
    $datas = json_decode($request
      ->getContent());

    // Remove the first column.
    unset($datas->positions[0]);
    try {
      $this->database
        ->merge('opigno_dashboard_positioning')
        ->key([
        'uid' => $this->currentUser
          ->id(),
      ])
        ->fields([
        'columns' => (int) $datas->columns,
      ])
        ->fields([
        'positions' => json_encode($datas->positions),
      ])
        ->execute();
    } catch (\Exception $e) {
      watchdog_exception('opigno_dashboard_exception', $e);
    }
    return new JsonResponse(NULL, Response::HTTP_OK);
  }

  /**
   * Returns blocks contents.
   */
  public function getBlocksContents() {
    $data = $this->blockService
      ->getDashboardBlocksContents();
    return new JsonResponse([
      'blocks' => $data['blocks'],
      'drupalSettings' => $data['attachments']['drupalSettings'] ?? [],
    ]);
  }

  /**
   * Returns the default positioning.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The default positioning.
   */
  public function getDefaultPositioning() : JsonResponse {
    $positioning = $this->blockService
      ->getPositioning(NULL, TRUE);
    return new JsonResponse([
      'positions' => $positioning['positions'],
      'columns' => $positioning['columns'],
    ], Response::HTTP_OK);
  }

  /**
   * Sets default positioning.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The JSON response.
   */
  public function setDefaultPositioning(Request $request) : JsonResponse {
    $datas = json_decode($request
      ->getContent());
    unset($datas->positions[0]);

    // Fix critical symbols.
    if (!empty($datas->positions)) {
      foreach ($datas->positions as &$position) {
        if (!empty($position)) {
          foreach ($position as &$block) {
            $block->admin_label = str_replace("'", "`", $block->admin_label);
          }
        }
      }
    }
    try {
      $config = $this->configFactory
        ->getEditable('opigno_dashboard.default.settings');
      $config
        ->set('positions', json_encode($datas->positions));
      $config
        ->set('columns', (int) $datas->columns);
      $config
        ->save();
    } catch (\Exception $e) {
      watchdog_exception('opigno_dashboard_exception', $e);
      $this->messenger
        ->addMessage($e
        ->getMessage(), 'error');
    }
    return new JsonResponse();
  }

  /**
   * Restore dashboard settings to defaults for the current user.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The JSON response.
   */
  public function restoreToDefaultAll() : JsonResponse {
    $positioning = $this->blockService
      ->getPositioning(NULL, TRUE, TRUE);
    unset($positioning['positions'][0]);
    if (!$this->userEntityQuery instanceof QueryInterface) {
      return new JsonResponse(NULL, 400);
    }
    $uids = $this->userEntityQuery
      ->execute();
    unset($uids[0]);
    if (!$uids) {
      return new JsonResponse(NULL, 400);
    }
    foreach ($uids as $uid) {
      try {
        $this->database
          ->merge('opigno_dashboard_positioning')
          ->key([
          'uid' => $uid,
        ])
          ->fields([
          'columns' => (int) $positioning['columns'],
          'positions' => json_encode($positioning['positions']),
        ])
          ->execute();
      } catch (\Exception $e) {
        watchdog_exception('opigno_dashboard_exception', $e);
      }
    }
    return new JsonResponse();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
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::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.
ControllerBase::state protected function Returns the state storage service.
DashboardController::$blockService protected property The block service.
DashboardController::$database protected property The database connection manager.
DashboardController::$userEntityQuery protected property The users entity query.
DashboardController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
DashboardController::dashboardDefaultBlocks public function Get the default blocks.
DashboardController::getBlocksContents public function Returns blocks contents.
DashboardController::getDefaultPositioning public function Returns the default positioning.
DashboardController::getPositioning public function Returns positioning.
DashboardController::restoreToDefaultAll public function Restore dashboard settings to defaults for the current user.
DashboardController::setDefaultPositioning public function Sets default positioning.
DashboardController::setPositioning public function Sets the positioning.
DashboardController::__construct public function DashboardController constructor.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.