blizz_vanisher-8.x-1.x-dev/src/Service/SoundcloudVanisher.php
src/Service/SoundcloudVanisher.php
<?php
namespace Drupal\blizz_vanisher\Service;
use Drupal\blizz_vanisher\Entity\ThirdPartyServiceEntityInterface;
/**
* Class SoundcloudVanisher.
*
* @package Drupal\blizz_vanisher\Service
*/
class SoundcloudVanisher extends IframeVanisher implements IframeVanisherInterface {
const SOUNDCLOUD_IFRAME_REGEX = '~(<iframe[^>]*?src=(\'|")[^\2]*?soundcloud\.com[^\2]*?\2[^>]*?>.*?</iframe>)~is';
const FIND_MARKUP_ATTRIBUTES_REGEX = '~([a-z][a-z0-9\-_]*)(=([\'"])([^\3]*?)\3)?~is';
/**
* {@inheritdoc}
*/
protected function getIframeSearchRegexPattern() {
return self::SOUNDCLOUD_IFRAME_REGEX;
}
/**
* {@inheritdoc}
*/
protected function getReplacementMarkup(array $data, ThirdPartyServiceEntityInterface $entity) {
$attributes = array_map(
function ($key) use ($data) {
return sprintf(
'data-%s="%s"',
$key,
$data[$key]
);
},
array_keys($data)
);
return sprintf(
'<div class="soundcloud_player" %s> %s',
implode(' ', $attributes),
$entity->getInfo()
);
}
/**
* {@inheritdoc}
*/
protected function getReplacementScript() {
return '(tarteaucitron.job = tarteaucitron.job || []).push(\'soundcloud_player\');';
}
/**
* {@inheritdoc}
*/
public function getJavascript() {
return <<<JS
function () {
"use strict";
tarteaucitron.fallback(['soundcloud_player'], function (x) {
var attributes = {};
for (var index in x.attributes) {
var attributeName = x.attributes[index].name;
if (typeof attributeName !== 'undefined' && attributeName.match(/^data\-/i)) {
var attr = attributeName.split('-').pop();
attributes[attr] = x.attributes[index].value;
}
}
if (typeof attributes.src === 'undefined') {
return '';
}
var elem = document.createElement('iframe');
for (var attr in attributes) {
elem[attr] = attributes[attr];
}
return elem.outerHTML;
});
}
JS;
}
/**
* {@inheritdoc}
*/
public function getFallbackJavascript() {
return <<<JS
function () {
var id = 'soundcloud_player';
tarteaucitron.fallback(['soundcloud_player'], function (elem) {
return tarteaucitron.engage(id);
});
}
JS;
}
/**
* {@inheritdoc}
*/
protected function getIframeData($iframe) {
$data = [];
$ret = preg_match_all(self::FIND_MARKUP_ATTRIBUTES_REGEX, $iframe, $matches);
if ($ret !== FALSE && $ret > 0) {
$data = array_combine($matches[1], $matches[4]);
unset($data['iframe']);
}
return $data;
}
/**
* {@inheritdoc}
*/
public function getCookies() {
return [];
}
/**
* {@inheritdoc}
*/
public function getVanisherName() {
return 'soundcloud_player';
}
/**
* {@inheritdoc}
*/
public function __toString() {
return 'Soundcloud Vanisher';
}
}
