You are here

function cookiepro_page_attachments_alter in CookiePro by OneTrust 2.x

Same name and namespace in other branches
  1. 8 cookiepro.module \cookiepro_page_attachments_alter()

Implements hook_page_attachments_alter().

Addes JS scripts as needed. which are defined on the settings page.

File

./cookiepro.module, line 42
Add cookiepro script.

Code

function cookiepro_page_attachments_alter(array &$attachments) {
  $header_section = \Drupal::config('cookiepro.header.settings')
    ->get();
  if (isset($header_section['scripts']) && !empty($header_section['scripts'])) {
    $output_scripts = preg_split("/(<\\/script>|<\\/noscript>)/", preg_replace('/<!--(.|\\s)*?-->/', '', $header_section['scripts']));
    $i = 1;
    $i = count($attachments['#attached']['html_head']) + 1;
    foreach ($output_scripts as $row) {
      if (empty($row)) {
        continue;
      }
      $script_tag = 'script';
      $script_attr = [];
      $value = '';
      $script_attributes = preg_replace('/(<script|<noscript)/', '', $row, 1);
      $get_script_attr = preg_split('/(>)/', $script_attributes, 2);
      if (isset($get_script_attr[1])) {
        $value = $get_script_attr[1];
      }
      $get_script_tag = preg_split('/<noscript/', $row, 2);
      if (isset($get_script_tag[1])) {
        $script_tag = 'noscript';
      }
      if (isset($get_script_attr[0]) && !empty($get_script_attr[0])) {
        $get_attr = preg_replace('/(\'|\\")/', '', $get_script_attr[0]);
        $get_attr = preg_replace('/\\s+/', ',', $get_attr);
        $get_attr = preg_replace('/(,=,|,=|=,)/', '=', $get_attr);
        $fetch_attr = explode(',', $get_attr);
        foreach ($fetch_attr as $attr) {
          if (empty($attr)) {
            continue;
          }
          $attr_key_value = explode('=', $attr);
          if (isset($attr_key_value[0]) && isset($attr_key_value[1])) {
            $script_attr[$attr_key_value[0]] = $attr_key_value[1];
          }
          else {
            $script_attr[$attr_key_value[0]] = $attr_key_value[0];
          }
        }
      }
      $attachments['#attached']['html_head'][$i] = [
        [
          '#type' => 'html_tag',
          '#tag' => $script_tag,
          '#value' => $value,
        ],
        'cookiepro-' . $i,
      ];
      if (!empty($script_attr)) {
        $attachments['#attached']['html_head'][$i][0]['#attributes'] = $script_attr;
      }
      $i++;
    }
  }
}