niobi-8.x-2.0-alpha4/modules/niobi_form/modules/niobi_app/src/Entity/NiobiApplicationWorkflow.php

modules/niobi_form/modules/niobi_app/src/Entity/NiobiApplicationWorkflow.php
<?php

namespace Drupal\niobi_app\Entity;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\group\Entity\GroupContent;
use Drupal\niobi_app\Form\Entity\NiobiApplicationForm;
use Drupal\niobi_form\Entity\NiobiForm;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
use Drupal\user\UserInterface;
use Drupal\views\Views;
use Drupal\webform\Entity\Webform;

/**
 * Defines the Niobi Application Workflow entity.
 *
 * @ingroup niobi_app
 *
 * @ContentEntityType(
 *   id = "niobi_application_workflow",
 *   label = @Translation("Niobi Application Workflow"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\niobi_app\NiobiApplicationWorkflowListBuilder",
 *     "views_data" = "Drupal\niobi_app\Entity\NiobiApplicationWorkflowViewsData",
 *     "translation" = "Drupal\niobi_app\NiobiApplicationWorkflowTranslationHandler",
 *
 *     "form" = {
 *       "default" = "Drupal\niobi_app\Form\Entity\NiobiApplicationWorkflowForm",
 *       "add" = "Drupal\niobi_app\Form\Entity\NiobiApplicationWorkflowForm",
 *       "edit" = "Drupal\niobi_app\Form\Entity\NiobiApplicationWorkflowForm",
 *       "delete" = "Drupal\niobi_app\Form\Entity\NiobiApplicationWorkflowDeleteForm",
 *     },
 *     "access" = "Drupal\niobi_app\NiobiApplicationWorkflowAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\niobi_app\NiobiApplicationWorkflowHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "niobi_application_workflow",
 *   data_table = "niobi_application_workflow_field_data",
 *   translatable = TRUE,
 *   admin_permission = "administer niobi application workflow entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *   links = {
 *     "canonical" = "/application_workflow/{niobi_application_workflow}",
 *     "add-form" = "/application_workflow/add",
 *     "edit-form" = "/application_workflow/{niobi_application_workflow}/manage/settings",
 *     "delete-form" = "/application_workflow/{niobi_application_workflow}/manage/delete",
 *     "collection" = "/admin/niobi/niobi_application_workflow",
 *   },
 *   field_ui_base_route = "niobi_application_workflow.settings"
 * )
 */
class NiobiApplicationWorkflow extends ContentEntityBase implements NiobiApplicationWorkflowInterface {

  use EntityChangedTrait;

  /**
   * @param bool $load
   * @return array|\Drupal\Core\Entity\EntityInterface[]|User[]
   */
  public function getAdminTeam($load = FALSE) {
    $team = [$this->getOwner()->id()];
    $values = $this->get('field_workflow_admin_team')->getValue();
    if (!empty($values)) {
      foreach($values as $index => $value) {
        if (isset($value['target_id']) && !empty($value['target_id'])) {
          $team[] = $value['target_id'];
        }
      }
    }

    if ($load) {
      $team = User::loadMultiple($team);
    }
    return $team;
  }

  /**
   * @param null $account_id
   * @return array|\Drupal\Core\Entity\EntityInterface[]|User[]
   */
  public function isOnAdminTeam($account_id = NULL) {
    $account_id = $account_id ? $account_id : \Drupal::currentUser()->id();
    $team = $this->getAdminTeam();

    return in_array($account_id, $team);
  }

  /**
   * @param bool $load
   * @return array|\Drupal\Core\Entity\EntityInterface[]|User[]
   */
  public function getViewAccessTeam($load = FALSE) {
    $team = [$this->getOwner()->id()];
    $values = $this->get('field_view_access_team')->getValue();
    if (!empty($values)) {
      foreach($values as $index => $value) {
        $team[] = $value['target_id'];
      }
    }

    if ($load) {
      $team = User::loadMultiple($team);
    }
    return $team;
  }

  /**
   * @param null $account_id
   * @return array|\Drupal\Core\Entity\EntityInterface[]|User[]
   */
  public function isOnViewAccessTeam($account_id = NULL) {
    $account_id = $account_id ? $account_id : \Drupal::currentUser()->id();
    $team = $this->getViewAccessTeam();

    return in_array($account_id, $team);
  }

  /**
   * @return bool|mixed
   */
  public function getFirstStage() {
    $stages = $this->getStages();
    $stage = FALSE;
    if (!empty($stages)) {
      $stage = array_shift($stages);
    }

    return $stage;
  }

  /**
   * @return array
   */
  public function getStages() {
    $stage_view = Views::getView('niobi_applications_application_manager');
    $stage_view->setArguments([$this->id()]);
    $stage_view->setDisplay('page_1');
    $stage_view->preExecute();
    $stage_view->execute();
    $stages = [];
    if (!empty($stage_view->result)) {
      foreach ($stage_view->result as $stage_result) {
        if (isset($stage_result->_entity) && !empty($stage_result->_entity)) {
          $stages[$stage_result->_entity->id()] = $stage_result->_entity;
        }
      }
    }

    return $stages;
  }

  /**
   * @param AccountInterface|NULL $account
   * @return \Drupal\Core\Entity\EntityInterface[]|NiobiApplication[]
   */
  public function getUserApplications(AccountInterface $account = NULL) {
    $account = $account ? $account : \Drupal::currentUser();
    $query = \Drupal::entityQuery('niobi_application');
    $query->condition('field_application_workflow', $this->id());
    $query->condition('user_id', $account->id());
    $result = $query->execute();

    $applications = NiobiApplication::loadMultiple($result);
    return $applications;
  }

