You are here

class Instagram in Media entity Instagram 8.2

Same name and namespace in other branches
  1. 3.x src/Plugin/media/Source/Instagram.php \Drupal\media_entity_instagram\Plugin\media\Source\Instagram

Provides media type plugin for Instagram.

Plugin annotation


@MediaSource(
  id = "instagram",
  label = @Translation("Instagram"),
  description = @Translation("Provides business logic and metadata for Instagram."),
  allowed_field_types = {"string", "string_long", "link"},
  default_thumbnail_filename = "instagram.png"
)

Hierarchy

Expanded class hierarchy of Instagram

2 files declare their use of Instagram
InstagramEmbedCodeConstraintValidator.php in src/Plugin/Validation/Constraint/InstagramEmbedCodeConstraintValidator.php
InstagramEmbedFormatter.php in src/Plugin/Field/FieldFormatter/InstagramEmbedFormatter.php
1 string reference to 'Instagram'
InstagramEmbedFormatterTest::testFieldFormatter in tests/src/Functional/InstagramEmbedFormatterTest.php
Tests adding and editing an instagram embed formatter.

File

src/Plugin/media/Source/Instagram.php, line 28

Namespace

Drupal\media_entity_instagram\Plugin\media\Source
View source
class Instagram extends MediaSourceBase implements MediaSourceFieldConstraintsInterface {

  /**
   * The instagram fetcher.
   *
   * @var \Drupal\media_entity_instagram\InstagramEmbedFetcher
   */
  protected $fetcher;

  /**
   * Guzzle client.
   *
   * @var \GuzzleHttp\Client
   */
  protected $httpClient;

  /**
   * The file system service.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * Constructs a new class instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity type manager service.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   Entity field manager service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config factory service.
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
   *   The field type plugin manager service.
   * @param \Drupal\media_entity_instagram\InstagramEmbedFetcher $fetcher
   *   Instagram fetcher service.
   * @param \GuzzleHttp\Client $httpClient
   *   Guzzle client.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, ConfigFactoryInterface $config_factory, FieldTypePluginManagerInterface $field_type_manager, InstagramEmbedFetcher $fetcher, Client $httpClient, FileSystemInterface $fileSystem) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $field_type_manager, $config_factory);
    $this->fetcher = $fetcher;
    $this->httpClient = $httpClient;
    $this->fileSystem = $fileSystem;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('config.factory'), $container
      ->get('plugin.manager.field.field_type'), $container
      ->get('media_entity_instagram.instagram_embed_fetcher'), $container
      ->get('http_client'), $container
      ->get('file_system'));
  }

  /**
   * List of validation regular expressions.
   *
   * @var array
   */
  public static $validationRegexp = [
    '@((http|https):){0,1}//(www\\.){0,1}instagram\\.com/p/(?<shortcode>[a-z0-9_-]+)@i' => 'shortcode',
    '@((http|https):){0,1}//(www\\.){0,1}instagr\\.am/p/(?<shortcode>[a-z0-9_-]+)@i' => 'shortcode',
    '@((http|https):){0,1}//(www\\.){0,1}instagram\\.com/tv/(?<shortcode>[a-z0-9_-]+)@i' => 'shortcode',
    '@((http|https):){0,1}//(www\\.){0,1}instagr\\.am/tv/(?<shortcode>[a-z0-9_-]+)@i' => 'shortcode',
  ];

