RefreshInstagramTokenAction.php in Instagram Feeds 8
File
src/Plugin/Action/RefreshInstagramTokenAction.php
View source
<?php
namespace Drupal\instagram_feeds\Plugin\Action;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Action\Plugin\Action\EntityActionBase;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use GuzzleHttp\ClientInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
final class RefreshInstagramTokenAction extends EntityActionBase {
protected $time;
protected $httpClient;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, TimeInterface $time, ClientInterface $http_client) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
$this->time = $time;
$this->httpClient = $http_client;
}
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('datetime.time'), $container
->get('http_client'));
}
public function execute($entity = NULL) {
$entity
->refreshToken($this->httpClient, TRUE);
}
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
if (!$account) {
$account = \Drupal::currentUser();
}
if (!$object
->isPublished() || !$object
->tokenIsValid()) {
$result = AccessResult::forbidden('Unpublished or Instagram token is invalid.')
->addCacheableDependency($object);
return $return_as_object ? $result : $result
->isAllowed();
}
$primary_access = $account
->hasPermission('administer instagram_feeds');
$role_access = $primary_access || $account
->hasPermission('update instagram_account');
$user_access = $role_access || $account
->id() == $object
->getOwnerId() && $account
->hasPermission('update own instagram_account');
if (!$user_access) {
$result = AccessResult::forbidden()
->cachePerPermissions();
return $return_as_object ? $result : $result
->isAllowed();
}
$age = $object
->getTokenExpirationTime() - $this->time
->getRequestTime();
if ($age <= 5097600) {
$result = AccessResult::allowed()
->setCacheMaxAge($age)
->cachePerPermissions()
->addCacheableDependency($object);
return $return_as_object ? $result : $result
->isAllowed();
}
$age -= 5097600;
$result = AccessResult::forbidden('You should wait at least 24 hours prior previous token refesh')
->setCacheMaxAge($age)
->cachePerPermissions();
return $return_as_object ? $result : $result
->isAllowed();
}
}