updated-packages

This commit is contained in:
RafficMohammed
2023-01-08 00:13:22 +05:30
parent 3ff7df7487
commit da241bacb6
12659 changed files with 563377 additions and 510538 deletions

View File

@@ -1,4 +1,7 @@
/build
/vendor
/composer.lock
/coverage.xml
/.phpunit.result.cache
/.php_cs.cache
.DS_Store

View File

@@ -0,0 +1,29 @@
<?php
$finder = PhpCsFixer\Finder::create()->in([__DIR__ . '/src', __DIR__ . '/tests']);
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => true,
'blank_line_before_return' => true,
'cast_spaces' => true,
'concat_space' => ['spacing' => 'one'],
'no_singleline_whitespace_before_semicolons' => true,
'not_operator_with_space' => true,
'ordered_imports' => true,
'phpdoc_align' => true,
'phpdoc_indent' => true,
'phpdoc_no_access' => true,
'phpdoc_no_alias_tag' => true,
'phpdoc_no_package' => true,
'phpdoc_scalar' => true,
'phpdoc_separation' => true,
'phpdoc_summary' => true,
'phpdoc_to_comment' => true,
'phpdoc_trim' => true,
'single_blank_line_at_eof' => true,
'ternary_operator_spaces' => true,
])
->setFinder($finder);

View File

@@ -1,22 +1,57 @@
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
matrix:
include:
- php: 7.1
dist: bionic
env: COMPOSER_OPTS=""
- php: 7.1
dist: bionic
env: COMPOSER_OPTS="--prefer-lowest"
- php: 7.2
dist: bionic
env: COMPOSER_OPTS=""
- php: 7.2
dist: bionic
env: COMPOSER_OPTS="--prefer-lowest"
- php: 7.3
dist: bionic
env: COMPOSER_OPTS=""
- php: 7.3
dist: bionic
env: COMPOSER_OPTS="--prefer-lowest"
- php: 7.4
dist: bionic
env: COMPOSER_OPTS=""
- php: 7.4
dist: bionic
env: COMPOSER_OPTS="--prefer-lowest"
- php: 8.0
dist: bionic
env: COMPOSER_OPTS=""
- php: 8.0
dist: bionic
env: COMPOSER_OPTS="--prefer-lowest"
- php: nightly
dist: bionic
env: COMPOSER_OPTS="--ignore-platform-reqs"
- php: nightly
dist: bionic
env: COMPOSER_OPTS="--ignore-platform-reqs --prefer-lowest"
allow_failures:
- php: nightly
env: COMPOSER_OPTS="--ignore-platform-reqs"
- php: nightly
env: COMPOSER_OPTS="--ignore-platform-reqs --prefer-lowest"
before_script:
- travis_retry composer self-update
- travis_retry composer install --no-interaction --prefer-source --dev
- travis_retry phpenv rehash
install:
- travis_retry composer update --prefer-dist $COMPOSER_OPTS
script:
- ./vendor/bin/phpcs --standard=psr2 src/
- ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover
- composer php-cs-fixer:lint
- composer test:unit
- composer analyze
after_script:
- if [ "$TRAVIS_PHP_VERSION" != "hhvm" ] && [ "$TRAVIS_PHP_VERSION" != "7.0" ]; then wget https://scrutinizer-ci.com/ocular.phar; fi
- if [ "$TRAVIS_PHP_VERSION" != "hhvm" ] && [ "$TRAVIS_PHP_VERSION" != "7.0" ]; then php ocular.phar code-coverage:upload --format=php-clover coverage.clover; fi
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover coverage.xml

View File

