You are here

class OpignoUserSelectionController in Opigno Learning path 3.x

Returns responses for Opigno User Selection routes.

Hierarchy

Expanded class hierarchy of OpignoUserSelectionController

1 string reference to 'OpignoUserSelectionController'
opigno_user_selection.routing.yml in modules/opigno_user_selection/opigno_user_selection.routing.yml
modules/opigno_user_selection/opigno_user_selection.routing.yml

File

modules/opigno_user_selection/src/Controller/OpignoUserSelectionController.php, line 21

Namespace

Drupal\opigno_user_selection\Controller
View source
class OpignoUserSelectionController extends ControllerBase {

  /**
   * Service "request_stack" definition.
   *
   * @var \Symfony\Component\HttpFoundation\Request|null
   */
  protected $currentRequest;

  /**
   * Service "group.membership_loader" definition.
   *
   * @var \Drupal\group\GroupMembershipLoaderInterface
   */
  protected $groupMembershipLoader;

  /**
   * {@inheritdoc}
   */
  public function __construct(RequestStack $request_stack, GroupMembershipLoaderInterface $membership_loader) {
    $this->currentRequest = $request_stack
      ->getCurrentRequest();
    $this->groupMembershipLoader = $membership_loader;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('request_stack'), $container
      ->get('group.membership_loader'));
  }

  /**
   * {@inheritdoc}
   *
   * @opigno_deprecated
   */
  protected function getEntityField(EntityInterface $entity, string $field_name) {

    /** @var \Drupal\Core\Entity\FieldableEntityInterface $user */
    if ($entity
      ->hasField($field_name) && !($field = $entity
      ->get($field_name))
      ->isEmpty()) {
      if (($child_entity = $field->entity) instanceof EntityInterface) {
        return $child_entity;
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   *
   * @opigno_deprecated
   */
  public function getuserAvatar($user) {
    $default_image = file_create_url(drupal_get_path('module', 'opigno_user_selection') . '/assets/profile.svg');
    $image_style = ImageStyle::load('thumbnail');
    if (!$image_style instanceof ImageStyle) {
      return $default_image;
    }

    /** @var \Drupal\Core\Entity\FieldableEntityInterface $user */
    if (!($file = $this
      ->getEntityField($user, 'user_picture'))) {
      return $default_image;
    }
    return $image_style
      ->buildUrl($file
      ->getFileUri());
  }

  /**
   * {@inheritdoc}
   *
   * @opigno_deprecated
   */
  public function getGroupImage($type, $group) {
    $default_image = file_create_url(drupal_get_path('module', 'opigno_user_selection') . '/assets/' . $type . '.svg');
    $image_style = ImageStyle::load('thumbnail');
    if (!$image_style instanceof ImageStyle) {
      return $default_image;
    }
    $media = $this
      ->getEntityField($group, 'field_learning_path_media_image');
    if (!$media instanceof Media) {
      return $default_image;
    }
    $file = $this
      ->getEntityField($media, 'field_media_image');
    if (!$file instanceof File) {
      return $default_image;
    }
    return $image_style
      ->buildUrl($file
      ->getFileUri());
  }

  /**
   * {@inheritdoc}
   */
  public function post($data = NULL) {
    $content = $this->currentRequest
      ->getContent();
    if (!empty($content)) {

      // 2nd param to get as array.
      $data = json_decode($content, TRUE);
    }
    $groups_id = [];
    $response_data = [];
    $meta = new CacheableMetadata();
    $meta
      ->setCacheMaxAge(Cache::PERMANENT);

    /** @var \Drupal\user\Entity\User[] $users */
    $users = $this
      ->entityTypeManager()
      ->getStorage('user')
      ->loadMultiple($data ?: []);
    $map = [
      'learning_path' => 'training',
      'opigno_class' => 'class',
    ];
    $response_data['users'] = array_map(function ($user) use (&$groups_id, $meta, $map) {
      $meta
        ->addCacheableDependency($user);
      $memberships = $this->groupMembershipLoader
        ->loadByUser($user);

      /** @var \Drupal\user\Entity\User $user */
      return [
        'id' => $user
          ->id(),
        'name' => $user
          ->getDisplayName(),
        'email' => '',
        'avatar' => $this
          ->getuserAvatar($user),
        'member' => array_filter(array_map(function (GroupMembership $membership) use (&$groups_id, $map) {
          $group = $membership
            ->getGroup();
          if (array_key_exists($group
            ->bundle(), $map)) {
            $groups_id[] = $gid = (int) $group
              ->id();
            return $gid;
          }
          return NULL;
        }, $memberships)),
      ];
    }, $users);

    /** @var \Drupal\group\Entity\Group[] $groups */
    $groups = $this
      ->entityTypeManager()
      ->getStorage('group')
      ->loadMultiple($groups_id ?: []);
    $response_data['members'] = array_map(function ($group) use ($meta, $map) {
      $meta
        ->addCacheableDependency($group);
      $memberships = $this->groupMembershipLoader
        ->loadByGroup($group);

      /** @var \Drupal\group\Entity\Group $group */
      return [
        "id" => $group
          ->id(),
        "type" => $map[$group
          ->bundle()],
        "info" => [
          "name" => $group
            ->label(),
          'avatar' => $this
            ->getGroupImage($map[$group
            ->bundle()], $group),
        ],
        "key" => $map[$group
          ->bundle()] . "_" . $group
          ->id(),
        "loaded" => TRUE,
        "members" => array_map(function (GroupMembership $membership) {
          return (int) $membership
            ->getGroupContent()
            ->getEntity()
            ->id();
        }, $memberships),
      ];
    }, $groups);
    $response = new CacheableJsonResponse($response_data);
    $response
      ->addCacheableDependency($meta);
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function training($data = NULL) {
    $content = $this->currentRequest
      ->getContent();
    if (!empty($content)) {

      // 2nd param to get as array.
      $data = json_decode($content, TRUE);
    }
    $response_data = [];
    $meta = new CacheableMetadata();
    $meta
      ->setCacheMaxAge(Cache::PERMANENT);
    $map = [
      'learning_path' => 'training',
      'opigno_class' => 'class',
    ];

    /** @var \Drupal\group\Entity\Group[] $groups */
    $groups = $this
      ->entityTypeManager()
      ->getStorage('group')
      ->loadMultiple($data ?: []);

    // Response_data key should be "users",
    $response_data['users'] = array_map(function ($group) use ($meta, $map) {
      $meta
        ->addCacheableDependency($group);

      /** @var \Drupal\group\Entity\Group $group */
      return [
        'id' => $group
          ->id(),
        'name' => $group
          ->label(),
        'email' => '',
        'avatar' => $this
          ->getGroupImage($map[$group
          ->bundle()], $group),
      ];
    }, $groups);
    $response = new CacheableJsonResponse($response_data);
    $response
      ->addCacheableDependency($meta);
    return $response;
  }

}

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.
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.
OpignoUserSelectionController::$currentRequest protected property Service "request_stack" definition.
OpignoUserSelectionController::$groupMembershipLoader protected property Service "group.membership_loader" definition.
OpignoUserSelectionController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
OpignoUserSelectionController::getEntityField protected function @opigno_deprecated
OpignoUserSelectionController::getGroupImage public function @opigno_deprecated
OpignoUserSelectionController::getuserAvatar public function @opigno_deprecated
OpignoUserSelectionController::post public function
OpignoUserSelectionController::training public function
OpignoUserSelectionController::__construct public function
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.