eu_cookie_compliance_rocketship-1.0.x-dev/src/Plugin/Field/FieldFormatter/CookieBlockedIframeOnly.php
src/Plugin/Field/FieldFormatter/CookieBlockedIframeOnly.php
<?php
namespace Drupal\eu_cookie_compliance_rocketship\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\iframe\Plugin\Field\FieldFormatter\IframeOnlyFormatter;
class CookieBlockedIframeOnly extends IframeOnlyFormatter {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'whitelist_hostnames' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['whitelist_hostnames'] = [
'#type' => 'textarea',
'#title' => $this->t('Whitelist hostnames'),
'#description' => $this->t('Specify domains to be skipped from cookie_content_blocker. One hostname per line'),
'#default_value' => $this->getSetting('whitelist_hostnames'),
'#required' => FALSE,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$whitelist_hostnames = $this->getSetting('whitelist_hostnames');
if (!empty($whitelist_hostnames)) {
$summary[] = $this->t('Whitelist hostnames @hostnames', ['@hostnames' => str_replace("\n", ', ', $whitelist_hostnames)]);
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
// Let parent formatter do it's magic.
$elements = parent::viewElements($items, $langcode);
$whitelist_hostnames = explode("\n", $this->getSetting('whitelist_hostnames'));
// Attach Cookie Content Blocker's pre_render.
foreach ($items as $delta => $item) {
// Don
if (!empty($whitelist_hostnames) && in_array(parse_url($elements[$delta]['#src'], PHP_URL_HOST), $whitelist_hostnames)) {
continue;
}
$element[$delta]['#pre_render'] = $element[$delta]['#pre_render'] ?? [];
$elements[$delta]['#pre_render'][] = 'cookie_content_blocker.element.processor:processElement';
// TODO: extend formatter settings with CCB options (like button_text) and set them here.
// $defaults = [
// 'blocked_message' => $config->get('blocked_message'),
// 'show_button' => $config->get('show_button'),
// 'button_text' => $config->get('button_text'),
// 'enable_click' => $config->get('enable_click_consent_change'),
// 'show_placeholder' => TRUE,
// 'preview' => [],
// ];
$elements[$delta]['#cookie_content_blocker'] = $elements[$delta]['#cookie_content_blocker'] ?? TRUE;
}
return $elements;
}
}
