You are here

class CertificateTabController in Course 8.2

Same name and namespace in other branches
  1. 8.3 modules/course_certificate/src/Controller/CertificateTabController.php \Drupal\course_certificate\Controller\CertificateTabController

An example controller.

Hierarchy

Expanded class hierarchy of CertificateTabController

File

modules/course_certificate/src/Controller/CertificateTabController.php, line 21

Namespace

Drupal\course_certificate\Controller
View source
class CertificateTabController extends ControllerBase {

  /**
   *  Helper to plugin current user when not provided in path
   * @param Course $course
   * @return main cert tab
   */
  public function renderDefaultCertificateTab(Course $course) {
    $account = Drupal::currentUser();
    return $this
      ->renderCertificateTab($course, $account);
  }

  /**
   *  Helper to plugin current user when not provided in path
   * @param Course $course
   * @return main cert tab
   */
  public function accessDefaultTab(Course $course) {
    $account = Drupal::currentUser();
    return $this
      ->accessTab($course, $account);
  }

  /**
   * @param EntityInterface $course
   *   The entity this belongs to
   * @param AccountInterface $account
   * The user account to check
   * @return \Drupal\Core\Access\AccessResultInterface
   *   An access result
   */
  public function accessTab(Course $course, AccountInterface $account = NULL) {
    $has_object = FALSE;
    $account = $account ?? Drupal::currentUser();
    $admin = $account
      ->hasPermission('administer certificates');
    $view_all = $account
      ->hasPermission('view all user certificates');
    $access_result = AccessResult::forbidden("Access not granted");
    if (!$account
      ->id()) {
      return AccessResult::forbidden("Not a valid user");
    }

    // Does the course have a certificate object?
    foreach ($course
      ->getObjects() as $courseObject) {
      if ($courseObject
        ->getComponent() == 'certificate') {
        $has_object = TRUE;
        break;
      }
    }
    if (!$has_object) {
      return AccessResult::forbidden("No certificate object provided");
    }

    // Are they enrolled?
    $enrollments = $this
      ->entityTypeManager()
      ->getStorage('course_enrollment')
      ->loadByProperties([
      'uid' => $account
        ->id(),
      'cid' => $course
        ->id(),
    ]);
    if (empty($enrollments)) {
      $access_result = AccessResult::forbidden();
    }
    else {
      $enrollment = reset($enrollments);

      // Are they an admin or have they completed the course?
      if ($admin || $view_all || $enrollment
        ->isComplete()) {
        $access_result = AccessResult::allowed();
      }
    }
    return $access_result;
  }

  /**
   * Full tab
   * @param Course $course
   * @param AccountInterface $account
   * @return type
   */
  function renderCertificateTab(Course $course, AccountInterface $account) {

    // Get all templates for this entity combo
    $render = [];
    $valid_certs = [];
    $global_certs = CertificateMapping::getGlobalCertificateMappings();
    $certificate_mappers = Drupal::service('plugin.manager.certificate_mapper');
    $map_defs = $certificate_mappers
      ->getDefinitions();
    $certs = $course
      ->get('certificate')
      ->referencedEntities();

    //Default to load a page
    $render['info']['#markup'] = '';
    foreach ($map_defs as $map_key => $maps) {
      $plugin = $certificate_mappers
        ->createInstance($map_key, [
        'of' => 'configuration values',
      ]);
      $matches = $plugin
        ->processMapping($course, $account) ?? [];
      foreach ($matches as $match) {
        foreach ($certs as $local) {
          if ($local
            ->isMatch($map_key, $match)) {
            $valid_certs["{$map_key}.{$match}"] = $local
              ->get('cid')->value;
          }
        }

        // If local is not set, check the global mappings
        if (!isset($valid_certs["{$map_key}.{$match}"])) {
          $render['table'] = [
            '#type' => 'table',
            '#header' => [
              $this
                ->t('Type'),
              $this
                ->t('Download'),
            ],
          ];
          foreach ($global_certs as $global) {
            if ($global
              ->isMatch($map_key, $match) && $global
              ->get('cid')->value !== '-1') {
              $valid_certs["{$map_key}.{$match}"] = $global
                ->get('cid')->value;
            }
          }
        }
        elseif ($valid_certs["{$map_key}.{$match}"] == '-1') {
          unset($valid_certs["{$map_key}.{$match}"]);
        }
      }
    }

    // Return markup if we need to present messages
    if (count($valid_certs) > 1) {
      $render['info']['#markup'] = ' You are eligible for multiple certificates.';
    }
    if (empty($valid_certs)) {
      $render['info']['#markup'] = 'You are not eligible for a certificate';
    }
    foreach ($valid_certs as $cert_name => $val) {
      $opts = [
        'course' => $course
          ->id(),
        'account' => $account
          ->id(),
        'template' => $val,
      ];
      $render['table'][$val] = [
        'type' => [
          '#markup' => $cert_name,
        ],
        'download' => Link::createFromRoute(t('Download certificate'), 'certificate.course.pdf', $opts)
          ->toRenderable(),
      ];
    }
    return $render;
  }

  /**
   * Downloads
   *
   * @param Course $course
   * @param AccountInterface $account
   * @param CertificateTemplate $template
   * @return type
   */
  function accessPdf(Course $course, AccountInterface $account, CertificateTemplate $template) {
    return $this
      ->accessTab($course, $account);
  }

  /**
   * Stream a PDF to the browser
   * @param Course $course
   * @param AccountInterface $account
   * @param CertificateTemplate $template
   * @return type
   */
  function returnPdf(Course $course, AccountInterface $account, CertificateTemplate $template) {
    $pdf_gen = $template
      ->loadPrintableEngine();

    // Check for a PDF engine
    if ($pdf_gen === FALSE) {
      $current_user = \Drupal::currentUser();
      $msg = t('Current site configuration does not allow PDF file creation. Please contact an administrator.');
      if ($current_user
        ->hasPermission('administer printable')) {
        $url = Url::fromRoute('printable.format_configure_pdf');
        $link = Link::createFromRoute('configure a PDF library', 'printable.format_configure_pdf');
        $msg = t('Please @link to print certificates.', [
          '@link' => $link
            ->toString(),
        ]);
      }
      return [
        '#markup' => $msg,
      ];
    }

    // Everything is configured, build the PDF
    $render = $template
      ->renderView($account, $course);
    $pdf_gen
      ->addPage(render($render));
    return $pdf_gen
      ->stream($pdf_gen
      ->getObject()
      ->getPdfFilename());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CertificateTabController::accessDefaultTab public function Helper to plugin current user when not provided in path
CertificateTabController::accessPdf function Downloads
CertificateTabController::accessTab public function
CertificateTabController::renderCertificateTab function Full tab
CertificateTabController::renderDefaultCertificateTab public function Helper to plugin current user when not provided in path
CertificateTabController::returnPdf function Stream a PDF to the browser
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.
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.