You are here

class PullController in Salesforce Suite 5.0.x

Same name and namespace in other branches
  1. 8.4 modules/salesforce_pull/src/Controller/PullController.php \Drupal\salesforce_pull\Controller\PullController
  2. 8.3 modules/salesforce_pull/src/Controller/PullController.php \Drupal\salesforce_pull\Controller\PullController

Push controller.

Hierarchy

Expanded class hierarchy of PullController

File

modules/salesforce_pull/src/Controller/PullController.php, line 30

Namespace

Drupal\salesforce_pull\Controller
View source
class PullController extends ControllerBase {
  const DEFAULT_TIME_LIMIT = 30;

  /**
   * Pull queue handler service.
   *
   * @var \Drupal\salesforce_pull\QueueHandler
   */
  protected $queueHandler;

  /**
   * Pull delete handler service.
   *
   * @var \Drupal\salesforce_pull\DeleteHandler
   */
  protected $deleteHandler;

  /**
   * Mapping storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $mappingStorage;

  /**
   * Queue factory service.
   *
   * @var \Drupal\Core\Queue\QueueFactory
   */
  protected $queueService;

  /**
   * Queue worker manager.
   *
   * @var \Drupal\Core\Queue\QueueWorkerManagerInterface
   */
  protected $queueWorkerManager;

  /**
   * Event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * Time.
   *
   * @var \Drupal\Component\Datetime\Time
   */
  protected $time;

  /**
   * Current Request.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * PushController constructor.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function __construct(QueueHandler $queueHandler, DeleteHandler $deleteHandler, EntityTypeManagerInterface $etm, ConfigFactoryInterface $configFactory, StateInterface $stateService, QueueFactory $queueService, QueueWorkerManagerInterface $queueWorkerManager, EventDispatcherInterface $eventDispatcher, Time $time, RequestStack $requestStack) {
    $this->queueHandler = $queueHandler;
    $this->deleteHandler = $deleteHandler;
    $this->mappingStorage = $etm
      ->getStorage('salesforce_mapping');
    $this->configFactory = $configFactory;
    $this->stateService = $stateService;
    $this->queueService = $queueService;
    $this->queueWorkerManager = $queueWorkerManager;
    $this->eventDispatcher = $eventDispatcher;
    $this->time = $time;
    $this->request = $requestStack
      ->getCurrentRequest();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('salesforce_pull.queue_handler'), $container
      ->get('salesforce_pull.delete_handler'), $container
      ->get('entity_type.manager'), $container
      ->get('config.factory'), $container
      ->get('state'), $container
      ->get('queue'), $container
      ->get('plugin.manager.queue_worker'), $container
      ->get('event_dispatcher'), $container
      ->get('datetime.time'), $container
      ->get('request_stack'));
  }

  /**
   * Page callback to process push queue for a given mapping.
   */
  public function endpoint(SalesforceMappingInterface $salesforce_mapping = NULL, $key = NULL, $id = NULL) {

    // If standalone for this mapping is disabled, and global standalone is
    // disabled, then "Access Denied" for this mapping.
    if ($key != $this->stateService
      ->get('system.cron_key')) {
      throw new AccessDeniedHttpException();
    }
    $global_standalone = $this
      ->config('salesforce.settings')
      ->get('standalone');
    if (!$salesforce_mapping && !$global_standalone) {
      throw new AccessDeniedHttpException();
    }
    if ($salesforce_mapping && !$salesforce_mapping
      ->doesPullStandalone() && !$global_standalone) {
      throw new AccessDeniedHttpException();
    }
    if ($id) {
      try {
        $id = new SFID($id);
      } catch (\Exception $e) {
        throw new AccessDeniedHttpException();
      }
    }
    $this
      ->populateQueue($salesforce_mapping, $id);
    $this
      ->processQueue();
    if ($this->request
      ->get('destination')) {
      return new RedirectResponse($this->request
        ->get('destination'));
    }
    return new Response('', 204);
  }

  /**
   * Helper method to populate queue, optionally by mapping or a single record.
   */
  protected function populateQueue(SalesforceMappingInterface $mapping = NULL, SFID $id = NULL) {
    $mappings = [];
    if ($id) {
      return $this->queueHandler
        ->getSingleUpdatedRecord($mapping, $id, TRUE);
    }
    if ($mapping != NULL) {
      $mappings[] = $mapping;
    }
    else {
      $mappings = $this->mappingStorage
        ->loadByProperties([
        "pull_standalone" => TRUE,
      ]);
    }
    foreach ($mappings as $mapping) {
      $this->queueHandler
        ->getUpdatedRecordsForMapping($mapping);
    }
  }

  /**
   * Helper method to get queue processing time limit.
   */
  protected function getTimeLimit() {
    return self::DEFAULT_TIME_LIMIT;
  }

  /**
   * Helper method to process queue.
   */
  protected function processQueue() {
    $start = microtime(TRUE);
    $worker = $this->queueWorkerManager
      ->createInstance(QueueHandler::PULL_QUEUE_NAME);
    $end = time() + $this
      ->getTimeLimit();
    $queue = $this->queueService
      ->get(QueueHandler::PULL_QUEUE_NAME);
    $count = 0;
    while ((!$this
      ->getTimeLimit() || time() < $end) && ($item = $queue
      ->claimItem())) {
      try {
        $this->eventDispatcher
          ->dispatch(new SalesforceNoticeEvent(NULL, 'Processing item @id from @name queue.', [
          '@name' => QueueHandler::PULL_QUEUE_NAME,
          '@id' => $item->item_id,
        ]), SalesforceEvents::NOTICE);
        $worker
          ->processItem($item->data);
        $queue
          ->deleteItem($item);
        $count++;
      } catch (RequeueException $e) {

        // The worker requested the task to be immediately requeued.
        $queue
          ->releaseItem($item);
      } catch (SuspendQueueException $e) {

        // If the worker indicates there is a problem with the whole queue,
        // release the item.
        $queue
          ->releaseItem($item);
        throw new \Exception($e
          ->getMessage());
      }
    }
    $elapsed = microtime(TRUE) - $start;
    $this->eventDispatcher
      ->dispatch(new SalesforceNoticeEvent(NULL, 'Processed @count items from the @name queue in @elapsed sec.', [
      '@count' => $count,
      '@name' => QueueHandler::PULL_QUEUE_NAME,
      '@elapsed' => round($elapsed, 2),
    ]), SalesforceEvents::NOTICE);
  }

}

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.
PullController::$deleteHandler protected property Pull delete handler service.
PullController::$eventDispatcher protected property Event dispatcher.
PullController::$mappingStorage protected property Mapping storage.
PullController::$queueHandler protected property Pull queue handler service.
PullController::$queueService protected property Queue factory service.
PullController::$queueWorkerManager protected property Queue worker manager.
PullController::$request protected property Current Request.
PullController::$time protected property Time.
PullController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
PullController::DEFAULT_TIME_LIMIT constant
PullController::endpoint public function Page callback to process push queue for a given mapping.
PullController::getTimeLimit protected function Helper method to get queue processing time limit.
PullController::populateQueue protected function Helper method to populate queue, optionally by mapping or a single record.
PullController::processQueue protected function Helper method to process queue.
PullController::__construct public function PushController constructor.
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.