You are here

class StepsBlock in Opigno Learning path 3.x

Same name and namespace in other branches
  1. 8 src/Plugin/Block/StepsBlock.php \Drupal\opigno_learning_path\Plugin\Block\StepsBlock

Provides a 'article' block.

Plugin annotation


@Block(
  id = "lp_steps_block",
  admin_label = @Translation("LP Steps block")
)

Hierarchy

Expanded class hierarchy of StepsBlock

File

src/Plugin/Block/StepsBlock.php, line 26

Namespace

Drupal\opigno_learning_path\Plugin\Block
View source
class StepsBlock extends BlockBase implements ContainerFactoryPluginInterface, TrustedCallbackInterface {
  use LearningPathAchievementTrait;

  /**
   * Service "opigno_group_manager.content_types.manager" definition.
   *
   * @var \Drupal\opigno_group_manager\OpignoGroupContentTypesManager
   */
  protected $opignoGroupContentTypesManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, OpignoGroupContentTypesManager $opigno_group_content_types_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->opignoGroupContentTypesManager = $opigno_group_content_types_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('opigno_group_manager.content_types.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {

    // Every new route this block will rebuild.
    return Cache::mergeContexts(parent::getCacheContexts(), [
      'route',
      'opigno_current:group_id',
      'opigno_current:content_id',
      'opigno_current:activity_id',
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getGroupByRouteOrContext() {

    // By default a getCurrentGroupId gets a group by orute parameter.
    return Group::load($this
      ->getCurrentGroupId());
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $group = $this
      ->getGroupByRouteOrContext();
    $steps = $this
      ->getStepsByGroup($group);

    // Get group context.
    $cid = $this
      ->getCurrentGroupContentId();
    if (!$cid) {
      return [];
    }
    if (!$steps) {
      return [];
    }
    $steps = array_values($steps);
    if (!$steps) {
      return [];
    }
    foreach ($steps as $index => &$step) {
      $step['step_previous'] = $steps[$index - 1] ?? FALSE;
      $step['step_first'] = $index === 0;
      $step['step_last'] = count($steps) - 1 === $index;
    }
    return [
      '#type' => 'container',
      [
        '#theme' => 'opigno_lp_step_activity',
        'title' => [
          '#markup' => $group
            ->label(),
        ],
        'steps' => $steps,
        '#pre_render' => [
          [
            $this,
            'processModuleList',
          ],
        ],
      ],
    ];
  }

  /**
   * Process module list.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  public function processModuleList($elements) {
    foreach ($elements["steps"] as &$step) {
      $link = $this
        ->getLinkToStart($step);
      $step = [
        // @todo seems it is a bad idea to generate a thme based on typology.
        '#theme' => sprintf('%s_%s', 'opigno_lp_step', strtolower($step["typology"])),
        'step' => $step,
        '#state' => $this
          ->getState($step),
        '#current' => $this
          ->isModuleCurrent($step),
        '#link' => FALSE,
        '#locked' => !$link,
        '#pre_render' => [
          [
            $this,
            'processActivityList',
          ],
        ],
      ];
    }
    return $elements;
  }

  /**
   * Converts a step array to a renderable array.
   */
  public function processActivityList($elements) {
    $meta = CacheableMetadata::createFromRenderArray($elements);
    if (in_array($elements["step"]['typology'], [
      'Module',
    ])) {
      [
        $training,
        $course,
        $module,
      ] = $this
        ->getTrainingAndCourse($elements["step"]);
      [
        $activities,
        $attempts,
      ] = $this
        ->getActivities($training, $course, $module);
      $meta
        ->addCacheableDependency($attempts);
      $activity_status = $this
        ->getActivityStatus($activities, $attempts, $module);
      $activity_passed = array_filter($activity_status, static function ($status) {
        return 'passed' === $status;
      });
      $next = FALSE;
      $current_module = $this
        ->isModuleCurrent($elements["step"]);
      foreach ($activities as &$activity) {
        $meta
          ->addCacheableDependency($activity);
        $state = $activity_status[$activity
          ->id()] ?? 'pending';
        $current = $this
          ->getCurrentActivityId() === $activity
          ->id();
        $is_link = in_array($state, [
          'passed',
        ]);
        $activity = [
          '#theme' => 'opigno_lp_step_module_activity',
          '#activity' => $activity,
          "#state" => $state,
          '#current' => $current,
          '#link' => $current_module && ($current || $is_link || $next) ? Url::fromRoute('opigno_module.group.answer_form', [
            'group' => $training
              ->id(),
            'opigno_activity' => $activity
              ->id(),
            'opigno_module' => $module
              ->id(),
          ])
            ->toString() : FALSE,
          '#pre_render' => [
            [
              $this,
              'processActivityStatus',
            ],
          ],
        ];
        $next = $is_link && $current;
      }
      $elements['activity_counter'] = [
        '#markup' => $this
          ->t('%passed/%total activities done', [
          '%passed' => count($activity_passed),
          '%total' => count($activity_status),
        ]),
      ];
      $elements['activities'] = $activities;
    }
    $meta
      ->applyTo($elements);
    return $elements;
  }

  /**
   * Activity pre-processor.
   */
  public function processActivityStatus($elements) {
    $elements['title'] = [
      '#markup' => $elements['#activity']
        ->label(),
    ];
    return $elements;
  }

  /**
   * Get the current active module.
   */
  protected function isModuleCurrent(array $step) : bool {
    return $this
      ->getCurrentGroupContentId() == $step['cid'];
  }

  /**
   * Get the state of the module.
   */
  protected function getState(array $step) : ?string {
    return opigno_learning_path_get_step_status($step, $this
      ->currentUser()
      ->id(), TRUE);
  }

  /**
   * Take a module link.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   * @todo Previously it can be take or next link, it should be researched.
   *
   */
  protected function getLink($step) : Url {
    $content_step = OpignoGroupManagedContent::load($step['cid']);

    /** @var \Drupal\opigno_group_manager\ContentTypeBase $content_type */
    $content_type = $this->opignoGroupContentTypesManager
      ->createInstance($content_step
      ->getGroupContentTypeId());
    $step_url = $content_type
      ->getStartContentUrl($content_step
      ->getEntityId(), $this
      ->getCurrentGroupId());
    return Url::fromRoute($step_url
      ->getRouteName(), $step_url
      ->getRouteParameters());
  }

  /**
   * {@inheritdoc}
   */
  public function getLinkToStart($step) : ?Url {
    $link = NULL;

    /** @var \Drupal\opigno_learning_path\Controller\LearningPathStepsController $controller */
    $controller = \Drupal::classResolver(LearningPathStepsController::class);
    if ($step['step_first']) {
      return $this
        ->getLink($step);
    }
    else {
      $group_id = $this
        ->getCurrentGroupId();
      $parent_content_id = $step["step_previous"]["cid"];
      $group = Group::load($group_id);
      $course_entity = OpignoGroupManagedContent::load($parent_content_id);
      $resp = $controller
        ->getNextStep($group, $course_entity, FALSE);
      if (($resp["#type"] ?? FALSE) != 'html_tag') {

        // @todo an access to link should be checked here.
        //
        // if the response is a html type, that means the function returns
        // a redirect message, because we reuse the legacy code
        // that actually is not developed for the checking an access to route.
        return Url::fromRoute('opigno_learning_path.steps.next', [
          'group' => $group_id,
          'parent_content' => $parent_content_id,
        ]);
      }
    }
    return $link;
  }

  /**
   * Loading a training/course and module entities by step array.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function getTrainingAndCourse($step) : array {
    $step_training = $this
      ->getStepTraining($step);
    if (!$step_training) {
      $step_training = [
        'cid' => $step['cid'],
        'id' => FALSE,
      ];
    }

    /** @var \Drupal\opigno_group_manager\OpignoGroupContent $content */
    $content = $this
      ->entityTypeManager()
      ->getStorage('opigno_group_content')
      ->load($step_training["cid"]);
    $training = $content instanceof OpignoGroupManagedContent ? $content
      ->getGroup() : NULL;
    $course = $step_training["id"] ? $this
      ->entityTypeManager()
      ->getStorage('group')
      ->load($step_training["id"]) : FALSE ?: NULL;
    $module = $this
      ->entityTypeManager()
      ->getStorage('opigno_module')
      ->load($step["id"]) ?: NULL;
    return [
      $training,
      $course,
      $module,
    ];
  }

  /**
   * If the module has a course as a parent object just return it.
   */
  protected function getStepTraining(array $elements) {
    return $elements["parent"] ?? FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return [
      'processModuleList',
      'processActivityList',
      'processActivityStatus',
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 2
BlockPluginInterface::BLOCK_LABEL_VISIBLE constant Indicates the block label (title) should be displayed to end users.
BlockPluginTrait::$transliteration protected property The transliteration service.
BlockPluginTrait::access public function
BlockPluginTrait::baseConfigurationDefaults protected function Returns generic default configuration for block plugins.
BlockPluginTrait::blockAccess protected function Indicates whether the block should be shown. 16
BlockPluginTrait::blockForm public function 16
BlockPluginTrait::blockSubmit public function 13
BlockPluginTrait::blockValidate public function 3
BlockPluginTrait::buildConfigurationForm public function Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. Aliased as: traitBuildConfigurationForm
BlockPluginTrait::calculateDependencies public function
BlockPluginTrait::defaultConfiguration public function 19
BlockPluginTrait::getConfiguration public function 1
BlockPluginTrait::getMachineNameSuggestion public function 1
BlockPluginTrait::getPreviewFallbackString public function 3
BlockPluginTrait::label public function
BlockPluginTrait::setConfiguration public function
BlockPluginTrait::setConfigurationValue public function
BlockPluginTrait::setTransliteration public function Sets the transliteration service.
BlockPluginTrait::submitConfigurationForm public function Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit().
BlockPluginTrait::transliteration protected function Wraps the transliteration service.
BlockPluginTrait::validateConfigurationForm public function Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). 1
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginTrait::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginTrait::$initializedContextConfig protected property Tracks whether the context has been initialized from configuration.
ContextAwarePluginTrait::getCacheMaxAge public function 7
ContextAwarePluginTrait::getCacheTags public function 4
ContextAwarePluginTrait::getContext public function
ContextAwarePluginTrait::getContextDefinition public function
ContextAwarePluginTrait::getContextDefinitions public function
ContextAwarePluginTrait::getContextMapping public function
ContextAwarePluginTrait::getContexts public function
ContextAwarePluginTrait::getContextValue public function
ContextAwarePluginTrait::getContextValues public function
ContextAwarePluginTrait::getPluginDefinition abstract protected function 1
ContextAwarePluginTrait::setContext public function 1
ContextAwarePluginTrait::setContextMapping public function
ContextAwarePluginTrait::setContextValue public function
ContextAwarePluginTrait::validateContexts public function
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
LearningPathAchievementTrait::$entityTypeManager protected property
LearningPathAchievementTrait::$routeMatch protected property
LearningPathAchievementTrait::currentUser public function Gets a current user.
LearningPathAchievementTrait::entityTypeManager protected function Retrieves the entity type manager.
LearningPathAchievementTrait::getActivities public function Gets the activities list by the group and module.
LearningPathAchievementTrait::getActivityStatus public function Gets a statuses of activities.
LearningPathAchievementTrait::getCurrentActivityId protected function Current Opigno Activity Id.
LearningPathAchievementTrait::getCurrentGroupContentId protected function Current Group Content Id.
LearningPathAchievementTrait::getCurrentGroupId protected function Current Group Id.
LearningPathAchievementTrait::getStepsByGroup public function Retrieves the steps by group.
LearningPathAchievementTrait::getTargetAttempt protected function Get last or best user attempt for Module.
LearningPathAchievementTrait::routeMatch protected function Retrieves the currently active route match object.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::getFormClass().
PluginWithFormsTrait::hasFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::hasFormClass().
StepsBlock::$opignoGroupContentTypesManager protected property Service "opigno_group_manager.content_types.manager" definition.
StepsBlock::build public function Builds and returns the renderable array for this block plugin. Overrides BlockPluginInterface::build
StepsBlock::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
StepsBlock::getCacheContexts public function Overrides ContextAwarePluginTrait::getCacheContexts
StepsBlock::getGroupByRouteOrContext public function
StepsBlock::getLink protected function Take a module link.
StepsBlock::getLinkToStart public function
StepsBlock::getState protected function Get the state of the module.
StepsBlock::getStepTraining protected function If the module has a course as a parent object just return it.
StepsBlock::getTrainingAndCourse protected function Loading a training/course and module entities by step array.
StepsBlock::isModuleCurrent protected function Get the current active module.
StepsBlock::processActivityList public function Converts a step array to a renderable array.
StepsBlock::processActivityStatus public function Activity pre-processor.
StepsBlock::processModuleList public function Process module list.
StepsBlock::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
StepsBlock::__construct public function Overrides BlockPluginTrait::__construct
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.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.