  /**
   * {@inheritdoc}
   */
  public function getMetadataAttributes() {
    return [
      'shortcode' => $this
        ->t('Instagram shortcode'),
      'id' => $this
        ->t('Media ID'),
      'type' => $this
        ->t('Media type: image or video'),
      'thumbnail' => $this
        ->t('Link to the thumbnail'),
      'thumbnail_local' => $this
        ->t("Copies thumbnail locally and return it's URI"),
      'thumbnail_local_uri' => $this
        ->t('Returns local URI of the thumbnail'),
      'username' => $this
        ->t('Author of the post'),
      'caption' => $this
        ->t('Caption'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getMetadata(MediaInterface $media, $attribute_name) {
    if ($attribute_name == 'default_name') {

      // Try to get some fields that need the API, if not available, just use
      // the shortcode as default name.
      $username = $this
        ->getMetadata($media, 'username');
      $id = $this
        ->getMetadata($media, 'id');
      if ($username && $id) {
        return $username . ' - ' . $id;
      }
      else {
        $code = $this
          ->getMetadata($media, 'shortcode');
        if (!empty($code)) {
          return $code;
        }
      }

      // Fallback to the parent's default name if everything else failed.
      return parent::getMetadata($media, 'default_name');
    }
    elseif ($attribute_name == 'thumbnail_uri') {
      return $this
        ->getMetadata($media, 'thumbnail_local');
    }
    $matches = $this
      ->matchRegexp($media);
    if (!$matches['shortcode']) {
      return FALSE;
    }
    if ($attribute_name == 'shortcode') {
      return $matches['shortcode'];
    }

    // If we have auth settings return the other fields.
    if ($instagram = $this->fetcher
      ->fetchInstagramEmbed($matches['shortcode'])) {
      switch ($attribute_name) {
        case 'id':
          if (isset($instagram['media_id'])) {
            return $instagram['media_id'];
          }
          return FALSE;
        case 'type':
          if (isset($instagram['type'])) {
            return $instagram['type'];
          }
          return FALSE;
        case 'thumbnail':
          return 'http://instagram.com/p/' . $matches['shortcode'] . '/media/?size=m';
        case 'thumbnail_local':
          $local_uri = $this
            ->getMetadata($media, 'thumbnail_local_uri');
          if ($local_uri) {
            if (file_exists($local_uri)) {
              return $local_uri;
            }
            else {
              $directory = dirname($local_uri);
              $this->fileSystem
                ->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
              $image_url = $this
                ->getMetadata($media, 'thumbnail');
              $response = $this->httpClient
                ->get($image_url);
              if ($response
                ->getStatusCode() == 200) {
                return $this->fileSystem
                  ->saveData($response
                  ->getBody(), $local_uri, FileSystemInterface::EXISTS_REPLACE);
              }
            }
          }
          return FALSE;
        case 'thumbnail_local_uri':
          if (isset($instagram['thumbnail_url'])) {
            return $this->configFactory
              ->get('media_entity_instagram.settings')
              ->get('local_images') . '/' . $matches['shortcode'] . '.' . pathinfo(parse_url($instagram['thumbnail_url'], PHP_URL_PATH), PATHINFO_EXTENSION);
          }
          return FALSE;
        case 'username':
          if (isset($instagram['author_name'])) {
            return $instagram['author_name'];
          }
          return FALSE;
        case 'caption':
          if (isset($instagram['title'])) {
            return $instagram['title'];
          }
          return FALSE;
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getSourceFieldConstraints() {
    return [
      'InstagramEmbedCode' => [],
    ];
  }

  /**
   * Runs preg_match on embed code/URL.
   *
   * @param \Drupal\media\MediaInterface $media
   *   Media object.
   *
   * @return array|bool
   *   Array of preg matches or FALSE if no match.
   *
   * @see preg_match()
   */
  protected function matchRegexp(MediaInterface $media) {
    $matches = [];
    if (isset($this->configuration['source_field'])) {
      $source_field = $this->configuration['source_field'];
      if ($media
        ->hasField($source_field)) {
        $property_name = $media->{$source_field}
          ->first()
          ->mainPropertyName();
        foreach (static::$validationRegexp as $pattern => $key) {
          if (preg_match($pattern, $media->{$source_field}->{$property_name}, $matches)) {
            return $matches;
          }
        }
      }
    }
    return FALSE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
Instagram::$fetcher protected property The instagram fetcher.
Instagram::$fileSystem protected property The file system service.
Instagram::$httpClient protected property Guzzle client.
Instagram::$validationRegexp public static property List of validation regular expressions.
Instagram::create public static function Creates an instance of the plugin. Overrides MediaSourceBase::create
Instagram::getMetadata public function Gets the value for a metadata attribute for a given media item. Overrides MediaSourceBase::getMetadata
Instagram::getMetadataAttributes public function Gets a list of metadata attributes provided by this plugin. Overrides MediaSourceInterface::getMetadataAttributes
Instagram::getSourceFieldConstraints public function Gets media source-specific validation constraints for a source field. Overrides MediaSourceFieldConstraintsInterface::getSourceFieldConstraints
Instagram::matchRegexp protected function Runs preg_match on embed code/URL.
Instagram::__construct public function Constructs a new class instance. Overrides MediaSourceBase::__construct
MediaSourceBase::$configFactory protected property The config factory service.
MediaSourceBase::$entityFieldManager protected property The entity field manager service.
MediaSourceBase::$entityTypeManager protected property The entity type manager service.
MediaSourceBase::$fieldTypeManager protected property The field type plugin manager service.
MediaSourceBase::$label protected property Plugin label.
MediaSourceBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 2
MediaSourceBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
MediaSourceBase::createSourceField public function Creates the source field definition for a type. Overrides MediaSourceInterface::createSourceField 2
MediaSourceBase::createSourceFieldStorage protected function Creates the source field storage definition.
MediaSourceBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 2
MediaSourceBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
MediaSourceBase::getSourceFieldDefinition public function Get the source field definition for a media type. Overrides MediaSourceInterface::getSourceFieldDefinition
MediaSourceBase::getSourceFieldName protected function Determine the name of the source field. 2
MediaSourceBase::getSourceFieldOptions protected function Get the source field options for the media type form.
MediaSourceBase::getSourceFieldStorage protected function Returns the source field storage definition.
MediaSourceBase::getSourceFieldValue public function Get the primary value stored in the source field. Overrides MediaSourceInterface::getSourceFieldValue
MediaSourceBase::prepareFormDisplay public function Prepares the media type fields for this source in the form display. Overrides MediaSourceInterface::prepareFormDisplay 3
MediaSourceBase::prepareViewDisplay public function Prepares the media type fields for this source in the view display. Overrides MediaSourceInterface::prepareViewDisplay 6
MediaSourceBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
MediaSourceBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm 1
MediaSourceBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 1
MediaSourceInterface::METADATA_FIELD_EMPTY constant Default empty value for metadata fields.
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.
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.