You are here

class AmpSocialPost in Accelerated Mobile Pages (AMP) 8.3

Provides AMP social post elements.

Provides amp-facebook, amp-twitter, amp-instagram, amp-pinterest. The provider is deduced from the url.

@parameter string #url: The social url. @parameter string placeholder: Placeholder for amp-twitter. @parameter array attributes: The HTML attributes for amp-social-post:

  • layout: The layout of the element.
  • height: The height of the element.
  • width: The width of the element.
  • data-embed-as: Embed as post or video for amp-facebook.
  • data-align-center: Center align or not for amp-facebook.

Example usage: $renderElement = [ '#type' => 'amp_social_post', '#url' => 'https://twitter.com/cramforce/status/638793490521001985', ];

Plugin annotation

@RenderElement("amp_social_post");

Hierarchy

Expanded class hierarchy of AmpSocialPost

2 files declare their use of AmpSocialPost
AmpSocialPostFormatter.php in src/Plugin/Field/FieldFormatter/AmpSocialPostFormatter.php
AmpSocialPostTest.php in tests/src/Unit/AmpSocialPostTest.php
1 #type use of AmpSocialPost
AmpSocialPostTest::renderData in tests/src/Unit/AmpSocialPostTest.php
Provides render data.

File

src/Element/AmpSocialPost.php, line 31

Namespace

Drupal\amp\Element
View source
class AmpSocialPost extends RenderElement {

  /**
   * {@inheritdoc}
   */
  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',
        ],
      ],
    );
  }

  /**
   * Pre-render callback.
   *
   * Processes the post and attaches libraries.
   */
  public static function preRenderSocialPost($element) {
    $url = $element['#url'];

    // If provider is invalid, the element is empty.
    if (!($provider = static::getProvider($url))) {
      return [];
    }
    else {
      $element['#provider'] = $provider;
    }

    // Set the url or id.
    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;
    }

    // Get rid of empty attributes.
    $element['#attributes'] = array_filter($element['#attributes']);

    // Attach the right library.
    $libraries = static::getLibraries();
    $element['#attached']['library'][] = $libraries[$provider];
    return $element;
  }

  /**
   * Option list of all providers.
   *
   * return array
   *   Array of names and labels for all supported providers.
   */
  public static function getProviders() {
    return [
      'facebook' => 'Facebook',
      'twitter' => 'Twitter',
      'instagram' => 'Instagram',
      'pinterest' => 'Pinterest',
    ];
  }

  /**
   * Provider libraries.
   *
   * return array
   *   Array of libraries required by all supported providers.
   */
  public static function getLibraries() {
    return [
      'facebook' => 'amp/amp.facebook',
      'twitter' => 'amp/amp.twitter',
      'instagram' => 'amp/amp.instagram',
      'pinterest' => 'amp/amp.pinterest',
    ];
  }

  /**
   * Provider regex patterns.
   *
   * return array
   *   Array of regex patterns for all supported providers.
   * @see https://code.tutsplus.com/tutorials/advanced-regular-expression-tips-and-techniques--net-11011
   */
  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',
      ],
    ];
  }

  /**
   * Find the provider from an url.
   *
   * @param $url
   *   The url.
   *
   * @return string
   *   The provider this url is valid for.
   */
  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;
  }

  /**
   * Get the provider id from an url.
   *
   * @param $url
   *   The url.
   *
   * @return string
   *   The id.
   */
  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;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AmpSocialPost::getId public static function Get the provider id from an url.
AmpSocialPost::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
AmpSocialPost::getLibraries public static function Provider libraries.
AmpSocialPost::getPatterns public static function Provider regex patterns.
AmpSocialPost::getProvider public static function Find the provider from an url.
AmpSocialPost::getProviders public static function Option list of all providers.
AmpSocialPost::preRenderSocialPost public static function Pre-render callback.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. 1
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.