View source
<?php
namespace Drupal\amp\Element;
use Drupal\Core\Render\Element\RenderElement;
class AmpSocialPost extends RenderElement {
public function getInfo() {
$class = get_class($this);
return array(
'#theme' => 'amp_social_post_theme',
'#pre_render' => array(
array(
$class,
'preRenderSocialPost',
),
),
'#url' => NULL,
'#placeholder' => NULL,
'#attributes' => [
'layout' => 'responsive',
'width' => NULL,
'height' => NULL,
'data-embed-as' => 'post',
'data-align-center' => NULL,
],
'#attached' => [
'library' => [
'amp/runtime',
],
],
);
}
public static function preRenderSocialPost($element) {
$url = $element['#url'];
if (!($provider = static::getProvider($url))) {
return [];
}
else {
$element['#provider'] = $provider;
}
switch ($provider) {
case 'twitter':
$element['#attributes']['data-tweetid'] = static::getId($url, $provider);
break;
case 'instagram':
$element['#attributes']['data-shortcode'] = static::getId($url, $provider);
break;
case 'pinterest':
$element['#attributes']['data-href'] = $url;
$element['#attributes']['data-do'] = 'embedPin';
break;
default:
$element['#attributes']['data-href'] = $url;
break;
}
$element['#attributes'] = array_filter($element['#attributes']);
$libraries = static::getLibraries();
$element['#attached']['library'][] = $libraries[$provider];
return $element;
}
public static function getProviders() {
return [
'facebook' => 'Facebook',
'twitter' => 'Twitter',
'instagram' => 'Instagram',
'pinterest' => 'Pinterest',
];
}
public static function getLibraries() {
return [
'facebook' => 'amp/amp.facebook',
'twitter' => 'amp/amp.twitter',
'instagram' => 'amp/amp.instagram',
'pinterest' => 'amp/amp.pinterest',
];
}
public static function getPatterns() {
return [
'facebook' => [
'@https?://(?:www\\.)?(?<provider>facebook)\\.com/?(.*/)?(?<id>[a-zA-Z0-9.]*)($|\\?.*)@',
],
'twitter' => [
'@https?://(?:www\\.)?(?<provider>twitter)\\.com/(?<user>[a-z0-9_-]+)/(status(es){0,1})/(?<id>[\\d]+)@i',
],
'instagram' => [
'@https?://(?:www\\.)?(?<provider>instagram)\\.com/p/(?<id>[a-z0-9_-]+)@i',
'@https?://(?:www\\.)?(?<provider>instagr\\.am)/p/(?<id>[a-z0-9_-]+)@i',
],
'pinterest' => [
'@https?://(?:www\\.)?(?<provider>pinterest)\\.([a-zA-Z]+\\.)?([a-zA-Z]+)/pin/(?<id>\\d+)/?\\s*$$@i',
],
];
}
public static function getProvider($url) {
$patterns = static::getPatterns();
$providers = array_keys(static::getProviders());
foreach ($providers as $provider) {
foreach ($patterns[$provider] as $pattern) {
if (preg_match($pattern, $url, $matches) && $matches['provider'] == $provider) {
return $provider;
}
}
}
return FALSE;
}
public static function getId($url, $provider) {
$patterns = static::getPatterns();
foreach ($patterns[$provider] as $pattern) {
if (preg_match($pattern, $url, $matches)) {
return $matches['id'];
}
}
return FALSE;
}
}