<?php
 namespace League\OAuth2\Client\Token; use InvalidArgumentException; use RuntimeException; class AccessToken implements AccessTokenInterface, ResourceOwnerAccessTokenInterface, SettableRefreshTokenInterface { protected $accessToken; protected $expires; protected $refreshToken; protected $resourceOwnerId; protected $values = []; private static $timeNow; public static function setTimeNow($timeNow) { self::$timeNow = $timeNow; } public static function resetTimeNow() { self::$timeNow = null; } public function getTimeNow() { return self::$timeNow ? self::$timeNow : time(); } public function __construct(array $options = []) { if (empty($options['access_token'])) { throw new InvalidArgumentException('Required option not passed: "access_token"'); } $this->accessToken = $options['access_token']; if (!empty($options['resource_owner_id'])) { $this->resourceOwnerId = $options['resource_owner_id']; } if (!empty($options['refresh_token'])) { $this->refreshToken = $options['refresh_token']; } if (isset($options['expires_in'])) { if (!is_numeric($options['expires_in'])) { throw new \InvalidArgumentException('expires_in value must be an integer'); } $this->expires = $options['expires_in'] != 0 ? $this->getTimeNow() + $options['expires_in'] : 0; } elseif (!empty($options['expires'])) { $expires = (int) $options['expires']; if (!$this->isExpirationTimestamp($expires)) { $expires += $this->getTimeNow(); } $this->expires = $expires; } $this->values = array_diff_key($options, array_flip([ 'access_token', 'resource_owner_id', 'refresh_token', 'expires_in', 'expires', ])); } protected function isExpirationTimestamp($value) { $oauth2InceptionDate = 1349067600; return ($value > $oauth2InceptionDate); } public function getToken() { return $this->accessToken; } public function getRefreshToken() { return $this->refreshToken; } public function setRefreshToken($refreshToken) { $this->refreshToken = $refreshToken; } public function getExpires() { return $this->expires; } public function getResourceOwnerId() { return $this->resourceOwnerId; } public function hasExpired() { $expires = $this->getExpires(); if (empty($expires)) { throw new RuntimeException('"expires" is not set on the token'); } return $expires < $this->getTimeNow(); } public function getValues() { return $this->values; } public function __toString() { return (string) $this->getToken(); } public function jsonSerialize() { $parameters = $this->values; if ($this->accessToken) { $parameters['access_token'] = $this->accessToken; } if ($this->refreshToken) { $parameters['refresh_token'] = $this->refreshToken; } if ($this->expires) { $parameters['expires'] = $this->expires; } if ($this->resourceOwnerId) { $parameters['resource_owner_id'] = $this->resourceOwnerId; } return $parameters; } } 