You are here

class DashboardController in Opigno dashboard 8

Same name and namespace in other branches
  1. 3.x 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

1 file declares its use of DashboardController
opigno_dashboard.module in ./opigno_dashboard.module
Contains opigno_dashboard.module.

File

src/Controller/DashboardController.php, line 13

Namespace

Drupal\opigno_dashboard\Controller
View source
class DashboardController extends ControllerBase {
  public function dashboardDefaultBlocks() {
    return [];
  }

  /**
   * Returns positioning.
   */
  public function getPositioning($uid = NULL, $default = FALSE, $user_default = FALSE) {
    if (empty($uid)) {
      $current_user = \Drupal::currentUser();
      if (!$current_user) {
        return new JsonResponse(NULL, Response::HTTP_BAD_REQUEST);
      }
      $uid = $current_user
        ->id();
    }
    $availables = \Drupal::service('opigno_dashboard.block')
      ->getAvailableBlocks();
    $connection = \Drupal::database();

    // Get default configuration.
    $config_default = $this
      ->config('opigno_dashboard.default.settings');
    $default_positions = json_decode($config_default
      ->get('positions'), TRUE);
    $default_columns = $config_default
      ->get('columns');
    if ($default) {
      $positions = $default_positions;
      $columns = $default_columns;
    }
    else {
      $query = $connection
        ->select('opigno_dashboard_positioning', 'p')
        ->fields('p', [
        'columns',
        'positions',
      ])
        ->condition('p.uid', $uid);
      $result = $query
        ->execute()
        ->fetchObject();
      $positions = FALSE;
      if (!empty($result->positions)) {
        $positions = json_decode($result->positions, TRUE);
      }
      $columns = !empty($result->columns) ? $result->columns : 3;
    }
    if (!$positions) {
      if (!empty($default_positions)) {
        $positions = $default_positions;
        $columns = $default_columns;
      }
      else {
        $positions = json_decode(OPIGNO_DASHBOARD_DEFAULT_CONFIG, TRUE);
        $columns = 3;
      }
    }

    // Get mandatory blocks.
    $config = $this
      ->config('opigno_dashboard.settings');
    $mandatory_blocks = $config
      ->get('blocks');
    if (!empty($mandatory_blocks)) {
      $mandatory_blocks = array_filter($mandatory_blocks, function ($block) {
        return $block['available'] && $block['mandatory'];
      });
    }

    // Keep all mandatory blocks.
    $mandatory = !empty($mandatory_blocks) ? $mandatory_blocks : [];

    // Remove blocks not availables.
    $availables_keys = [];
    foreach ($availables as $available) {
      $availables_keys[$available['id']] = $available['id'];
    }
    foreach ($positions as $key1 => $column) {
      foreach ($column as $key2 => $row) {
        if (!in_array($row['id'], $availables_keys)) {
          unset($positions[$key1][$key2]);
          continue;
        }

        // Filter unused mandatory blocks.
        if (!empty($mandatory_blocks) && isset($mandatory_blocks[$row['id']])) {
          unset($mandatory_blocks[$row['id']]);
        }

        // Add mandatory property to positions blocks.
        $positions[$key1][$key2]['mandatory'] = $mandatory && array_key_exists($row['id'], $mandatory) ? TRUE : FALSE;
      }
    }

    // Remove block already used.
    foreach ($availables as $key => $value) {
      foreach ($positions as $column) {
        foreach ($column as $row) {
          if (isset($row['id']) && isset($value['id']) && $row['id'] == $value['id']) {
            unset($availables[$key]);
          }
        }
      }

      // Save mandatory blocks key from "availables" array.
      if (!empty($mandatory_blocks) && array_key_exists($value['id'], $mandatory_blocks)) {
        $mandatory_blocks[$value['id']]['availables_key'] = $key;
      }
    }
    if (!$user_default) {
      $entities = array_merge([
        array_values($availables),
      ], $positions);
      $positions = $entities ? $entities : array_merge([
        array_values($availables),
      ], [
        [],
        [],
        [],
      ]);
    }

    // Add unused mandatory blocks.
    if (!empty($mandatory_blocks)) {
      foreach ($mandatory_blocks as $id => $mandatory_block) {
        if (!empty($mandatory_block['availables_key'])) {
          array_unshift($positions[1], [
            'admin_label' => isset($availables[$mandatory_block['availables_key']]['admin_label']) ? $availables[$mandatory_block['availables_key']]['admin_label'] : '',
            'id' => $id,
            'mandatory' => TRUE,
          ]);
        }
      }
    }
    $columns = !empty($columns) ? $columns : 3;
    $this
      ->clearEmptyPositions($positions, $availables_keys);
    if ($default) {
      return [
        'positions' => $positions,
        'columns' => $columns,
      ];
    }
    else {
      return new JsonResponse([
        'positions' => $positions,
        'columns' => $columns,
      ], Response::HTTP_OK);
    }
  }

