You are here

public function Twitter::getField in Media entity Twitter 8

Gets a media-related field/value.

Parameters

MediaInterface $media: Media object.

string $name: Name of field to fetch.

Return value

mixed Field value or FALSE if data unavailable.

Overrides MediaTypeInterface::getField

2 calls to Twitter::getField()
Twitter::getDefaultName in src/Plugin/MediaEntity/Type/Twitter.php
Provide a default name for the media.
Twitter::thumbnail in src/Plugin/MediaEntity/Type/Twitter.php
Gets thumbnail image.

File

src/Plugin/MediaEntity/Type/Twitter.php, line 148

Class

Twitter
Provides media type plugin for Twitter.

Namespace

Drupal\media_entity_twitter\Plugin\MediaEntity\Type

Code

public function getField(MediaInterface $media, $name) {
  $matches = $this
    ->matchRegexp($media);
  if (!$matches['id']) {
    return FALSE;
  }

  // First we return the fields that are available from regex.
  switch ($name) {
    case 'id':
      return $matches['id'];
    case 'user':
      if ($matches['user']) {
        return $matches['user'];
      }
      return FALSE;
  }

  // If we have auth settings return the other fields.
  if ($this->configuration['use_twitter_api'] && ($tweet = $this
    ->fetchTweet($matches['id']))) {
    switch ($name) {
      case 'image':
        if (isset($tweet['extended_entities']['media'][0]['media_url'])) {
          return $tweet['extended_entities']['media'][0]['media_url'];
        }
        return FALSE;
      case 'image_local':
        $local_uri = $this
          ->getField($media, 'image_local_uri');
        if ($local_uri) {
          if (file_exists($local_uri)) {
            return $local_uri;
          }
          else {
            $image_url = $this
              ->getField($media, 'image');

            // @TODO: Use Guzzle, possibly in a service, for this.
            $image_data = file_get_contents($image_url);
            if ($image_data) {
              return file_unmanaged_save_data($image_data, $local_uri, FILE_EXISTS_REPLACE);
            }
          }
        }
        return FALSE;
      case 'image_local_uri':
        $image_url = $this
          ->getField($media, 'image');
        if ($image_url) {
          return $this
            ->getLocalImageUri($matches['id'], $image_url);
        }
        return FALSE;
      case 'content':
        if (isset($tweet['text'])) {
          return $tweet['text'];
        }
        return FALSE;
      case 'retweet_count':
        if (isset($tweet['retweet_count'])) {
          return $tweet['retweet_count'];
        }
        return FALSE;
      case 'profile_image_url_https':
        if (isset($tweet['user']['profile_image_url_https'])) {
          return $tweet['user']['profile_image_url_https'];
        }
        return FALSE;
    }
  }
  return FALSE;
}