You are here

protected function HubspotWebformHandler::remotePost in HubSpot 3.x

Same name and namespace in other branches
  1. 8 src/Plugin/WebformHandler/HubspotWebformHandler.php \Drupal\hubspot\Plugin\WebformHandler\HubspotWebformHandler::remotePost()

Execute a remote post.

Parameters

string $operation: The type of webform submission operation to be posted. Can be 'insert', 'update', or 'delete'.

\Drupal\webform\WebformSubmissionInterface $webform_submission: The webform submission to be posted.

1 call to HubspotWebformHandler::remotePost()
HubspotWebformHandler::postSave in src/Plugin/WebformHandler/HubspotWebformHandler.php
Acts on a saved webform submission before the insert or update hook is invoked.

File

src/Plugin/WebformHandler/HubspotWebformHandler.php, line 675

Class

HubspotWebformHandler
Webform submission remote post handler.

Namespace

Drupal\hubspot\Plugin\WebformHandler

Code

protected function remotePost($operation, WebformSubmissionInterface $webform_submission) {

  // Get the hubspot config settings.
  $request_post_data = $this
    ->getPostData($operation, $webform_submission);
  $entity_type = $request_post_data['entity_type'];
  $context = [];

  // Get webform.
  $webform = $this
    ->getWebform();

  // Get all components.
  $elements = $webform
    ->getElementsDecodedAndFlattened();

  // Loop through components and set new value for checkbox fields.
  foreach ($elements as $component_key => $component) {
    if ($component['#type'] == 'checkbox') {
      $webform_submission
        ->setElementData($component_key, $webform_submission
        ->getElementData($component_key) ? 'true' : 'false');
    }
  }
  if ($entity_type) {
    $entity_storage = $this->entityTypeManager
      ->getStorage($entity_type);
    $entity = $entity_storage
      ->load($request_post_data['entity_id']);
    $form_title = $entity
      ->label();
    $page_url = Url::fromUserInput($request_post_data['uri'], [
      'absolute' => TRUE,
    ])
      ->toString();
  }
  else {

    // Case 2: Webform it self.
    // Webform title.
    $form_title = $this
      ->getWebform()
      ->label();
    $page_url = $this->webform
      ->toUrl('canonical', [
      'absolute' => TRUE,
    ])
      ->toString();
  }
  $context['pageUri'] = $page_url;
  $settings = $this
    ->getSettings();
  $form_guid = $settings['form_guid'];
  $field_mapping = $settings['field_mapping'];
  $webform_values = $webform_submission
    ->getData();
  $form_values = [];
  foreach ($field_mapping as $hubspot_field => $webform_path) {
    if ($webform_path != '--donotmap--') {
      if (strpos($webform_path, ':') !== FALSE) {

        // Is composite element.
        $composite = explode(':', $webform_path);
        $composite_value = NestedArray::getValue($webform_values, $composite);
        $form_values[$hubspot_field] = $composite_value;
      }
      else {

        // Not a composite element.
        $form_values[$hubspot_field] = $webform_values[$webform_path];
      }
    }
  }
  $request_body = [];
  if (isset($settings['legal_consent']) && $settings['legal_consent']['include'] != 'never') {
    if ($settings['legal_consent']['include'] == 'always' || in_array($elements[$settings['legal_consent']['source']['element']]['#type'], [
      'checkbox',
      'webform_terms_of_service',
    ]) && $webform_values[$settings['legal_consent']['source']['element']] == 1 || $webform_values[$settings['legal_consent']['source']['element']] == $settings['legal_consent']['source']['option']) {
      $request_body['legalConsentOptions']['consent']['consentToProcess'] = TRUE;
      $request_body['legalConsentOptions']['consent']['text'] = $settings['legal_consent']['include'] == 'always' ? $this
        ->t('I agree') : $elements[$settings['legal_consent']['source']['element']]['#title'];
    }
  }
  if (isset($settings['subscriptions'])) {
    foreach ($settings['subscriptions'] as $subscription) {
      if ($subscription['mapping']['include'] == 'always' || in_array($elements[$subscription['mapping']['element']]['#type'], [
        'checkbox',
        'webform_terms_of_service',
      ]) && $webform_values[$subscription['mapping']['element']] == 1 || $webform_values[$subscription['mapping']['element']] == $subscription['mapping']['option']) {
        $request_body['legalConsentOptions']['consent']['communications'][] = [
          'value' => TRUE,
          'subscriptionTypeId' => $subscription['subscription'],
          'text' => $subscription['mapping']['include'] == 'always' ? $this
            ->t('I agree') : $elements[$subscription['mapping']['element']]['#title'],
        ];
      }
    }
  }
  try {
    $response = $this->hubspot
      ->submitHubspotForm($form_guid, $form_values, $context, $request_body);

    // Debugging information.
    $config = $this->configFactory
      ->get('hubspot.settings');
    $hubspot_url = 'https://app.hubspot.com';
    $to = $config
      ->get('hubspot_debug_email');
    $default_language = \Drupal::languageManager()
      ->getDefaultLanguage()
      ->getId();
    $from = $config
      ->get('site_mail');
    if ($response) {
      $data = (string) $response
        ->getBody();
      if ($response
        ->getStatusCode() == '200' || $response
        ->getStatusCode() == '204') {
        $this->loggerFactory
          ->get('HubSpot')
          ->notice('Webform "@form" results successfully submitted to HubSpot.', [
          '@form' => $form_title,
        ]);
      }
      else {
        $this->loggerFactory
          ->get('HubSpot')
          ->notice('HTTP notice when submitting HubSpot data from Webform "@form". @code: <pre>@msg</pre>', [
          '@form' => $form_title,
          '@code' => $response
            ->getStatusCode(),
          '@msg' => $response
            ->getBody()
            ->getContents(),
        ]);
      }
      if ($config
        ->get('hubspot_debug_on')) {
        $this->mailManager
          ->mail('hubspot', 'hub_error', $to, $default_language, [
          'errormsg' => $data,
          'hubspot_url' => $hubspot_url,
          'node_title' => $form_title,
        ], $from);
      }
    }
    else {
      $this->loggerFactory
        ->get('HubSpot')
        ->notice('HTTP error when submitting HubSpot data from Webform "@form": <pre>@msg</pre>', [
        '@form' => $form_title,
        '@msg' => 'No response returned from Hubspot Client',
      ]);
    }
  } catch (HubspotException $e) {
    $this->loggerFactory
      ->get('HubSpot')
      ->notice('HTTP error when submitting HubSpot data from Webform "@form": <pre>@error</pre>', [
      '@form' => $form_title,
      '@error' => $e
        ->getResponse()
        ->getBody()
        ->getContents(),
    ]);
    watchdog_exception('HubSpot', $e);
  }
}