  /**
   * Clear empty positions.
   */
  private function clearEmptyPositions(array &$positions, array $availables_keys) {
    foreach ($positions as $c_key => $columns) {
      if (!is_array($columns)) {
        continue;
      }
      foreach ($columns as $key => $position) {
        if (!is_array($columns)) {
          continue;
        }

        // Unset empty arrays and removed blocks.
        if (!isset($position['id']) || isset($position['id']) && !in_array($position['id'], $availables_keys)) {
          unset($positions[$c_key][$key]);
        }
      }

      // Reset array keys.
      $positions[$c_key] = array_values($positions[$c_key]);
    }
  }

  /**
   * Sets positioning.
   */
  public function setPositioning(Request $request) {
    $datas = json_decode($request
      ->getContent());
    $connection = \Drupal::database();

    // Remove first column.
    unset($datas->positions[0]);
    $connection
      ->merge('opigno_dashboard_positioning')
      ->key([
      'uid' => \Drupal::currentUser()
        ->id(),
    ])
      ->fields([
      'columns' => (int) $datas->columns,
    ])
      ->fields([
      'positions' => json_encode($datas->positions),
    ])
      ->execute();
    return new JsonResponse(NULL, Response::HTTP_OK);
  }

  /**
   * Returns blocks contents.
   */
  public function getBlocksContents() {
    $blocks = \Drupal::service('opigno_dashboard.block')
      ->getDashboardBlocksContents();
    return new JsonResponse([
      'blocks' => $blocks,
    ], Response::HTTP_OK);
  }

  /**
   * Returns user default positioning.
   */
  public function getUserDefaultPositioning() {
    $positioning = $this
      ->getPositioning(NULL, TRUE, TRUE);
    return $positioning;
  }

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

  /**
   * Sets default positioning.
   */
  public function setDefaultPositioning(Request $request) {
    $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 = \Drupal::configFactory()
        ->getEditable('opigno_dashboard.default.settings');
      $config
        ->set('positions', json_encode($datas->positions));
      $config
        ->set('columns', (int) $datas->columns);
      $config
        ->save();
    } catch (\Exception $e) {
      \Drupal::logger('opigno_dashboard')
        ->error($e
        ->getMessage());
      \Drupal::messenger()
        ->addMessage($e
        ->getMessage(), 'error');
    }
    return new JsonResponse(NULL, Response::HTTP_OK);
  }

  /**
   *
   */
  public function restoreToDefaultAll() {
    $positioning = $this
      ->getPositioning(NULL, TRUE, TRUE);
    unset($positioning['positions'][0]);
    $connection = \Drupal::database();
    $uids = \Drupal::entityQuery('user')
      ->execute();
    unset($uids[0]);
    if ($uids) {
      foreach ($uids as $uid) {
        $connection
          ->merge('opigno_dashboard_positioning')
          ->key([
          'uid' => $uid,
        ])
          ->fields([
          'columns' => (int) $positioning['columns'],
          'positions' => json_encode($positioning['positions']),
        ])
          ->execute();
      }
    }
    return new JsonResponse(NULL, Response::HTTP_OK);
  }

}

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::$entityManager protected property The entity manager.
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 40
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.
DashboardController::clearEmptyPositions private function Clear empty positions.
DashboardController::dashboardDefaultBlocks public function
DashboardController::getBlocksContents public function Returns blocks contents.
DashboardController::getDefaultPositioning public function Returns default positioning.
DashboardController::getPositioning public function Returns positioning.
DashboardController::getUserDefaultPositioning public function Returns user default positioning.
DashboardController::restoreToDefaultAll public function
DashboardController::setDefaultPositioning public function Sets default positioning.
DashboardController::setPositioning public function Sets positioning.
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.
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.