  /**
   * Checks if application workflow meets minimum requirements for use.
   * @return bool
   */
  public function isReadyToUse() {
    $stages = $this->getStages();
    foreach ($stages as $stage) {
      if (!$stage->isReadyToUse()) {
        return FALSE;
      }
    }
    return TRUE;
  }

  /**
   * @return bool
   */
  public function multipleApplicationsAllowed() {
    if (isset($this->get('field_multiple_applications')->value) && $this->get('field_multiple_applications')->value) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

  /**
   * @param AccountInterface|NULL $account
   * @return bool
   */
  public function mayCreateApplications(AccountInterface $account = NULL) {
    // The workflow has the "open" status.
    if (!$this->openForApplications()) {
      return FALSE;
    }

    // Next, see if we are already full for applications (i.e. over the max).
    $query = \Drupal::entityQuery('niobi_application');
    $query->condition('field_application_workflow', $this->id());
    $query->condition('field_application_status', 'complete', '<>');
    $open_applications = $query->count()->execute();

    $max = $this->get('field_max_active_applications')->getValue();
    $max = isset($max[0]['value']) ? $max[0]['value'] : 0;
    if ($max && $max <= $open_applications) {
      return FALSE;
    }

    /*
     * Next check the multi-application case.
     * If we have an active (not complete) application, and we have not enabled
     * multiple applications, then hide the application button.
     */
    $applications = $this->getUserApplications();
    if (!$this->multipleApplicationsAllowed() && !empty($applications)) {
      $active = FALSE;
      foreach ($applications as $application) {
        /* @var $application \Drupal\niobi_app\Entity\NiobiApplication */
        if($application->getCurrentApplicationStatus() !== 'complete') {
          $active = TRUE;
        }
      }
      if ($active) {
        return FALSE;
      }
    }

    $account = $account ? $account : \Drupal::currentUser();

    // Finally, check route access.
    $route = 'niobi_application.create_application';
    $stage = $this->getFirstStage();
    if ($stage) {
      // Check if we have a nomination or application form.
      $nomination = $stage->getNominationForm();
      if ($nomination) {
        $route = 'niobi_application.create_nomination';
      }
    }

    $accessManager = \Drupal::service('access_manager');
    return $accessManager->checkNamedRoute($route, ['niobi_application_workflow' => $this->id()], $account);
  }

  /**
   * @return bool
   */
  public function openForApplications() {
    if (isset($this->get('field_workflow_open')->value) && $this->get('field_workflow_open')->value) {
      return TRUE;
    }
    elseif (!isset($this->get('field_workflow_open')->value)) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'user_id' => \Drupal::currentUser()->id(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('user_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('user_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('user_id', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('user_id', $account->id());
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isPublished() {
    return (bool) $this->getEntityKey('status');
  }

  /**
   * {@inheritdoc}
   */
  public function setPublished($published) {
    $this->set('status', $published ? TRUE : FALSE);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Niobi Application Workflow entity.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of the Niobi Application Workflow entity.'))
      ->setSettings([
        'max_length' => 511,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setRequired(TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Publishing status'))
      ->setDescription(t('A boolean indicating whether the Niobi Application Workflow is published.'))
      ->setDefaultValue(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'weight' => -3,
      ]);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'));

    return $fields;
  }

  /**
   * Check if the application workflow contain a specific form
   *
   * @param $form
   *
   * @return bool
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function containForm($form) {
    $stages = \Drupal::entityTypeManager()->getStorage('niobi_application_workflow_stage')
      ->loadByProperties(['field_parent_workflow' => $this->id()]);

    foreach ($stages as $stage) {
      $appValues = $stage->field_application->getValue();
      $autoAssignReviewValues = $stage->field_auto_assign_review_form->getValue();
      $optionalAddendaValues = $stage->field_optional_addenda->getValue();
      $requiredAddendaValues = $stage->field_required_addenda->getValue();
      $reviewValues = $stage->field_reviewer_pools->getValue();
      $values = array_merge($appValues, $autoAssignReviewValues, $optionalAddendaValues,
        $requiredAddendaValues, $reviewValues);

      foreach ($values as $v) {
        if ($v['target_id'] == $form->id()) {
          return TRUE;
        }
      }
    }

    return FALSE;
  }

  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);

    // sync setting multiple drafts to for all webforms
    $stages = \Drupal::entityTypeManager()->getStorage('niobi_application_workflow_stage')
      ->loadByProperties(['field_parent_workflow' => $this->id()]);

    $formIds = [];
    foreach ($stages as $stage) {
      $appValues = $stage->field_application->getValue();
      $autoAssignReviewValues = $stage->field_auto_assign_review_form->getValue();
      $optionalAddendaValues = $stage->field_optional_addenda->getValue();
      $requiredAddendaValues = $stage->field_required_addenda->getValue();
      $reviewValues = $stage->field_review->getValue();
      $values = array_merge($appValues, $autoAssignReviewValues, $optionalAddendaValues,
        $requiredAddendaValues, $reviewValues);

      foreach ($values as $v) {
        $formIds[] = $v['target_id'];
      }
    }

    $forms = NiobiForm::loadMultiple($formIds);
    $webFormIds = [];
    foreach ($forms as $form) {
      $v = current($form->field_form->getValue());
      if (!empty($v['target_id'])) {
        $webFormIds[] = $v['target_id'];
      }
    }

    $webforms = Webform::loadMultiple($webFormIds);
    $draftMultiple = $this->field_draft_multiple->value;
    foreach ($webforms as $webform) {
      if ($webform->getSetting('draft_multiple') != $draftMultiple) {
        $webform->setSetting('draft_multiple', $draftMultiple);
        $webform->save();
      }
    }

    // after saving workflow, flush render cache
    // (in case there are changes in view access team and workflow admin team)
    \Drupal::service('cache.render')->invalidateAll();
  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc