You are here

public function FormAssemblyRequest::splitHTML in FormAssembly 7

Split FormAssembly form HTML into HEAD and BODY markup.

Parameters

string $markup: HTML markup.

Return value

string[] Array with two entries: Body HTML and Head HTML for the form.

File

includes/FormAssemblyRequest.php, line 403
Authorizes the current site and handles API requests to FormAssembly.

Class

FormAssemblyRequest
@file Authorizes the current site and handles API requests to FormAssembly.

Code

public function splitHTML($markup) {
  $dom = new DOMDocument();
  libxml_use_internal_errors(TRUE);
  if (!$dom
    ->loadHTML($markup)) {
    foreach (libxml_get_errors() as $error) {
      watchdog('FormAssembly', 'Form HTML failed to load to split markup. LibXML error message is: ' . $error->message, WATCHDOG_ERROR, NULL);
    }
    libxml_clear_errors();
  }

  /** @var DOMElement|bool $body_wrapper_div */
  $body_wrapper_div_markup = FALSE;
  $div_elements = $dom
    ->getElementsByTagName('div');

  // Now, per FormAssembly support, we'll try to find a <div> element with the class name "wFormContainer".

  /** @var DOMElement $div */
  foreach ($div_elements as $div) {
    $class = $div
      ->getAttribute('class');

    // If this <div> element's class contains "wFormContainer"
    if (stripos($class, 'wFormContainer') !== FALSE) {
      $body_wrapper_div_markup = $div->ownerDocument
        ->saveHTML($div);
      break;
    }
  }

  // If we found the body wrapper div
  if ($body_wrapper_div_markup) {

    // Split the markup into its Body and Head components.
    // Just in case there's another wrapper, we get the HTML before the first
    // <div>, which is probably the same <div> we just found.
    $head_markup = substr($markup, 0, stripos($markup, '<div'));

    // We clean up the Head HTML by removing known useless comments.
    $head_markup = str_ireplace('<!-- FORM: HEAD SECTION -->', '', $head_markup);
    $head_markup = str_ireplace('<!-- FORM: BODY SECTION -->', '', $head_markup);
    $head_markup = trim($head_markup);
    $body_markup = $body_wrapper_div_markup;
  }
  else {

    // Fall back to using the entire markup in the body.
    $head_markup = '';
    $body_markup = trim($markup);
  }
  return array(
    $head_markup,
    $body_markup,
  );
}