You are here

protected function InstagramPostsObtainedSubscriber::getAvatarFromPostPermalink in Instagram Feeds 8

Scrape the Instagram post owner avatar URL using permalink URL.

Parameters

\Drupal\instagram_feeds\Event\InstagramPostsObtainedEvent $event: Instance of InstagramPostsObtainedEvent.

Return value

string[] An array with 'target_id' and 'alt' keys to fill in file reference field.

Throws

\Exception

1 call to InstagramPostsObtainedSubscriber::getAvatarFromPostPermalink()
InstagramPostsObtainedSubscriber::onInstagramPostsObtained in src/EventSubscriber/InstagramPostsObtainedSubscriber.php
Reacts on posts obtained event.

File

src/EventSubscriber/InstagramPostsObtainedSubscriber.php, line 93

Class

InstagramPostsObtainedSubscriber
Subscriber to InstagramPostsObtainedEvent event.

Namespace

Drupal\instagram_feeds\EventSubscriber

Code

protected function getAvatarFromPostPermalink(InstagramPostsObtainedEvent $event) {
  $permalink_url = $event->posts[0]['permalink'];
  $account = $event
    ->getAccount();
  $avatar_dir = $event
    ->getConfig('avatar_uri_scheme') . '://' . $event
    ->getConfig('avatar_directory');
  $full_name = $account
    ->getAccountName();
  try {
    $shards = explode('window._sharedData = ', $this
      ->getInstagramResponceContents($permalink_url));
    $insta_encoded_json = explode(';</script>', $shards[1]);
    $insta_array = Json::decode($insta_encoded_json[0]);
    $owner = $insta_array['entry_data']['PostPage'][0]['graphql']['shortcode_media']['owner'] ?? [];
    if (!empty($owner['profile_pic_url']) && $this
      ->prepareDirectory($avatar_dir)) {
      $file_data = file_get_contents($owner['profile_pic_url']);
      $full_name = $owner['full_name'] ?? 'Instagram Avatar';
      $avatar_file_extension = pathinfo(parse_url($owner['profile_pic_url'], PHP_URL_PATH), PATHINFO_EXTENSION);
      $file_uri_destination = $avatar_dir . '/' . $account
        ->id() . '.' . $avatar_file_extension;
      $file = file_save_data($file_data, $file_uri_destination, $this->file_exists_replace);
    }
  } catch (\Exception $e) {
    $this
      ->logger()
      ->error($e
      ->getMessage());
  }
  return !empty($file) ? [
    'target_id' => $file
      ->id(),
    'alt' => $full_name,
  ] : [];
}