Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
1
Indexable
Never
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\workflows\WorkflowTransitionValidation;
use Symfony\Component\DependencyInjection\ContainerInterface;

// Get the required services through dependency injection.
public static function create(ContainerInterface $container) {
  return new static(
    $container->get('entity_type.manager'),
    $container->get('workflows.transition_validation')
  );
}

// Constructor to set up the services.
public function __construct(EntityTypeManagerInterface $entity_type_manager, WorkflowTransitionValidation $workflow_transition_validation) {
  $this->entityTypeManager = $entity_type_manager;
  $this->workflowTransitionValidation = $workflow_transition_validation;
}

// Function to get roles that can do the next transitions for a specific workflow and state.
public function getRolesForNextTransitions($workflow_id, $current_state_id) {
  $workflow = $this->entityTypeManager->getStorage('workflow')->load($workflow_id);
  $current_state = $workflow->getTypePlugin()->getState($current_state_id);

  // Get the list of transitions available from the current state.
  $transitions = $current_state->getTransitions();

  $roles_with_permissions = [];

  foreach ($transitions as $transition) {
    // Check if the transition is valid and if so, get the roles with permission for that transition.
    if ($this->workflowTransitionValidation->canTransition($transition, $current_state)) {
      $permissions = $transition->getPermissions();
      foreach ($permissions as $permission) {
        // If you have a custom permission pattern for role-based access, modify the following line accordingly.
        $roles_with_permissions[] = $this->entityTypeManager->getStorage('user_role')->loadByProperties(['id' => $permission]);
      }
    }
  }

  return $roles_with_permissions;
}