CertificateController.php in Opigno certificate 3.x
File
src/Controller/CertificateController.php
View source
<?php
namespace Drupal\opigno_certificate\Controller;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Controller\EntityViewController;
use Drupal\Core\Session\AccountInterface;
use Drupal\opigno_certificate\OpignoCertificateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CertificateController extends EntityViewController {
protected $currentUser;
public function __construct(AccountInterface $current_user, ...$default) {
parent::__construct(...$default);
$this->currentUser = $current_user ?: \Drupal::currentUser();
}
public static function create(ContainerInterface $container) {
return new static($container
->get('current_user'), $container
->get('entity_type.manager'), $container
->get('renderer'));
}
public function viewEntity($entity_type, $entity_id, $view_mode = 'full') {
try {
$entity = $this->entityTypeManager
->getStorage($entity_type)
->load($entity_id);
} catch (PluginNotFoundException|InvalidPluginDefinitionException $e) {
watchdog_exception('opigno_certificate_exception', $e);
$entity = NULL;
}
if (!$entity instanceof ContentEntityInterface || !$entity
->hasField('field_certificate')) {
return [];
}
$opigno_certificate = $entity
->get('field_certificate')->entity;
if (!$opigno_certificate instanceof OpignoCertificateInterface) {
return [];
}
$opigno_certificate
->set('referencing_entity', $entity);
return $this
->view($opigno_certificate, $view_mode);
}
public function view(EntityInterface $opigno_certificate, $view_mode = 'full') {
if (in_array($view_mode, [
'full',
'default',
]) && $opigno_certificate
->getViewModeSelectorField()) {
$view_mode = 'view_mode_selector';
}
$build = parent::view($opigno_certificate, $view_mode);
return $build;
}
public function viewAccess($entity_type, $entity_id) : AccessResultInterface {
$entity = $this->entityTypeManager
->getStorage($entity_type)
->load($entity_id);
if (!$entity instanceof ContentEntityInterface || !$entity
->hasField('field_certificate')) {
return AccessResult::forbidden();
}
$opigno_certificate = $entity
->get('field_certificate')->entity;
if (!$opigno_certificate instanceof OpignoCertificateInterface) {
return AccessResult::forbidden();
}
$opigno_certificate
->set('referencing_entity', $entity);
$access_result = AccessResult::allowedIfHasPermission($this->currentUser, 'administer certificates');
if ($access_result
->isAllowed()) {
return $access_result;
}
$access_result = $entity
->access('view certificate', $this->currentUser, TRUE);
return $access_result instanceof AccessResultInterface ? $access_result : AccessResult::forbidden();
}
}