@@ -0,0 +1,40 @@
# Changelog
## v1.10.1
- Fix deprecation error (#147)
## v1.10.0
- Adds customizable application scope (setting the `x_auth_access_type` query parameter when fetching temporary credentials) on the Twitter provider - thanks to @Diegslapasteque
## v1.9.3
- Reverts bug in `v1.9.1` and will reintroduce `x_auth_access_type` to Twitter provider in `v1.10.0`.
## v1.9.2
- Adds `x_auth_access_type` to Twitter provider - thanks to @Diegslapasteque
## v1.9.1
- Remove deprecated Guzzle function call.
## v1.9.0
- Adds support for PHP 8.0.
- Allows optional authorization URL parameters to be passed.
## v1.8.2
- Fixes an issue where the base string used to generate signatures did not account for non-standard ports.
## v1.8.1
- Reverts the public API changes introduced in v1.8.0 where language level type declarations and return types that were introduced caused inheritence to break.
- Fixes a Composer warning with relation to autoloading test files.
## v1.8.0
- We allow installation with Guzzle 6 **or** Guzzle 7.
- The minimum PHP version has been bumped from PHP 5.6 to 7.1.

View File

@@ -12,12 +12,14 @@ OAuth 1 Client is an OAuth [RFC 5849 standards-compliant](http://tools.ietf.org/
It has built in support for:
- Bitbucket
- Magento
- Trello
- Tumblr
- Twitter
- Uservoice
- Xing
Adding support for other providers is trivial. The library requires PHP 5.3+ and is PSR-2 compatible.
Adding support for other providers is trivial. The library requires PHP 7.1+ and is PSR-2 compatible.
### Third-Party Providers
@@ -31,6 +33,8 @@ so please help them out with a pull request if you notice this.
- [500px](https://packagist.org/packages/mechant/oauth1-500px)
- [Etsy](https://packagist.org/packages/y0lk/oauth1-etsy)
- [Xero](https://packagist.org/packages/Invoiced/oauth1-xero)
- [Garmin](https://packagist.org/packages/techgyani/garmin-wellness)
- [Goodreads](https://packagist.org/packages/netgalley/oauth1-goodreads)
#### Terminology (as per the RFC 5849 specification):
@@ -96,54 +100,55 @@ $ composer require league/oauth1-client
### Bitbucket
```php
$server = new League\OAuth1\Client\Server\Bitbucket(array(
$server = new League\OAuth1\Client\Server\Bitbucket([
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
));
]);
```
### Trello
```php
$server = new League\OAuth1\Client\Server\Trello(array(
$server = new League\OAuth1\Client\Server\Trello([
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => 'http://your-callback-uri/',
'name' => 'your-application-name', // optional, defaults to null
'expiration' => 'your-application-expiration', // optional ('never', '1day', '2days'), defaults to '1day'
'scope' => 'your-application-scope' // optional ('read', 'read,write'), defaults to 'read'
));
]);
```
### Tumblr
```php
$server = new League\OAuth1\Client\Server\Tumblr(array(
$server = new League\OAuth1\Client\Server\Tumblr([
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
));
]);
```
### Twitter
```php
$server = new League\OAuth1\Client\Server\Twitter(array(
$server = new League\OAuth1\Client\Server\Twitter([
'identifier' => 'your-identifier',
'secret' => 'your-secret',
'callback_uri' => "http://your-callback-uri/",
));
'scope' => 'your-application-scope' // optional ('read', 'write'), empty by default
]);
```
### Xing
```php
$server = new League\OAuth1\Client\Server\Xing(array(
$server = new League\OAuth1\Client\Server\Xing([
'identifier' => 'your-consumer-key',
'secret' => 'your-consumer-secret',
'callback_uri' => "http://your-callback-uri/",
));
]);
```
### Showing a Login Button

View File

@@ -3,13 +3,27 @@
"description": "OAuth 1.0 Client Library",
"license": "MIT",
"require": {
"php": ">=5.5.0",
"guzzlehttp/guzzle": "^6.0"
"php": ">=7.1||>=8.0",
"ext-json": "*",
"ext-openssl": "*",
"guzzlehttp/guzzle": "^6.0|^7.0",
"guzzlehttp/psr7": "^1.7|^2.0"
},
"require-dev": {
"phpunit/phpunit": "^4.0",
"mockery/mockery": "^0.9",
"squizlabs/php_codesniffer": "^2.0"
"ext-simplexml": "*",
"phpunit/phpunit": "^7.5||9.5",
"mockery/mockery": "^1.3.3",
"phpstan/phpstan": "^0.12.42",
"friendsofphp/php-cs-fixer": "^2.17"
},
"scripts": {
"analyze": "vendor/bin/phpstan analyse -l 6 src/",
"php-cs-fixer:lint": "PHP_CS_FIXER_IGNORE_ENV=1 vendor/bin/php-cs-fixer fix --verbose --dry-run",
"php-cs-fixer:format": "PHP_CS_FIXER_IGNORE_ENV=1 vendor/bin/php-cs-fixer fix",
"test:unit": "vendor/bin/phpunit --coverage-text --coverage-clover coverage.xml"
},
"suggest": {
"ext-simplexml": "For decoding XML-based responses."
},
"keywords": [
"oauth",
@@ -35,12 +49,18 @@
],
"autoload": {
"psr-4": {
"League\\OAuth1\\": "src/"
"League\\OAuth1\\Client\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"League\\OAuth1\\Client\\Tests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
"dev-master": "1.0-dev",
"dev-develop": "2.0-dev"
}
}
}

View File

@@ -0,0 +1,11 @@
parameters:
checkMissingIterableValueType: false
checkGenericClassInNonGenericObjectType: false
ignoreErrors:
-
message: '#has unknown class OpenSSLAsymmetricKey as its type#'
path: src/Credentials/RsaClientCredentials.php
-
message: '#invalid type OpenSSLAsymmetricKey#'
path: src/Credentials/RsaClientCredentials.php
reportUnmatchedIgnoredErrors: false

View File

@@ -0,0 +1,5 @@
<?php
include __DIR__ . '/vendor/autoload.php';
date_default_timezone_set('UTC');

View File

@@ -1,28 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true"
stopOnFailure="false"
bootstrap="./vendor/autoload.php"
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="./phpunit.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true">
<logging>
<log type="coverage-html"
target="./build/coverage/html"
charset="UTF-8"
highlight="false"
lowUpperBound="35"
highLowerBound="70"/>
<log type="coverage-clover"
target="./build/coverage/log/coverage.xml"/>
</logging>
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
verbose="true"
>
<testsuites>
<testsuite name="common">
<directory suffix="Test.php">tests</directory>
<testsuite name="oauth1-client/tests">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./src/</directory>
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-text" target="php://stdout" showUncoveredFiles="true"/>
<log type="coverage-clover" target="coverage.xml" showUncoveredFiles="true"/>
</logging>
</phpunit>

View File

@@ -1,100 +0,0 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
class Twitter extends Server
{
/**
* {@inheritDoc}
*/
public function urlTemporaryCredentials()
{
return 'https://api.twitter.com/oauth/request_token';
}
/**
* {@inheritDoc}
*/
public function urlAuthorization()
{
return 'https://api.twitter.com/oauth/authenticate';
}
/**
* {@inheritDoc}
*/
public function urlTokenCredentials()
{
return 'https://api.twitter.com/oauth/access_token';
}
/**
* {@inheritDoc}
*/
public function urlUserDetails()
{
return 'https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true';
}
/**
* {@inheritDoc}
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
$user = new User();
$user->uid = $data['id_str'];
$user->nickname = $data['screen_name'];
$user->name = $data['name'];
$user->location = $data['location'];
$user->description = $data['description'];
$user->imageUrl = $data['profile_image_url'];
$user->email = null;
if (isset($data['email'])) {
$user->email = $data['email'];
}
$used = array('id', 'screen_name', 'name', 'location', 'description', 'profile_image_url', 'email');
foreach ($data as $key => $value) {
if (strpos($key, 'url') !== false) {
if (!in_array($key, $used)) {
$used[] = $key;
}
$user->urls[$key] = $value;
}
}
// Save all extra data
$user->extra = array_diff_key($data, array_flip($used));
return $user;
}
/**
* {@inheritDoc}
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
return $data['id'];
}
/**
* {@inheritDoc}
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return;
}
/**
* {@inheritDoc}
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['name'];
}
}

View File

@@ -1,125 +0,0 @@
<?php
namespace League\OAuth1\Client\Signature;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Uri;
class HmacSha1Signature extends Signature implements SignatureInterface
{
/**
* {@inheritDoc}
*/
public function method()
{
return 'HMAC-SHA1';
}
/**
* {@inheritDoc}
*/
public function sign($uri, array $parameters = array(), $method = 'POST')
{
$url = $this->createUrl($uri);
$baseString = $this->baseString($url, $method, $parameters);
return base64_encode($this->hash($baseString));
}
/**
* Create a Guzzle url for the given URI.
*
* @param string $uri
*
* @return Url
*/
protected function createUrl($uri)
{
return Psr7\uri_for($uri);
}
/**
* Generate a base string for a HMAC-SHA1 signature
* based on the given a url, method, and any parameters.
*
* @param Url $url
* @param string $method
* @param array $parameters
*
* @return string
*/
protected function baseString(Uri $url, $method = 'POST', array $parameters = array())
{
$baseString = rawurlencode($method).'&';
$schemeHostPath = Uri::fromParts(array(
'scheme' => $url->getScheme(),
'host' => $url->getHost(),
'path' => $url->getPath(),
));
$baseString .= rawurlencode($schemeHostPath).'&';
$data = array();
parse_str($url->getQuery(), $query);
$data = array_merge($query, $parameters);
// normalize data key/values
array_walk_recursive($data, function (&$key, &$value) {
$key = rawurlencode(rawurldecode($key));
$value = rawurlencode(rawurldecode($value));
});
ksort($data);
$baseString .= $this->queryStringFromData($data);
return $baseString;
}
/**
* Creates an array of rawurlencoded strings out of each array key/value pair
* Handles multi-demensional arrays recursively.
*
* @param array $data Array of parameters to convert.
* @param array $queryParams Array to extend. False by default.
* @param string $prevKey Optional Array key to append
*
* @return string rawurlencoded string version of data
*/
protected function queryStringFromData($data, $queryParams = false, $prevKey = '')
{
if ($initial = (false === $queryParams)) {
$queryParams = array();
}
foreach ($data as $key => $value) {
if ($prevKey) {
$key = $prevKey.'['.$key.']'; // Handle multi-dimensional array
}
if (is_array($value)) {
$queryParams = $this->queryStringFromData($value, $queryParams, $key);
} else {
$queryParams[] = rawurlencode($key.'='.$value); // join with equals sign
}
}
if ($initial) {
return implode('%26', $queryParams); // join with ampersand
}
return $queryParams;
}
/**
* Hashes a string with the signature's key.
*
* @param string $string
*
* @return string
*/
protected function hash($string)
{
return hash_hmac('sha1', $string, $this->key(), true);
}
}

View File

@@ -12,7 +12,7 @@ class ClientCredentials extends Credentials implements ClientCredentialsInterfac
protected $callbackUri;
/**
* {@inheritDoc}
* @inheritDoc
*/
public function getCallbackUri()
{
@@ -20,7 +20,7 @@ class ClientCredentials extends Credentials implements ClientCredentialsInterfac
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function setCallbackUri($callbackUri)
{

View File

@@ -14,7 +14,9 @@ interface ClientCredentialsInterface extends CredentialsInterface
/**
* Set the credentials callback URI.
*
* @return string
* @param string $callbackUri
*
* @return void
*/
public function setCallbackUri($callbackUri);
}

View File

@@ -19,7 +19,7 @@ abstract class Credentials implements CredentialsInterface
protected $secret;
/**
* {@inheritDoc}
* @inheritDoc
*/
public function getIdentifier()
{
@@ -27,7 +27,7 @@ abstract class Credentials implements CredentialsInterface
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function setIdentifier($identifier)
{
@@ -35,7 +35,7 @@ abstract class Credentials implements CredentialsInterface
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function getSecret()
{
@@ -43,7 +43,7 @@ abstract class Credentials implements CredentialsInterface
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function setSecret($secret)
{

View File

@@ -15,6 +15,8 @@ interface CredentialsInterface
* Set the credentials identifier.
*
* @param string $identifier
*
* @return void
*/
public function setIdentifier($identifier);
@@ -29,6 +31,8 @@ interface CredentialsInterface
* Set the credentials secret.
*
* @param string $secret
*
* @return void
*/
public function setSecret($secret);
}

View File

@@ -0,0 +1,110 @@
<?php
namespace League\OAuth1\Client\Credentials;
use OpenSSLAsymmetricKey;
class RsaClientCredentials extends ClientCredentials
{
/**
* @var string
*/
protected $rsaPublicKeyFile;
/**
* @var string
*/
protected $rsaPrivateKeyFile;
/**
* @var resource|OpenSSLAsymmetricKey|null
*/
protected $rsaPublicKey;
/**
* @var resource|OpenSSLAsymmetricKey|null
*/
protected $rsaPrivateKey;
/**
* Sets the path to the RSA public key.
*
* @param string $filename
*
* @return self
*/
public function setRsaPublicKey($filename)
{
$this->rsaPublicKeyFile = $filename;
$this->rsaPublicKey = null;
return $this;
}
/**
* Sets the path to the RSA private key.
*
* @param string $filename
*
* @return self
*/
public function setRsaPrivateKey($filename)
{
$this->rsaPrivateKeyFile = $filename;
$this->rsaPrivateKey = null;
return $this;
}
/**
* Gets the RSA public key.
*
* @throws CredentialsException when the key could not be loaded.
*
* @return resource|OpenSSLAsymmetricKey
*/
public function getRsaPublicKey()
{
if ($this->rsaPublicKey) {
return $this->rsaPublicKey;
}
if ( ! file_exists($this->rsaPublicKeyFile)) {
throw new CredentialsException('Could not read the public key file.');
}
$this->rsaPublicKey = openssl_get_publickey(file_get_contents($this->rsaPublicKeyFile));
if ( ! $this->rsaPublicKey) {
throw new CredentialsException('Cannot access public key for signing');
}
return $this->rsaPublicKey;
}
/**
* Gets the RSA private key.
*
* @throws CredentialsException when the key could not be loaded.
*
* @return resource|OpenSSLAsymmetricKey
*/
public function getRsaPrivateKey()
{
if ($this->rsaPrivateKey) {
return $this->rsaPrivateKey;
}
if ( ! file_exists($this->rsaPrivateKeyFile)) {
throw new CredentialsException('Could not read the private key file.');
}
$this->rsaPrivateKey = openssl_pkey_get_private(file_get_contents($this->rsaPrivateKeyFile));
if ( ! $this->rsaPrivateKey) {
throw new CredentialsException('Cannot access private key for signing');
}
return $this->rsaPrivateKey;
}
}

View File

@@ -7,7 +7,7 @@ use League\OAuth1\Client\Credentials\TokenCredentials;
class Bitbucket extends Server
{
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
@@ -15,7 +15,7 @@ class Bitbucket extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlAuthorization()
{
@@ -23,7 +23,7 @@ class Bitbucket extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTokenCredentials()
{
@@ -31,7 +31,7 @@ class Bitbucket extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlUserDetails()
{
@@ -39,7 +39,7 @@ class Bitbucket extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
@@ -52,11 +52,11 @@ class Bitbucket extends Server
$user->lastName = $data['user']['last_name'];
$user->imageUrl = $data['user']['avatar'];
$used = array('username', 'display_name', 'avatar');
$used = ['username', 'display_name', 'avatar'];
foreach ($data as $key => $value) {
if (strpos($key, 'url') !== false) {
if (!in_array($key, $used)) {
if ( ! in_array($key, $used)) {
$used[] = $key;
}
@@ -71,7 +71,7 @@ class Bitbucket extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
@@ -79,15 +79,15 @@ class Bitbucket extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return;
return null;
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{

View File

@@ -4,6 +4,7 @@ namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TemporaryCredentials;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\SignatureInterface;
/**
* Magento OAuth 1.0a.
@@ -48,7 +49,7 @@ class Magento extends Server
private $verifier;
/**
* {@inheritDoc}
* @inheritDoc
*/
public function __construct($clientCredentials, SignatureInterface $signature = null)
{
@@ -59,45 +60,45 @@ class Magento extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
return $this->baseUri.'/oauth/initiate';
return $this->baseUri . '/oauth/initiate';
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlAuthorization()
{
return $this->isAdmin
? $this->adminUrl
: $this->baseUri.'/oauth/authorize';
: $this->baseUri . '/oauth/authorize';
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTokenCredentials()
{
return $this->baseUri.'/oauth/token';
return $this->baseUri . '/oauth/token';
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlUserDetails()
{
return $this->baseUri.'/api/rest/customers';
return $this->baseUri . '/api/rest/customers';
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
if (!is_array($data) || !count($data)) {
if ( ! is_array($data) || ! count($data)) {
throw new \Exception('Not possible to get user info');
}
@@ -107,13 +108,13 @@ class Magento extends Server
$user = new User();
$user->uid = $id;
$mapping = array(
$mapping = [
'email' => 'email',
'firstName' => 'firstname',
'lastName' => 'lastname',
);
'lastName' => 'lastname',
];
foreach ($mapping as $userKey => $dataKey) {
if (!isset($data[$dataKey])) {
if ( ! isset($data[$dataKey])) {
continue;
}
$user->{$userKey} = $data[$dataKey];
@@ -125,7 +126,7 @@ class Magento extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
@@ -133,27 +134,29 @@ class Magento extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
$data = current($data);
if (!isset($data['email'])) {
return;
if ( ! isset($data['email'])) {
return null;
}
return $data['email'];
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return;
return null;
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function getTokenCredentials(TemporaryCredentials $temporaryCredentials, $temporaryIdentifier, $verifier)
{
@@ -163,13 +166,13 @@ class Magento extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
protected function additionalProtocolParameters()
{
return array(
return [
'oauth_verifier' => $this->verifier,
);
];
}
protected function getHttpClientDefaultHeaders()
@@ -185,28 +188,31 @@ class Magento extends Server
* Parse configuration array to set attributes.
*
* @param array $configuration
*
* @return void
*
* @throws \Exception
*/
private function parseConfigurationArray(array $configuration = array())
private function parseConfigurationArray(array $configuration = [])
{
if (!isset($configuration['host'])) {
if ( ! isset($configuration['host'])) {
throw new \Exception('Missing Magento Host');
}
$url = parse_url($configuration['host']);
$this->baseUri = sprintf('%s://%s', $url['scheme'], $url['host']);
if (isset($url['port'])) {
$this->baseUri .= ':'.$url['port'];
$this->baseUri .= ':' . $url['port'];
}
if (isset($url['path'])) {
$this->baseUri .= '/'.trim($url['path'], '/');
$this->baseUri .= '/' . trim($url['path'], '/');
}
$this->isAdmin = !empty($configuration['admin']);
if (!empty($configuration['adminUrl'])) {
$this->adminUrl = $configuration['adminUrl'].'/oauth_authorize';
$this->isAdmin = ! empty($configuration['admin']);
if ( ! empty($configuration['adminUrl'])) {
$this->adminUrl = $configuration['adminUrl'] . '/oauth_authorize';
} else {
$this->adminUrl = $this->baseUri.'/admin/oauth_authorize';
$this->adminUrl = $this->baseUri . '/admin/oauth_authorize';
}
}
}

View File

@@ -4,21 +4,25 @@ namespace League\OAuth1\Client\Server;
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\BadResponseException;
use League\OAuth1\Client\Credentials\ClientCredentialsInterface;
use League\OAuth1\Client\Credentials\ClientCredentials;
use League\OAuth1\Client\Credentials\CredentialsInterface;
use League\OAuth1\Client\Credentials\ClientCredentialsInterface;
use League\OAuth1\Client\Credentials\CredentialsException;
use League\OAuth1\Client\Credentials\CredentialsInterface;
use League\OAuth1\Client\Credentials\RsaClientCredentials;
use League\OAuth1\Client\Credentials\TemporaryCredentials;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\HmacSha1Signature;
use League\OAuth1\Client\Signature\RsaSha1Signature;
use League\OAuth1\Client\Signature\SignatureInterface;
use SimpleXMLElement;
use Throwable;
abstract class Server
{
/**
* Client credentials.
*
* @var ClientCredentials
* @var ClientCredentialsInterface
*/
protected $clientCredentials;
@@ -39,7 +43,7 @@ abstract class Server
/**
* Cached user details response.
*
* @var unknown
* @var array|SimpleXMLElement
*/
protected $cachedUserDetailsResponse;
@@ -61,11 +65,15 @@ abstract class Server
// Pass through an array or client credentials, we don't care
if (is_array($clientCredentials)) {
$clientCredentials = $this->createClientCredentials($clientCredentials);
} elseif (!$clientCredentials instanceof ClientCredentialsInterface) {
} elseif ( ! $clientCredentials instanceof ClientCredentialsInterface) {
throw new \InvalidArgumentException('Client credentials must be an array or valid object.');
}
$this->clientCredentials = $clientCredentials;
if ( ! $signature && $clientCredentials instanceof RsaClientCredentials) {
$signature = new RsaSha1Signature($clientCredentials);
}
$this->signature = $signature ?: new HmacSha1Signature($clientCredentials);
}
@@ -74,6 +82,8 @@ abstract class Server
* the server.
*
* @return TemporaryCredentials
*
* @throws CredentialsException
*/
public function getTemporaryCredentials()
{
@@ -82,18 +92,20 @@ abstract class Server
$client = $this->createHttpClient();
$header = $this->temporaryCredentialsProtocolHeader($uri);
$authorizationHeader = array('Authorization' => $header);
$authorizationHeader = ['Authorization' => $header];
$headers = $this->buildHttpClientHeaders($authorizationHeader);
try {
$response = $client->post($uri, [
'headers' => $headers,
]);
return $this->createTemporaryCredentials((string) $response->getBody());
} catch (BadResponseException $e) {
return $this->handleTemporaryCredentialsBadResponse($e);
$this->handleTemporaryCredentialsBadResponse($e);
}
return $this->createTemporaryCredentials((string) $response->getBody());
throw new CredentialsException('Failed to get temporary credentials');
}
/**
@@ -101,10 +113,11 @@ abstract class Server
* identifier or an object instance.
*
* @param TemporaryCredentials|string $temporaryIdentifier
* @param array $options
*
* @return string
*/
public function getAuthorizationUrl($temporaryIdentifier)
public function getAuthorizationUrl($temporaryIdentifier, array $options = [])
{
// Somebody can pass through an instance of temporary
// credentials and we'll extract the identifier from there.
@@ -112,7 +125,7 @@ abstract class Server
$temporaryIdentifier = $temporaryIdentifier->getIdentifier();
}
$parameters = array('oauth_token' => $temporaryIdentifier);
$parameters = array_merge($options, ['oauth_token' => $temporaryIdentifier]);
$url = $this->urlAuthorization();
$queryString = http_build_query($parameters);
@@ -124,14 +137,14 @@ abstract class Server
* Redirect the client to the authorization URL.
*
* @param TemporaryCredentials|string $temporaryIdentifier
*
* @return void
*/
public function authorize($temporaryIdentifier)
{
$url = $this->getAuthorizationUrl($temporaryIdentifier);
header('Location: '.$url);
return;
header('Location: ' . $url);
}
/**
@@ -144,6 +157,8 @@ abstract class Server
* @param string $verifier
*
* @return TokenCredentials
*
* @throws CredentialsException
*/
public function getTokenCredentials(TemporaryCredentials $temporaryCredentials, $temporaryIdentifier, $verifier)
{
@@ -155,7 +170,7 @@ abstract class Server
}
$uri = $this->urlTokenCredentials();
$bodyParameters = array('oauth_verifier' => $verifier);
$bodyParameters = ['oauth_verifier' => $verifier];
$client = $this->createHttpClient();
@@ -166,11 +181,13 @@ abstract class Server
'headers' => $headers,
'form_params' => $bodyParameters,
]);
return $this->createTokenCredentials((string) $response->getBody());
} catch (BadResponseException $e) {
return $this->handleTokenCredentialsBadResponse($e);
$this->handleTokenCredentialsBadResponse($e);
}
return $this->createTokenCredentials((string) $response->getBody());
throw new CredentialsException('Failed to get token credentials.');
}
/**
@@ -243,7 +260,7 @@ abstract class Server
*/
protected function fetchUserDetails(TokenCredentials $tokenCredentials, $force = true)
{
if (!$this->cachedUserDetailsResponse || $force) {
if ( ! $this->cachedUserDetailsResponse || $force) {
$url = $this->urlUserDetails();
$client = $this->createHttpClient();
@@ -338,10 +355,10 @@ abstract class Server
*
* @return array
*/
public function getHeaders(CredentialsInterface $credentials, $method, $url, array $bodyParameters = array())
public function getHeaders(CredentialsInterface $credentials, $method, $url, array $bodyParameters = [])
{
$header = $this->protocolHeader(strtoupper($method), $url, $credentials, $bodyParameters);
$authorizationHeader = array('Authorization' => $header);
$authorizationHeader = ['Authorization' => $header];
$headers = $this->buildHttpClientHeaders($authorizationHeader);
return $headers;
@@ -354,8 +371,8 @@ abstract class Server
*/
protected function getHttpClientDefaultHeaders()
{
$defaultHeaders = array();
if (!empty($this->userAgent)) {
$defaultHeaders = [];
if ( ! empty($this->userAgent)) {
$defaultHeaders['User-Agent'] = $this->userAgent;
}
@@ -365,9 +382,11 @@ abstract class Server
/**
* Build Guzzle HTTP client headers.
*
* @param array $headers
*
* @return array
*/
protected function buildHttpClientHeaders($headers = array())
protected function buildHttpClientHeaders($headers = [])
{
$defaultHeaders = $this->getHttpClientDefaultHeaders();
@@ -383,15 +402,22 @@ abstract class Server
*/
protected function createClientCredentials(array $clientCredentials)
{
$keys = array('identifier', 'secret');
$keys = ['identifier', 'secret'];
foreach ($keys as $key) {
if (!isset($clientCredentials[$key])) {
if ( ! isset($clientCredentials[$key])) {
throw new \InvalidArgumentException("Missing client credentials key [$key] from options.");
}
}
$_clientCredentials = new ClientCredentials();
if (isset($clientCredentials['rsa_private_key']) && isset($clientCredentials['rsa_public_key'])) {
$_clientCredentials = new RsaClientCredentials();
$_clientCredentials->setRsaPrivateKey($clientCredentials['rsa_private_key']);
$_clientCredentials->setRsaPublicKey($clientCredentials['rsa_public_key']);
} else {
$_clientCredentials = new ClientCredentials();
}
$_clientCredentials->setIdentifier($clientCredentials['identifier']);
$_clientCredentials->setSecret($clientCredentials['secret']);
@@ -407,6 +433,8 @@ abstract class Server
*
* @param BadResponseException $e
*
* @return void
*
* @throws CredentialsException
*/
protected function handleTemporaryCredentialsBadResponse(BadResponseException $e)
@@ -431,11 +459,11 @@ abstract class Server
{
parse_str($body, $data);
if (!$data || !is_array($data)) {
if ( ! $data || ! is_array($data)) {
throw new CredentialsException('Unable to parse temporary credentials response.');
}
if (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] != 'true') {
if ( ! isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] != 'true') {
throw new CredentialsException('Error in retrieving temporary credentials.');
}
@@ -451,6 +479,8 @@ abstract class Server
*
* @param BadResponseException $e
*
* @return void
*
* @throws CredentialsException
*/
protected function handleTokenCredentialsBadResponse(BadResponseException $e)
@@ -475,7 +505,7 @@ abstract class Server
{
parse_str($body, $data);
if (!$data || !is_array($data)) {
if ( ! $data || ! is_array($data)) {
throw new CredentialsException('Unable to parse token credentials response.');
}
@@ -502,13 +532,13 @@ abstract class Server
{
$dateTime = new \DateTime();
return array(
return [
'oauth_consumer_key' => $this->clientCredentials->getIdentifier(),
'oauth_nonce' => $this->nonce(),
'oauth_signature_method' => $this->signature->method(),
'oauth_timestamp' => $dateTime->format('U'),
'oauth_version' => '1.0',
);
];
}
/**
@@ -519,7 +549,7 @@ abstract class Server
*/
protected function additionalProtocolParameters()
{
return array();
return [];
}
/**
@@ -532,9 +562,9 @@ abstract class Server
*/
protected function temporaryCredentialsProtocolHeader($uri)
{
$parameters = array_merge($this->baseProtocolParameters(), array(
$parameters = array_merge($this->baseProtocolParameters(), [
'oauth_callback' => $this->clientCredentials->getCallbackUri(),
));
]);
$parameters['oauth_signature'] = $this->signature->sign($uri, $parameters, 'POST');
@@ -553,14 +583,14 @@ abstract class Server
*
* @return string
*/
protected function protocolHeader($method, $uri, CredentialsInterface $credentials, array $bodyParameters = array())
protected function protocolHeader($method, $uri, CredentialsInterface $credentials, array $bodyParameters = [])
{
$parameters = array_merge(
$this->baseProtocolParameters(),
$this->additionalProtocolParameters(),
array(
[
'oauth_token' => $credentials->getIdentifier(),
)
]
);
$this->signature->setCredentials($credentials);
@@ -585,10 +615,10 @@ abstract class Server
protected function normalizeProtocolParameters(array $parameters)
{
array_walk($parameters, function (&$value, $key) {
$value = rawurlencode($key).'="'.rawurlencode($value).'"';
$value = rawurlencode($key) . '="' . rawurlencode($value) . '"';
});
return 'OAuth '.implode(', ', $parameters);
return 'OAuth ' . implode(', ', $parameters);
}
/**
@@ -618,7 +648,7 @@ abstract class Server
*/
protected function buildUrl($host, $queryString)
{
return $host.(strpos($host, '?') !== false ? '&' : '?').$queryString;
return $host . (strpos($host, '?') !== false ? '&' : '?') . $queryString;
}
/**
@@ -678,7 +708,7 @@ abstract class Server
* @param mixed $data
* @param TokenCredentials $tokenCredentials
*
* @return string
* @return string|null
*/
abstract public function userEmail($data, TokenCredentials $tokenCredentials);
@@ -689,7 +719,7 @@ abstract class Server
* @param mixed $data
* @param TokenCredentials $tokenCredentials
*
* @return string
* @return string|null
*/
abstract public function userScreenName($data, TokenCredentials $tokenCredentials);
}

View File

@@ -3,6 +3,7 @@
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Signature\SignatureInterface;
class Trello extends Server
{
@@ -42,7 +43,7 @@ class Trello extends Server
protected $applicationScope;
/**
* {@inheritDoc}
* @inheritDoc
*/
public function __construct($clientCredentials, SignatureInterface $signature = null)
{
@@ -140,7 +141,7 @@ class Trello extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
@@ -148,16 +149,16 @@ class Trello extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlAuthorization()
{
return 'https://trello.com/1/OAuthAuthorizeToken?'.
return 'https://trello.com/1/OAuthAuthorizeToken?' .
$this->buildAuthorizationQueryParameters();
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTokenCredentials()
{
@@ -165,15 +166,15 @@ class Trello extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlUserDetails()
{
return 'https://trello.com/1/members/me?key='.$this->applicationKey.'&token='.$this->accessToken;
return 'https://trello.com/1/members/me?key=' . $this->applicationKey . '&token=' . $this->accessToken;
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
@@ -181,7 +182,6 @@ class Trello extends Server
$user->nickname = $data['username'];
$user->name = $data['fullName'];
$user->imageUrl = null;
$user->extra = (array) $data;
@@ -189,7 +189,7 @@ class Trello extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
@@ -197,15 +197,15 @@ class Trello extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return;
return null;
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
@@ -219,12 +219,12 @@ class Trello extends Server
*/
private function buildAuthorizationQueryParameters()
{
$params = array(
$params = [
'response_type' => 'fragment',
'scope' => $this->getApplicationScope(),
'expiration' => $this->getApplicationExpiration(),
'name' => $this->getApplicationName(),
);
];
return http_build_query($params);
}
@@ -233,15 +233,17 @@ class Trello extends Server
* Parse configuration array to set attributes.
*
* @param array $configuration
*
* @return void
*/
private function parseConfiguration(array $configuration = array())
private function parseConfiguration(array $configuration = [])
{
$configToPropertyMap = array(
$configToPropertyMap = [
'identifier' => 'applicationKey',
'expiration' => 'applicationExpiration',
'name' => 'applicationName',
'scope' => 'applicationScope',
);
];
foreach ($configToPropertyMap as $config => $property) {
if (isset($configuration[$config])) {

View File

@@ -3,11 +3,13 @@
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
use LogicException;
use RuntimeException;
class Tumblr extends Server
{
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
@@ -15,7 +17,7 @@ class Tumblr extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlAuthorization()
{
@@ -23,7 +25,7 @@ class Tumblr extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTokenCredentials()
{
@@ -31,7 +33,7 @@ class Tumblr extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlUserDetails()
{
@@ -39,13 +41,13 @@ class Tumblr extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
// If the API has broke, return nothing
if (!isset($data['response']['user']) || !is_array($data['response']['user'])) {
return;
if ( ! isset($data['response']['user']) || ! is_array($data['response']['user'])) {
throw new LogicException('Not possible to get user info');
}
$data = $data['response']['user'];
@@ -55,19 +57,19 @@ class Tumblr extends Server
$user->nickname = $data['name'];
// Save all extra data
$used = array('name');
$used = ['name'];
$user->extra = array_diff_key($data, array_flip($used));
return $user;
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
if (!isset($data['response']['user']) || !is_array($data['response']['user'])) {
return;
if ( ! isset($data['response']['user']) || ! is_array($data['response']['user'])) {
throw new LogicException('Not possible to get user UUID');
}
$data = $data['response']['user'];
@@ -76,20 +78,20 @@ class Tumblr extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return;
return null;
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
if (!isset($data['response']['user']) || !is_array($data['response']['user'])) {
return;
if ( ! isset($data['response']['user']) || ! is_array($data['response']['user'])) {
throw new LogicException('Not possible to get user screen name');
}
$data = $data['response']['user'];

View File

@@ -0,0 +1,182 @@
<?php
namespace League\OAuth1\Client\Server;
use League\OAuth1\Client\Credentials\TokenCredentials;
class Twitter extends Server
{
/**
* Application scope.
*
* @var ?string
*/
protected $applicationScope = null;
/**
* @inheritDoc
*/
public function __construct($clientCredentials, SignatureInterface $signature = null)
{
parent::__construct($clientCredentials, $signature);
if (is_array($clientCredentials)) {
$this->parseConfiguration($clientCredentials);
}
}
/**
* Set the application scope.
*
* @param ?string $applicationScope
*
* @return Twitter
*/
public function setApplicationScope($applicationScope)
{
$this->applicationScope = $applicationScope;
return $this;
}
/**
* Get application scope.
*
* @return ?string
*/
public function getApplicationScope()
{
return $this->applicationScope;
}
/**
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
$url = 'https://api.twitter.com/oauth/request_token';
$queryParams = $this->temporaryCredentialsQueryParameters();
return empty($queryParams) ? $url : $url . '?' . $queryParams;
}
/**
* @inheritDoc
*/
public function urlAuthorization()
{
return 'https://api.twitter.com/oauth/authenticate';
}
/**
* @inheritDoc
*/
public function urlTokenCredentials()
{
return 'https://api.twitter.com/oauth/access_token';
}
/**
* @inheritDoc
*/
public function urlUserDetails()
{
return 'https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true';
}
/**
* @inheritDoc
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
$user = new User();
$user->uid = $data['id_str'];
$user->nickname = $data['screen_name'];
$user->name = $data['name'];
$user->location = $data['location'];
$user->description = $data['description'];
$user->imageUrl = $data['profile_image_url'];
if (isset($data['email'])) {
$user->email = $data['email'];
}
$used = ['id', 'screen_name', 'name', 'location', 'description', 'profile_image_url', 'email'];
foreach ($data as $key => $value) {
if (strpos($key, 'url') !== false) {
if ( ! in_array($key, $used)) {
$used[] = $key;
}
$user->urls[$key] = $value;
}
}
// Save all extra data
$user->extra = array_diff_key($data, array_flip($used));
return $user;
}
/**
* @inheritDoc
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
return $data['id'];
}
/**
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
return null;
}
/**
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
return $data['name'];
}
/**
* Query parameters for a Twitter OAuth request to get temporary credentials.
*
* @return string
*/
protected function temporaryCredentialsQueryParameters()
{
$queryParams = [];
if ($scope = $this->getApplicationScope()) {
$queryParams['x_auth_access_type'] = $scope;
}
return http_build_query($queryParams);
}
/**
* Parse configuration array to set attributes.
*
* @param array $configuration
*
* @return void
*/
private function parseConfiguration(array $configuration = [])
{
$configToPropertyMap = [
'scope' => 'applicationScope',
];
foreach ($configToPropertyMap as $config => $property) {
if (isset($configuration[$config])) {
$this->$property = $configuration[$config];
}
}
}
}

View File

@@ -2,6 +2,8 @@
namespace League\OAuth1\Client\Server;
use ArrayIterator;
class User implements \IteratorAggregate
{
/**
@@ -9,83 +11,85 @@ class User implements \IteratorAggregate
*
* @var mixed
*/
public $uid = null;
public $uid;
/**
* The user's nickname (screen name, username etc).
*
* @var mixed
*/
public $nickname = null;
public $nickname;
/**
* The user's name.
*
* @var mixed
*/
public $name = null;
public $name;
/**
* The user's first name.
*
* @var string
*/
public $firstName = null;
public $firstName;
/**
* The user's last name.
*
* @var string
*/
public $lastName = null;
public $lastName;
/**
* The user's email.
*
* @var string
*/
public $email = null;
public $email;
/**
* The user's location.
*
* @var string|array
*/
public $location = null;
public $location;
/**
* The user's description.
*
* @var string
*/
public $description = null;
public $description;
/**
* The user's image URL.
*
* @var string
*/
public $imageUrl = null;
public $imageUrl;
/**
* The users' URLs.
*
* @var string|array
*/
public $urls = array();
public $urls = [];
/**
* Any extra data.
*
* @var array
*/
public $extra = array();
public $extra = [];
/**
* Set a property on the user.
*
* @param string $key
* @param mixed $value
*
* @return void
*/
public function __set($key, $value)
{
@@ -94,6 +98,18 @@ class User implements \IteratorAggregate
}
}
/**
* Tells if a property is set.
*
* @param string $key
*
* @return bool
*/
public function __isset($key)
{
return isset($this->{$key});
}
/**
* Get a property from the user.
*
@@ -109,10 +125,11 @@ class User implements \IteratorAggregate
}
/**
* {@inheritDoc}
* @inheritDoc
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return new \ArrayIterator($this);
return new ArrayIterator(get_object_vars($this));
}
}

View File

@@ -16,7 +16,7 @@ class Uservoice extends Server
protected $base;
/**
* {@inheritDoc}
* @inheritDoc
*/
public function __construct($clientCredentials, SignatureInterface $signature = null)
{
@@ -28,39 +28,39 @@ class Uservoice extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
return $this->base.'/oauth/request_token';
return $this->base . '/oauth/request_token';
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlAuthorization()
{
return $this->base.'/oauth/authorize';
return $this->base . '/oauth/authorize';
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTokenCredentials()
{
return $this->base.'/oauth/access_token';
return $this->base . '/oauth/access_token';
}
/**
* {@inheritdoc}
* @inheritDoc
*/
public function urlUserDetails()
{
return $this->base.'/api/v1/users/current.json';
return $this->base . '/api/v1/users/current.json';
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
@@ -72,13 +72,11 @@ class Uservoice extends Server
$user->email = $data['user']['email'];
if ($data['user']['name']) {
$parts = explode(' ', $data['user']['name']);
$parts = explode(' ', $data['user']['name'], 2);
if (count($parts) > 0) {
$user->firstName = $parts[0];
}
$user->firstName = $parts[0];
if (count($parts) > 1) {
if (2 === count($parts)) {
$user->lastName = $parts[1];
}
}
@@ -89,7 +87,7 @@ class Uservoice extends Server
}
/**
* {@inheritdoc}
* @inheritDoc
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
@@ -97,7 +95,7 @@ class Uservoice extends Server
}
/**
* {@inheritdoc}
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
@@ -105,7 +103,7 @@ class Uservoice extends Server
}
/**
* {@inheritdoc}
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
@@ -117,9 +115,11 @@ class Uservoice extends Server
*
* @param array $configuration
*
* @return void
*
* @throws InvalidArgumentException
*/
private function parseConfigurationArray(array $configuration = array())
private function parseConfigurationArray(array $configuration = [])
{
if (isset($configuration['host'])) {
throw new InvalidArgumentException('Missing host');

View File

@@ -9,39 +9,39 @@ class Xing extends Server
const XING_API_ENDPOINT = 'https://api.xing.com';
/**
* {@inheritDoc}
*/
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
return self::XING_API_ENDPOINT . '/v1/request_token';
}
/**
* {@inheritDoc}
*/
* @inheritDoc
*/
public function urlAuthorization()
{
return self::XING_API_ENDPOINT . '/v1/authorize';
}
/**
* {@inheritDoc}
*/
* @inheritDoc
*/
public function urlTokenCredentials()
{
return self::XING_API_ENDPOINT . '/v1/access_token';
}
/**
* {@inheritDoc}
*/
* @inheritDoc
*/
public function urlUserDetails()
{
return self::XING_API_ENDPOINT . '/v1/users/me';
}
/**
* {@inheritDoc}
*/
* @inheritDoc
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
if (!isset($data['users'][0])) {
if ( ! isset($data['users'][0])) {
throw new \Exception('Not possible to get user info');
}
$data = $data['users'][0];
@@ -66,27 +66,30 @@ class Xing extends Server
return $user;
}
/**
* {@inheritDoc}
*/
* @inheritDoc
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
$data = $data['users'][0];
return $data['id'];
}
/**
* {@inheritDoc}
*/
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
$data = $data['users'][0];
return $data['active_email'];
}
/**
* {@inheritDoc}
*/
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{
$data = $data['users'][0];
return $data['display_name'];
}
}

View File

@@ -0,0 +1,115 @@
<?php
namespace League\OAuth1\Client\Signature;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\UriInterface;
trait EncodesUrl
{
/**
* Create a Guzzle url for the given URI.
*
* @param string $uri
*
* @return UriInterface
*/
protected function createUrl($uri)
{
return Psr7\Utils::uriFor($uri);
}
/**
* Generate a base string for a RSA-SHA1 signature
* based on the given a url, method, and any parameters.
*
* @param UriInterface $url
* @param string $method
* @param array $parameters
*
* @return string
*/
protected function baseString(UriInterface $url, $method = 'POST', array $parameters = [])
{
$baseString = rawurlencode($method) . '&';
$schemeHostPath = Uri::fromParts([
'scheme' => $url->getScheme(),
'host' => $url->getHost(),
'port' => $url->getPort(),
'path' => $url->getPath(),
]);
$baseString .= rawurlencode($schemeHostPath) . '&';
parse_str($url->getQuery(), $query);
$data = array_merge($query, $parameters);
// normalize data key/values
$data = $this->normalizeArray($data);
ksort($data);
$baseString .= $this->queryStringFromData($data);
return $baseString;
}
/**
* Return a copy of the given array with all keys and values rawurlencoded.
*
* @param array $array Array to normalize
*
* @return array Normalized array
*/
protected function normalizeArray(array $array = [])
{
$normalizedArray = [];
foreach ($array as $key => $value) {
$key = rawurlencode(rawurldecode($key));
if (is_array($value)) {
$normalizedArray[$key] = $this->normalizeArray($value);
} else {
$normalizedArray[$key] = rawurlencode(rawurldecode($value));
}
}
return $normalizedArray;
}
/**
* Creates an array of rawurlencoded strings out of each array key/value pair
* Handles multi-dimensional arrays recursively.
*
* @param array $data Array of parameters to convert.
* @param array|null $queryParams Array to extend. False by default.
* @param string $prevKey Optional Array key to append
*
* @return string rawurlencoded string version of data
*/
protected function queryStringFromData($data, $queryParams = null, $prevKey = '')
{
if ($initial = (null === $queryParams)) {
$queryParams = [];
}
foreach ($data as $key => $value) {
if ($prevKey) {
$key = $prevKey . '[' . $key . ']'; // Handle multi-dimensional array
}
if (is_array($value)) {
$queryParams = $this->queryStringFromData($value, $queryParams, $key);
} else {
$queryParams[] = rawurlencode($key . '=' . $value); // join with equals sign
}
}
if ($initial) {
return implode('%26', $queryParams); // join with ampersand
}
return $queryParams;
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace League\OAuth1\Client\Signature;
class HmacSha1Signature extends Signature implements SignatureInterface
{
use EncodesUrl;
/**
* @inheritDoc
*/
public function method()
{
return 'HMAC-SHA1';
}
/**
* @inheritDoc
*/
public function sign($uri, array $parameters = [], $method = 'POST')
{
$url = $this->createUrl($uri);
$baseString = $this->baseString($url, $method, $parameters);
return base64_encode($this->hash($baseString));
}
/**
* Hashes a string with the signature's key.
*
* @param string $string
*
* @return string
*/
protected function hash($string)
{
return hash_hmac('sha1', $string, $this->key(), true);
}
}

View File

@@ -5,7 +5,7 @@ namespace League\OAuth1\Client\Signature;
class PlainTextSignature extends Signature implements SignatureInterface
{
/**
* {@inheritDoc}
* @inheritDoc
*/
public function method()
{
@@ -13,9 +13,9 @@ class PlainTextSignature extends Signature implements SignatureInterface
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function sign($uri, array $parameters = array(), $method = 'POST')
public function sign($uri, array $parameters = [], $method = 'POST')
{
return $this->key();
}

View File

@@ -0,0 +1,35 @@
<?php
namespace League\OAuth1\Client\Signature;
use League\OAuth1\Client\Credentials\RsaClientCredentials;
class RsaSha1Signature extends Signature implements SignatureInterface
{
use EncodesUrl;
/**
* @inheritDoc
*/
public function method()
{
return 'RSA-SHA1';
}
/**
* @inheritDoc
*/
public function sign($uri, array $parameters = [], $method = 'POST')
{
$url = $this->createUrl($uri);
$baseString = $this->baseString($url, $method, $parameters);
/** @var RsaClientCredentials $clientCredentials */
$clientCredentials = $this->clientCredentials;
$privateKey = $clientCredentials->getRsaPrivateKey();
openssl_sign($baseString, $signature, $privateKey);
return base64_encode($signature);
}
}

View File

@@ -22,7 +22,7 @@ abstract class Signature implements SignatureInterface
protected $credentials;
/**
* {@inheritDoc}
* @inheritDoc
*/
public function __construct(ClientCredentialsInterface $clientCredentials)
{
@@ -30,7 +30,7 @@ abstract class Signature implements SignatureInterface
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function setCredentials(CredentialsInterface $credentials)
{
@@ -44,7 +44,7 @@ abstract class Signature implements SignatureInterface
*/
protected function key()
{
$key = rawurlencode($this->clientCredentials->getSecret()).'&';
$key = rawurlencode($this->clientCredentials->getSecret()) . '&';
if ($this->credentials !== null) {
$key .= rawurlencode($this->credentials->getSecret());

View File

@@ -21,6 +21,8 @@ interface SignatureInterface
* the API.
*
* @param CredentialsInterface $credentials
*
* @return void
*/
public function setCredentials(CredentialsInterface $credentials);
@@ -40,5 +42,5 @@ interface SignatureInterface
*
* @return string
*/
public function sign($uri, array $parameters = array(), $method = 'POST');
public function sign($uri, array $parameters = [], $method = 'POST');
}

View File

@@ -1,37 +1,18 @@
<?php namespace League\OAuth1\Client\Tests;
/**
* Part of the Sentry package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/licenses/BSD-3-Clause
*
* @package Sentry
* @version 2.0.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011 - 2013, Cartalyst LLC
* @link http://cartalyst.com
*/
<?php
namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Credentials\ClientCredentials;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use PHPUnit\Framework\TestCase;
class ClientCredentialsTest extends PHPUnit_Framework_TestCase
class ClientCredentialsTest extends TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
protected function tearDown(): void
{
m::close();
parent::tearDown();
}
public function testManipulating()
@@ -44,4 +25,4 @@ class ClientCredentialsTest extends PHPUnit_Framework_TestCase
$credentials->setSecret('foo');
$this->assertEquals('foo', $credentials->getSecret());
}
}
}

View File

@@ -1,38 +1,18 @@
<?php namespace League\OAuth1\Client\Tests;
<?php
/**
* Part of the Sentry package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/licenses/BSD-3-Clause
*
* @package Sentry
* @version 2.0.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011 - 2013, Cartalyst LLC
* @link http://cartalyst.com
*/
namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Signature\HmacSha1Signature;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use PHPUnit\Framework\TestCase;
class HmacSha1SignatureTest extends PHPUnit_Framework_TestCase
class HmacSha1SignatureTest extends TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
protected function tearDown(): void
{
m::close();
parent::tearDown();
}
public function testSigningRequest()
@@ -40,14 +20,24 @@ class HmacSha1SignatureTest extends PHPUnit_Framework_TestCase
$signature = new HmacSha1Signature($this->getMockClientCredentials());
$uri = 'http://www.example.com/?qux=corge';
$parameters = array('foo' => 'bar', 'baz' => null);
$parameters = ['foo' => 'bar', 'baz' => null];
$this->assertEquals('A3Y7C1SUHXR1EBYIUlT3d6QT1cQ=', $signature->sign($uri, $parameters));
}
public function testSigningRequestWhereThePortIsNotStandard()
{
$signature = new HmacSha1Signature($this->getMockClientCredentials());
$uri = 'http://www.example.com:8080/?qux=corge';
$parameters = ['foo' => 'bar', 'baz' => null];
$this->assertEquals('ECcWxyi5UOC1G0MxH0ygm6Pd6JE=', $signature->sign($uri, $parameters));
}
public function testQueryStringFromArray()
{
$array = array('a' => 'b');
$array = ['a' => 'b'];
$res = $this->invokeQueryStringFromData($array);
$this->assertSame(
@@ -58,7 +48,7 @@ class HmacSha1SignatureTest extends PHPUnit_Framework_TestCase
public function testQueryStringFromIndexedArray()
{
$array = array('a', 'b');
$array = ['a', 'b'];
$res = $this->invokeQueryStringFromData($array);
$this->assertSame(
@@ -69,20 +59,20 @@ class HmacSha1SignatureTest extends PHPUnit_Framework_TestCase
public function testQueryStringFromMultiDimensionalArray()
{
$array = array(
'a' => array(
'b' => array(
$array = [
'a' => [
'b' => [
'c' => 'd',
),
'e' => array(
],
'e' => [
'f' => 'g',
),
),
],
],
'h' => 'i',
'empty' => '',
'null' => null,
'false' => false,
);
];
// Convert to query string.
$res = $this->invokeQueryStringFromData($array);
@@ -105,20 +95,20 @@ class HmacSha1SignatureTest extends PHPUnit_Framework_TestCase
// And ensure it matches the orignal array (approximately).
$this->assertSame(
array(
'a' => array(
'b' => array(
[
'a' => [
'b' => [
'c' => 'd',
),
'e' => array(
],
'e' => [
'f' => 'g',
),
),
],
],
'h' => 'i',
'empty' => '',
'null' => '', // null value gets lost in string translation
'false' => '', // false value gets lost in string translation
),
],
$original_array
);
}
@@ -128,20 +118,20 @@ class HmacSha1SignatureTest extends PHPUnit_Framework_TestCase
$signature = new HmacSha1Signature($this->getMockClientCredentials());
$uri = 'http://www.example.com/';
$parameters = array(
'a' => array(
'b' => array(
$parameters = [
'a' => [
'b' => [
'c' => 'd',
),
'e' => array(
],
'e' => [
'f' => 'g',
),
),
],
],
'h' => 'i',
'empty' => '',
'null' => null,
'false' => false,
);
];
$this->assertEquals('ZUxiJKugeEplaZm9e4hshN0I70U=', $signature->sign($uri, $parameters));
}
@@ -152,13 +142,15 @@ class HmacSha1SignatureTest extends PHPUnit_Framework_TestCase
$refl = new \ReflectionObject($signature);
$method = $refl->getMethod('queryStringFromData');
$method->setAccessible(true);
return $method->invokeArgs($signature, array($args));
return $method->invokeArgs($signature, [$args]);
}
protected function getMockClientCredentials()
{
$clientCredentials = m::mock('League\OAuth1\Client\Credentials\ClientCredentialsInterface');
$clientCredentials->shouldReceive('getSecret')->andReturn('clientsecret');
return $clientCredentials;
}
}

View File

@@ -1,37 +1,18 @@
<?php namespace League\OAuth1\Client\Tests;
/**
* Part of the Sentry package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/licenses/BSD-3-Clause
*
* @package Sentry
* @version 2.0.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011 - 2013, Cartalyst LLC
* @link http://cartalyst.com
*/
<?php
namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Signature\PlainTextSignature;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use PHPUnit\Framework\TestCase;
class PlainTextSignatureTest extends PHPUnit_Framework_TestCase
class PlainTextSignatureTest extends TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
protected function tearDown(): void
{
m::close();
parent::tearDown();
}
public function testSigningRequest()
@@ -48,6 +29,7 @@ class PlainTextSignatureTest extends PHPUnit_Framework_TestCase
{
$clientCredentials = m::mock('League\OAuth1\Client\Credentials\ClientCredentialsInterface');
$clientCredentials->shouldReceive('getSecret')->andReturn('clientsecret');
return $clientCredentials;
}
@@ -55,6 +37,7 @@ class PlainTextSignatureTest extends PHPUnit_Framework_TestCase
{
$credentials = m::mock('League\OAuth1\Client\Credentials\CredentialsInterface');
$credentials->shouldReceive('getSecret')->andReturn('tokensecret');
return $credentials;
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Credentials\CredentialsException;
use League\OAuth1\Client\Credentials\RsaClientCredentials;
use OpenSSLAsymmetricKey;
use PHPUnit\Framework\TestCase;
class RsaClientCredentialsTest extends TestCase
{
public function testGetRsaPublicKey()
{
$credentials = new RsaClientCredentials();
$credentials->setRsaPublicKey(__DIR__ . '/test_rsa_publickey.pem');
/** @var resource|OpenSSLAsymmetricKey $key */
$key = $credentials->getRsaPublicKey();
$this->assertFalse(is_null($key));
$this->assertEquals($key, $credentials->getRsaPublicKey());
}
public function testGetRsaPublicKeyNotExists()
{
$this->expectException(CredentialsException::class);
$credentials = new RsaClientCredentials();
$credentials->setRsaPublicKey('fail');
$credentials->getRsaPublicKey();
}
public function testGetRsaPublicKeyInvalid()
{
$this->expectException(CredentialsException::class);
$credentials = new RsaClientCredentials();
$credentials->setRsaPublicKey(__DIR__ . '/test_rsa_invalidkey.pem');
$credentials->getRsaPublicKey();
}
public function testGetRsaPrivateKey()
{
$credentials = new RsaClientCredentials();
$credentials->setRsaPrivateKey(__DIR__ . '/test_rsa_privatekey.pem');
/** @var resource|OpenSSLAsymmetricKey $key */
$key = $credentials->getRsaPrivateKey();
$this->assertFalse(is_null($key));
$this->assertEquals($key, $credentials->getRsaPrivateKey());
}
public function testGetRsaPrivateKeyNotExists()
{
$this->expectException(CredentialsException::class);
$credentials = new RsaClientCredentials();
$credentials->setRsaPrivateKey('fail');
$credentials->getRsaPrivateKey();
}
public function testGetRsaPrivateKeyInvalid()
{
$this->expectException(CredentialsException::class);
$credentials = new RsaClientCredentials();
$credentials->setRsaPrivateKey(__DIR__ . '/test_rsa_invalidkey.pem');
$credentials->getRsaPrivateKey();
}
}

View File

@@ -0,0 +1,148 @@
<?php
namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Credentials\ClientCredentialsInterface;
use League\OAuth1\Client\Credentials\RsaClientCredentials;
use League\OAuth1\Client\Signature\RsaSha1Signature;
use Mockery;
use PHPUnit\Framework\TestCase;
class RsaSha1SignatureTest extends TestCase
{
public function testMethod()
{
$signature = new RsaSha1Signature($this->getClientCredentials());
$this->assertEquals('RSA-SHA1', $signature->method());
}
public function testSigningRequest()
{
$signature = new RsaSha1Signature($this->getClientCredentials());
$uri = 'http://www.example.com/?qux=corge';
$parameters = ['foo' => 'bar', 'baz' => null];
$this->assertEquals('h8vpV4CYnLwss+rWicKE4sY6AiW2+DT6Fe7qB8jA7LSLhX5jvLEeX1D8E2ynSePSksAY48j+OSLu9vo5juS2duwNK8UA2Rtnnvuj6UFxpx70dpjHAsQg6EbycGptL/SChDkxfpG8LhuwX1FlFa+H0jLYXI5Dy8j90g51GRJbj48=', $signature->sign($uri, $parameters));
}
public function testQueryStringFromArray()
{
$array = ['a' => 'b'];
$res = $this->invokeQueryStringFromData($array);
$this->assertSame(
'a%3Db',
$res
);
}
public function testQueryStringFromIndexedArray()
{
$array = ['a', 'b'];
$res = $this->invokeQueryStringFromData($array);
$this->assertSame(
'0%3Da%261%3Db',
$res
);
}
public function testQueryStringFromMultiDimensionalArray()
{
$array = [
'a' => [
'b' => [
'c' => 'd',
],
'e' => [
'f' => 'g',
],
],
'h' => 'i',
'empty' => '',
'null' => null,
'false' => false,
];
// Convert to query string.
$res = $this->invokeQueryStringFromData($array);
$this->assertSame(
'a%5Bb%5D%5Bc%5D%3Dd%26a%5Be%5D%5Bf%5D%3Dg%26h%3Di%26empty%3D%26null%3D%26false%3D',
$res
);
// Reverse engineer the string.
$res = urldecode($res);
$this->assertSame(
'a[b][c]=d&a[e][f]=g&h=i&empty=&null=&false=',
$res
);
// Finally, parse the string back to an array.
parse_str($res, $original_array);
// And ensure it matches the orignal array (approximately).
$this->assertSame(
[
'a' => [
'b' => [
'c' => 'd',
],
'e' => [
'f' => 'g',
],
],
'h' => 'i',
'empty' => '',
'null' => '', // null value gets lost in string translation
'false' => '', // false value gets lost in string translation
],
$original_array
);
}
public function testSigningRequestWithMultiDimensionalParams()
{
$signature = new RsaSha1Signature($this->getClientCredentials());
$uri = 'http://www.example.com/';
$parameters = [
'a' => [
'b' => [
'c' => 'd',
],
'e' => [
'f' => 'g',
],
],
'h' => 'i',
'empty' => '',
'null' => null,
'false' => false,
];
$this->assertEquals('X9EkmOEbA5CoF2Hicf3ciAumpp1zkKxnVZkh/mEwWyF2DDcrfou9XF11WvbBu3G4loJGeX4GY1FsIrQpsjEILbn0e7Alyii/x8VA9mBwdqMhQVl49jF0pdowocc03M04cAbAOMNObT7tMmDs+YTFgRxEGCiUkq9AizP1cW3+eBo=', $signature->sign($uri, $parameters));
}
protected function invokeQueryStringFromData(array $args)
{
$signature = new RsaSha1Signature(Mockery::mock(ClientCredentialsInterface::class));
$refl = new \ReflectionObject($signature);
$method = $refl->getMethod('queryStringFromData');
$method->setAccessible(true);
return $method->invokeArgs($signature, [$args]);
}
protected function getClientCredentials()
{
$credentials = new RsaClientCredentials();
$credentials->setRsaPublicKey(__DIR__ . '/test_rsa_publickey.pem');
$credentials->setRsaPrivateKey(__DIR__ . '/test_rsa_privatekey.pem');
return $credentials;
}
}

View File

@@ -1,47 +1,32 @@
<?php namespace League\OAuth1\Client\Tests;
/**
* Part of the Sentry package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file. It is also available at
* the following URL: http://www.opensource.org/licenses/BSD-3-Clause
*
* @package Sentry
* @version 2.0.0
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011 - 2013, Cartalyst LLC
* @link http://cartalyst.com
*/
<?php
namespace League\OAuth1\Client\Tests;
use InvalidArgumentException;
use League\OAuth1\Client\Credentials\ClientCredentials;
use League\OAuth1\Client\Credentials\RsaClientCredentials;
use League\OAuth1\Client\Signature\RsaSha1Signature;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
class ServerTest extends PHPUnit_Framework_TestCase
class ServerTest extends TestCase
{
/**
* Setup resources and dependencies.
*
* @return void
*/
public static function setUpBeforeClass()
public static function setUpBeforeClass(): void
{
require_once __DIR__.'/stubs/ServerStub.php';
parent::setUpBeforeClass();
require_once __DIR__ . '/stubs/ServerStub.php';
}
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
protected function tearDown(): void
{
m::close();
parent::tearDown();
}
public function testCreatingWithArray()
@@ -55,6 +40,24 @@ class ServerTest extends PHPUnit_Framework_TestCase
$this->assertEquals('http://app.dev/', $credentials->getCallbackUri());
}
public function testCreatingWithArrayRsa()
{
$config = [
'identifier' => 'app_key',
'secret' => 'secret',
'callback_uri' => 'https://example.com/callback',
'rsa_public_key' => __DIR__ . '/test_rsa_publickey.pem',
'rsa_private_key' => __DIR__ . '/test_rsa_privatekey.pem',
];
$server = new ServerStub($config);
$credentials = $server->getClientCredentials();
$this->assertInstanceOf(RsaClientCredentials::class, $credentials);
$signature = $server->getSignature();
$this->assertInstanceOf(RsaSha1Signature::class, $signature);
}
public function testCreatingWithObject()
{
$credentials = new ClientCredentials;
@@ -67,22 +70,21 @@ class ServerTest extends PHPUnit_Framework_TestCase
$this->assertEquals($credentials, $server->getClientCredentials());
}
/**
* @expectedException InvalidArgumentException
**/
public function testCreatingWithInvalidInput()
{
$server = new ServerStub(uniqid());
$this->expectException(InvalidArgumentException::class);
new ServerStub(uniqid());
}
public function testGettingTemporaryCredentials()
{
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient]', array($this->getMockClientCredentials()));
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient]', [$this->getMockClientCredentials()]);
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('http://www.example.com/temporary', m::on(function($options) use ($me) {
$client->shouldReceive('post')->with('http://www.example.com/temporary', m::on(function ($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
@@ -90,14 +92,17 @@ class ServerTest extends PHPUnit_Framework_TestCase
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_callback="'.preg_quote('http%3A%2F%2Fapp.dev%2F', '/').'", oauth_signature=".*?"/';
$pattern
= '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_callback="'
. preg_quote('http%3A%2F%2Fapp.dev%2F', '/') . '", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=temporarycredentialsidentifier&oauth_token_secret=temporarycredentialssecret&oauth_callback_confirmed=true');
$response->shouldReceive('getBody')
->andReturn('oauth_token=temporarycredentialsidentifier&oauth_token_secret=temporarycredentialssecret&oauth_callback_confirmed=true');
$credentials = $server->getTemporaryCredentials();
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TemporaryCredentials', $credentials);
@@ -118,9 +123,16 @@ class ServerTest extends PHPUnit_Framework_TestCase
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
/**
* @expectedException InvalidArgumentException
*/
public function testGettingAuthorizationUrlWithOptions()
{
$server = new ServerStub($this->getMockClientCredentials());
$expected = 'http://www.example.com/authorize?oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo', ['oauth_token' => 'bar']));
$expected = 'http://www.example.com/authorize?test=bar&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo', ['test' => 'bar']));
}
public function testGettingTokenCredentialsFailsWithManInTheMiddle()
{
$server = new ServerStub($this->getMockClientCredentials());
@@ -128,12 +140,14 @@ class ServerTest extends PHPUnit_Framework_TestCase
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->expectException(InvalidArgumentException::class);
$server->getTokenCredentials($credentials, 'bar', 'verifier');
}
public function testGettingTokenCredentials()
{
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient]', array($this->getMockClientCredentials()));
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient]', [$this->getMockClientCredentials()]);
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('temporarycredentialsidentifier');
@@ -142,7 +156,7 @@ class ServerTest extends PHPUnit_Framework_TestCase
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('http://www.example.com/token', m::on(function($options) use ($me) {
$client->shouldReceive('post')->with('http://www.example.com/token', m::on(function ($options) use ($me) {
$headers = $options['headers'];
$body = $options['form_params'];
@@ -152,16 +166,18 @@ class ServerTest extends PHPUnit_Framework_TestCase
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="temporarycredentialsidentifier", oauth_signature=".*?"/';
$pattern
= '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="temporarycredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
$me->assertSame($body, array('oauth_verifier' => 'myverifiercode'));
$me->assertSame($body, ['oauth_verifier' => 'myverifiercode']);
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$response->shouldReceive('getBody')
->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$credentials = $server->getTokenCredentials($temporaryCredentials, 'temporarycredentialsidentifier', 'myverifiercode');
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TokenCredentials', $credentials);
@@ -172,7 +188,7 @@ class ServerTest extends PHPUnit_Framework_TestCase
public function testGettingTokenCredentialsWithUserAgent()
{
$userAgent = 'FooBar';
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient]', array($this->getMockClientCredentials()));
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient]', [$this->getMockClientCredentials()]);
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('temporarycredentialsidentifier');
@@ -181,7 +197,7 @@ class ServerTest extends PHPUnit_Framework_TestCase
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('http://www.example.com/token', m::on(function($options) use ($me, $userAgent) {
$client->shouldReceive('post')->with('http://www.example.com/token', m::on(function ($options) use ($me, $userAgent) {
$headers = $options['headers'];
$body = $options['form_params'];
@@ -192,27 +208,32 @@ class ServerTest extends PHPUnit_Framework_TestCase
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="temporarycredentialsidentifier", oauth_signature=".*?"/';
$pattern
= '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="temporarycredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
$me->assertSame($body, array('oauth_verifier' => 'myverifiercode'));
$me->assertSame($body, ['oauth_verifier' => 'myverifiercode']);
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$response->shouldReceive('getBody')
->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$credentials = $server->setUserAgent($userAgent)->getTokenCredentials($temporaryCredentials, 'temporarycredentialsidentifier', 'myverifiercode');
$credentials = $server->setUserAgent($userAgent)
->getTokenCredentials($temporaryCredentials, 'temporarycredentialsidentifier', 'myverifiercode');
$this->assertInstanceOf('League\OAuth1\Client\Credentials\TokenCredentials', $credentials);
$this->assertEquals('tokencredentialsidentifier', $credentials->getIdentifier());
$this->assertEquals('tokencredentialssecret', $credentials->getSecret());
}
public function testGettingUserDetails()
{
$server = m::mock('League\OAuth1\Client\Tests\ServerStub[createHttpClient,protocolHeader]', array($this->getMockClientCredentials()));
$server = m::mock(
'League\OAuth1\Client\Tests\ServerStub[createHttpClient,protocolHeader]',
[$this->getMockClientCredentials()]
);
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TokenCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('tokencredentialsidentifier');
@@ -221,7 +242,7 @@ class ServerTest extends PHPUnit_Framework_TestCase
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('get')->with('http://www.example.com/user', m::on(function($options) use ($me) {
$client->shouldReceive('get')->with('http://www.example.com/user', m::on(function ($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
@@ -229,14 +250,20 @@ class ServerTest extends PHPUnit_Framework_TestCase
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="tokencredentialsidentifier", oauth_signature=".*?"/';
$pattern
= '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="tokencredentialsidentifier", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
$response->shouldReceive('getBody')->once()->andReturn(json_encode(array('foo' => 'bar', 'id' => 123, 'contact_email' => 'baz@qux.com', 'username' => 'fred')));
}))->once()->andReturn($response = m::mock(ResponseInterface::class));
$response->shouldReceive('getBody')->once()->andReturn(json_encode([
'foo' => 'bar',
'id' => 123,
'contact_email' => 'baz@qux.com',
'username' => 'fred',
]));
$user = $server->getUserDetails($temporaryCredentials);
$this->assertInstanceOf('League\OAuth1\Client\Server\User', $user);
@@ -257,7 +284,8 @@ class ServerTest extends PHPUnit_Framework_TestCase
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="mock_identifier", oauth_signature=".*?"/';
$pattern
= '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_token="mock_identifier", oauth_signature=".*?"/';
// With a GET request
$headers = $server->getHeaders($tokenCredentials, 'GET', 'http://example.com/');
@@ -267,7 +295,7 @@ class ServerTest extends PHPUnit_Framework_TestCase
$this->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
// With a POST request
$headers = $server->getHeaders($tokenCredentials, 'POST', 'http://example.com/', array('body' => 'params'));
$headers = $server->getHeaders($tokenCredentials, 'POST', 'http://example.com/', ['body' => 'params']);
$this->assertTrue(isset($headers['Authorization']));
$matches = preg_match($pattern, $headers['Authorization']);
@@ -276,10 +304,10 @@ class ServerTest extends PHPUnit_Framework_TestCase
protected function getMockClientCredentials()
{
return array(
return [
'identifier' => 'myidentifier',
'secret' => 'mysecret',
'callback_uri' => 'http://app.dev/',
);
];
}
}

View File

@@ -1,20 +1,21 @@
<?php namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Server\Trello;
use InvalidArgumentException;
use League\OAuth1\Client\Credentials\ClientCredentials;
use League\OAuth1\Client\Server\Trello;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use PHPUnit\Framework\TestCase;
class TrelloTest extends PHPUnit_Framework_TestCase
use Psr\Http\Message\ResponseInterface;
class TrelloTest extends TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
protected function tearDown(): void
{
m::close();
parent::tearDown();
}
public function testCreatingWithArray()
@@ -42,12 +43,12 @@ class TrelloTest extends PHPUnit_Framework_TestCase
public function testGettingTemporaryCredentials()
{
$server = m::mock('League\OAuth1\Client\Server\Trello[createHttpClient]', array($this->getMockClientCredentials()));
$server = m::mock('League\OAuth1\Client\Server\Trello[createHttpClient]', [$this->getMockClientCredentials()]);
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('https://trello.com/1/OAuthGetRequestToken', m::on(function($options) use ($me) {
$client->shouldReceive('post')->with('https://trello.com/1/OAuthGetRequestToken', m::on(function ($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
@@ -55,13 +56,13 @@ class TrelloTest extends PHPUnit_Framework_TestCase
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_callback="'.preg_quote('http%3A%2F%2Fapp.dev%2F', '/').'", oauth_signature=".*?"/';
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_callback="' . preg_quote('http%3A%2F%2Fapp.dev%2F', '/') . '", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
}))->once()->andReturn($response = m::mock(ResponseInterface::class));
$response->shouldReceive('getBody')->andReturn('oauth_token=temporarycredentialsidentifier&oauth_token_secret=temporarycredentialssecret&oauth_callback_confirmed=true');
$credentials = $server->getTemporaryCredentials();
@@ -90,7 +91,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$credentials['expiration'] = $expiration;
$server = new Trello($credentials);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration='.urlencode($expiration).'&oauth_token=foo';
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration=' . urlencode($expiration) . '&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
@@ -105,7 +106,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$server = new Trello($this->getMockClientCredentials());
$server->setApplicationExpiration($expiration);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration='.urlencode($expiration).'&oauth_token=foo';
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration=' . urlencode($expiration) . '&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
@@ -121,7 +122,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$credentials['name'] = $name;
$server = new Trello($credentials);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration=1day&name='.urlencode($name).'&oauth_token=foo';
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration=1day&name=' . urlencode($name) . '&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
@@ -136,7 +137,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$server = new Trello($this->getMockClientCredentials());
$server->setApplicationName($name);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration=1day&name='.urlencode($name).'&oauth_token=foo';
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=read&expiration=1day&name=' . urlencode($name) . '&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
@@ -152,7 +153,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$credentials['scope'] = $scope;
$server = new Trello($credentials);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope='.urlencode($scope).'&expiration=1day&oauth_token=foo';
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=' . urlencode($scope) . '&expiration=1day&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
@@ -167,7 +168,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$server = new Trello($this->getMockClientCredentials());
$server->setApplicationScope($scope);
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope='.urlencode($scope).'&expiration=1day&oauth_token=foo';
$expected = 'https://trello.com/1/OAuthAuthorizeToken?response_type=fragment&scope=' . urlencode($scope) . '&expiration=1day&oauth_token=foo';
$this->assertEquals($expected, $server->getAuthorizationUrl('foo'));
@@ -176,9 +177,6 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
/**
* @expectedException InvalidArgumentException
*/
public function testGettingTokenCredentialsFailsWithManInTheMiddle()
{
$server = new Trello($this->getMockClientCredentials());
@@ -186,12 +184,14 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->expectException(InvalidArgumentException::class);
$server->getTokenCredentials($credentials, 'bar', 'verifier');
}
public function testGettingTokenCredentials()
{
$server = m::mock('League\OAuth1\Client\Server\Trello[createHttpClient]', array($this->getMockClientCredentials()));
$server = m::mock('League\OAuth1\Client\Server\Trello[createHttpClient]', [$this->getMockClientCredentials()]);
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('temporarycredentialsidentifier');
@@ -200,7 +200,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('post')->with('https://trello.com/1/OAuthGetAccessToken', m::on(function($options) use ($me) {
$client->shouldReceive('post')->with('https://trello.com/1/OAuthGetAccessToken', m::on(function ($options) use ($me) {
$headers = $options['headers'];
$body = $options['form_params'];
@@ -214,10 +214,10 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
$me->assertSame($body, array('oauth_verifier' => 'myverifiercode'));
$me->assertSame($body, ['oauth_verifier' => 'myverifiercode']);
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
}))->once()->andReturn($response = m::mock(ResponseInterface::class));
$response->shouldReceive('getBody')->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$credentials = $server->getTokenCredentials($temporaryCredentials, 'temporarycredentialsidentifier', 'myverifiercode');
@@ -228,7 +228,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
public function testGettingUserDetails()
{
$server = m::mock('League\OAuth1\Client\Server\Trello[createHttpClient,protocolHeader]', array($this->getMockClientCredentials()));
$server = m::mock('League\OAuth1\Client\Server\Trello[createHttpClient,protocolHeader]', [$this->getMockClientCredentials()]);
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TokenCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('tokencredentialsidentifier');
@@ -237,7 +237,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
$me = $this;
$client->shouldReceive('get')->with('https://trello.com/1/members/me?key='.$this->getApplicationKey().'&token='.$this->getAccessToken(), m::on(function($options) use ($me) {
$client->shouldReceive('get')->with('https://trello.com/1/members/me?key=' . $this->getApplicationKey() . '&token=' . $this->getAccessToken(), m::on(function ($options) use ($me) {
$headers = $options['headers'];
$me->assertTrue(isset($headers['Authorization']));
@@ -251,7 +251,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
}))->once()->andReturn($response = m::mock(ResponseInterface::class));
$response->shouldReceive('getBody')->once()->andReturn($this->getUserPayload());
$user = $server
@@ -266,11 +266,11 @@ class TrelloTest extends PHPUnit_Framework_TestCase
protected function getMockClientCredentials()
{
return array(
return [
'identifier' => $this->getApplicationKey(),
'secret' => 'mysecret',
'callback_uri' => 'http://app.dev/',
);
];
}
protected function getAccessToken()
@@ -285,7 +285,7 @@ class TrelloTest extends PHPUnit_Framework_TestCase
protected function getApplicationExpiration($days = 0)
{
return is_numeric($days) && $days > 0 ? $days.'day'.($days == 1 ? '' : 's') : 'never';
return is_numeric($days) && $days > 0 ? $days . 'day' . ($days == 1 ? '' : 's') : 'never';
}
protected function getApplicationName()

View File

@@ -0,0 +1,38 @@
<?php
namespace League\OAuth1\Client\Tests;
use Generator;
use League\OAuth1\Client\Server\Twitter;
use PHPUnit\Framework\TestCase;
class TwitterServerTest extends TestCase
{
public function sampleTemporaryCredentialUrls(): Generator
{
yield 'No application scope' => [
null, 'https://api.twitter.com/oauth/request_token',
];
yield "Read" => [
'read', 'https://api.twitter.com/oauth/request_token?x_auth_access_type=read',
];
yield "Write" => [
'write', 'https://api.twitter.com/oauth/request_token?x_auth_access_type=write',
];
}
/** @dataProvider sampleTemporaryCredentialUrls */
public function testItProvidesNoApplicationScopeByDefault(?string $applicationScope, string $url): void
{
$twitter = new Twitter([
'identifier' => 'mykey',
'secret' => 'mysecret',
'callback_uri' => 'http://app.dev/',
'scope' => $applicationScope,
]);
self::assertEquals($url, $twitter->urlTemporaryCredentials());
}
}

View File

@@ -1,20 +1,21 @@
<?php namespace League\OAuth1\Client\Tests;
use League\OAuth1\Client\Server\Xing;
use InvalidArgumentException;
use League\OAuth1\Client\Credentials\ClientCredentials;
use League\OAuth1\Client\Server\Xing;
use Mockery as m;
use PHPUnit_Framework_TestCase;
use PHPUnit\Framework\TestCase;
class XingTest extends PHPUnit_Framework_TestCase
use Psr\Http\Message\ResponseInterface;
class XingTest extends TestCase
{
/**
* Close mockery.
*
* @return void
*/
public function tearDown()
protected function tearDown(): void
{
m::close();
parent::tearDown();
}
public function testCreatingWithArray()
@@ -42,7 +43,7 @@ class XingTest extends PHPUnit_Framework_TestCase
public function testGettingTemporaryCredentials()
{
$server = m::mock('League\OAuth1\Client\Server\Xing[createHttpClient]', array($this->getMockClientCredentials()));
$server = m::mock('League\OAuth1\Client\Server\Xing[createHttpClient]', [$this->getMockClientCredentials()]);
$server->shouldReceive('createHttpClient')->andReturn($client = m::mock('stdClass'));
@@ -54,13 +55,13 @@ class XingTest extends PHPUnit_Framework_TestCase
// OAuth protocol specifies a strict number of
// headers should be sent, in the correct order.
// We'll validate that here.
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_callback="'.preg_quote('http%3A%2F%2Fapp.dev%2F', '/').'", oauth_signature=".*?"/';
$pattern = '/OAuth oauth_consumer_key=".*?", oauth_nonce="[a-zA-Z0-9]+", oauth_signature_method="HMAC-SHA1", oauth_timestamp="\d{10}", oauth_version="1.0", oauth_callback="' . preg_quote('http%3A%2F%2Fapp.dev%2F', '/') . '", oauth_signature=".*?"/';
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
}))->once()->andReturn($response = m::mock(ResponseInterface::class));
$response->shouldReceive('getBody')->andReturn('oauth_token=temporarycredentialsidentifier&oauth_token_secret=temporarycredentialssecret&oauth_callback_confirmed=true');
$credentials = $server->getTemporaryCredentials();
@@ -82,9 +83,6 @@ class XingTest extends PHPUnit_Framework_TestCase
$this->assertEquals($expected, $server->getAuthorizationUrl($credentials));
}
/**
* @expectedException InvalidArgumentException
*/
public function testGettingTokenCredentialsFailsWithManInTheMiddle()
{
$server = new Xing($this->getMockClientCredentials());
@@ -92,12 +90,14 @@ class XingTest extends PHPUnit_Framework_TestCase
$credentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$credentials->shouldReceive('getIdentifier')->andReturn('foo');
$this->expectException(InvalidArgumentException::class);
$server->getTokenCredentials($credentials, 'bar', 'verifier');
}
public function testGettingTokenCredentials()
{
$server = m::mock('League\OAuth1\Client\Server\Xing[createHttpClient]', array($this->getMockClientCredentials()));
$server = m::mock('League\OAuth1\Client\Server\Xing[createHttpClient]', [$this->getMockClientCredentials()]);
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TemporaryCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('temporarycredentialsidentifier');
@@ -120,10 +120,10 @@ class XingTest extends PHPUnit_Framework_TestCase
$matches = preg_match($pattern, $headers['Authorization']);
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
$me->assertSame($body, array('oauth_verifier' => 'myverifiercode'));
$me->assertSame($body, ['oauth_verifier' => 'myverifiercode']);
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
}))->once()->andReturn($response = m::mock(ResponseInterface::class));
$response->shouldReceive('getBody')->andReturn('oauth_token=tokencredentialsidentifier&oauth_token_secret=tokencredentialssecret');
$credentials = $server->getTokenCredentials($temporaryCredentials, 'temporarycredentialsidentifier', 'myverifiercode');
@@ -134,7 +134,7 @@ class XingTest extends PHPUnit_Framework_TestCase
public function testGettingUserDetails()
{
$server = m::mock('League\OAuth1\Client\Server\Xing[createHttpClient,protocolHeader]', array($this->getMockClientCredentials()));
$server = m::mock('League\OAuth1\Client\Server\Xing[createHttpClient,protocolHeader]', [$this->getMockClientCredentials()]);
$temporaryCredentials = m::mock('League\OAuth1\Client\Credentials\TokenCredentials');
$temporaryCredentials->shouldReceive('getIdentifier')->andReturn('tokencredentialsidentifier');
@@ -157,7 +157,7 @@ class XingTest extends PHPUnit_Framework_TestCase
$me->assertEquals(1, $matches, 'Asserting that the authorization header contains the correct expression.');
return true;
}))->once()->andReturn($response = m::mock('stdClass'));
}))->once()->andReturn($response = m::mock(ResponseInterface::class));
$response->shouldReceive('getBody')->once()->andReturn($this->getUserPayload());
$user = $server->getUserDetails($temporaryCredentials);
@@ -170,11 +170,11 @@ class XingTest extends PHPUnit_Framework_TestCase
protected function getMockClientCredentials()
{
return array(
return [
'identifier' => $this->getApplicationKey(),
'secret' => 'mysecret',
'callback_uri' => 'http://app.dev/',
);
];
}
protected function getApplicationKey()
@@ -184,7 +184,7 @@ class XingTest extends PHPUnit_Framework_TestCase
protected function getApplicationExpiration($days = 0)
{
return is_numeric($days) && $days > 0 ? $days.'day'.($days == 1 ? '' : 's') : 'never';
return is_numeric($days) && $days > 0 ? $days . 'day' . ($days == 1 ? '' : 's') : 'never';
}
protected function getApplicationName()

View File

@@ -9,7 +9,7 @@ use League\OAuth1\Client\Server\User;
class ServerStub extends Server
{
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTemporaryCredentials()
{
@@ -17,7 +17,7 @@ class ServerStub extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlAuthorization()
{
@@ -25,7 +25,7 @@ class ServerStub extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlTokenCredentials()
{
@@ -33,7 +33,7 @@ class ServerStub extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function urlUserDetails()
{
@@ -41,17 +41,18 @@ class ServerStub extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userDetails($data, TokenCredentials $tokenCredentials)
{
$user = new User;
$user->firstName = $data['foo'];
return $user;
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userUid($data, TokenCredentials $tokenCredentials)
{
@@ -59,7 +60,7 @@ class ServerStub extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userEmail($data, TokenCredentials $tokenCredentials)
{
@@ -67,7 +68,7 @@ class ServerStub extends Server
}
/**
* {@inheritDoc}
* @inheritDoc
*/
public function userScreenName($data, TokenCredentials $tokenCredentials)
{

View File

@@ -0,0 +1 @@
not a valid RSA key

View File

@@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDJScPCpHHPakw9v4nhxi+cBumCml3WpMNDaE3Cxnkf6HALzoi8
fQPx3XRfKSoLG6b7uTG+vDoLCL49ZCyYwrnggsFF08bJMqIhUHlZrkiyT5UhdTIh
XEEFfb6XmieHNtra+ur8E3PVal4PEdOCEmJehBMJkiCsxNOJ/kCeYSMdbQIDAQAB
AoGAMo7JkcEWKP/NCJFsg33xBWKjEj/NpBUcSnkPVwXc9IvAYObOZ3GLJRv3l9NS
ERov9fgNK5hBh/X5OphHr1LxtqU5gAFYx5Qgt/WG3ZH9KScXkaPS3Oq2qK9krbA2
BXYKP4NEqhjJTecy7M8bju5+lsjteyqVSsVLHdLhUfPRbE0CQQDyYP6iChqZm1AK
A8x8PKvJsd4zSdxWXUYSmD7mAtek5VeWblbcXYYdeYPN6hNmqzaLelmrZI51x1Uf
hf1ryIfrAkEA1JmdSsNuxi9MOY3HqErWYsqZ//mVOxVyCAwf7OWQ0rTHEQBhQwpS
9nk0YFHI9t6nVUwXrZ7/7UJPTu8OjPKyBwJAYw2OomwcqM/XKvCYfeFRl1DwbOdv
e4AM5gaAFgHtXP85B0o6hz5VU/BYFCvoF9o6pU+wG6IxsiJvQD3C7mx6VwJAbXYW
PVs4WsQZe/ya0vSNQ1pLRjdr9XrKNoh/m4prMYGwiPloGotjQdIP/JO/ZBQplcpS
2qrl3HPqv5poJHwE2wJBAM37BVINHR0zcSHfFLmSYrqmLx2oC3UAB3exmpYSUgOz
wJqPfmPWuuXuu6h0Z2DazUan+2EiecX6C4ywkm+qk1I=
-----END RSA PRIVATE KEY-----

View File

@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDEDCCAnmgAwIBAgIJAMhMVuHMz+EgMA0GCSqGSIb3DQEBBQUAMGQxCzAJBgNV
BAYTAlVTMQswCQYDVQQIEwJUWDEPMA0GA1UEBxMGQXVzdGluMSEwHwYDVQQKExhJ
bnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxFDASBgNVBAMTC2V4YW1wbGUuY29tMB4X
DTE2MTEwMjIxMDUzNVoXDTIxMTEwMTIxMDUzNVowZDELMAkGA1UEBhMCVVMxCzAJ
BgNVBAgTAlRYMQ8wDQYDVQQHEwZBdXN0aW4xITAfBgNVBAoTGEludGVybmV0IFdp
ZGdpdHMgUHR5IEx0ZDEUMBIGA1UEAxMLZXhhbXBsZS5jb20wgZ8wDQYJKoZIhvcN
AQEBBQADgY0AMIGJAoGBAMlJw8Kkcc9qTD2/ieHGL5wG6YKaXdakw0NoTcLGeR/o
cAvOiLx9A/HddF8pKgsbpvu5Mb68OgsIvj1kLJjCueCCwUXTxskyoiFQeVmuSLJP
lSF1MiFcQQV9vpeaJ4c22tr66vwTc9VqXg8R04ISYl6EEwmSIKzE04n+QJ5hIx1t
AgMBAAGjgckwgcYwHQYDVR0OBBYEFLYKQbsK2oqRO83NbNXC2R6MkNcRMIGWBgNV
HSMEgY4wgYuAFLYKQbsK2oqRO83NbNXC2R6MkNcRoWikZjBkMQswCQYDVQQGEwJV
UzELMAkGA1UECBMCVFgxDzANBgNVBAcTBkF1c3RpbjEhMB8GA1UEChMYSW50ZXJu
ZXQgV2lkZ2l0cyBQdHkgTHRkMRQwEgYDVQQDEwtleGFtcGxlLmNvbYIJAMhMVuHM
z+EgMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEASwEwGQnRCqcNrb6k
g6/xpeyHE9/ruTBIE4dtArQI0NosaERC3i4nRKbgfJfIuYEaYiga4dC51CQqKrbH
YZ0dgYMzzp21OMQyKdz3E7csMJv5xxe5D2svdPzbBGU5+N80FYLx17f3UqsYFaAC
X0/YTQsdlM5tHZOd1ZbQUrERqLs=
-----END CERTIFICATE-----