Skip to content
This repository was archived by the owner on Mar 23, 2024. It is now read-only.

Commit 54c5264

Browse files
committed
:octocat: examples cleanup
1 parent 3cafcf0 commit 54c5264

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+558
-1380
lines changed

composer.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,7 @@
5252
"autoload-dev": {
5353
"psr-4": {
5454
"chillerlan\\OAuthTest\\": "vendor/chillerlan/php-oauth-core/tests",
55-
"chillerlan\\OAuthTest\\Providers\\": "tests/",
56-
"chillerlan\\OAuthExamples\\": "examples/"
55+
"chillerlan\\OAuthTest\\Providers\\": "tests/"
5756
}
5857
},
5958
"scripts": {

examples/OAuthExampleSessionStorage.php

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,28 +8,40 @@
88
* @license MIT
99
*/
1010

11-
namespace chillerlan\OAuthExamples;
12-
1311
use chillerlan\OAuth\Core\AccessToken;
12+
use chillerlan\OAuth\OAuthOptions;
1413
use chillerlan\OAuth\Storage\{OAuthStorageException, SessionStorage};
1514
use chillerlan\Settings\SettingsContainerInterface;
16-
17-
use function file_exists, file_get_contents, file_put_contents, sprintf;
15+
use Psr\Log\LoggerInterface;
16+
use Psr\Log\NullLogger;
1817

1918
class OAuthExampleSessionStorage extends SessionStorage{
2019

21-
protected string $storagepath;
20+
protected string|null $storagepath;
2221

2322
/**
2423
* OAuthExampleSessionStorage constructor.
2524
*
26-
* @param \chillerlan\Settings\SettingsContainerInterface|null $options
27-
* @param string|null $storagepath
25+
* @throws \chillerlan\OAuth\Storage\OAuthStorageException
2826
*/
29-
public function __construct(SettingsContainerInterface $options = null, string $storagepath = null){
30-
parent::__construct($options);
27+
public function __construct(
28+
OAuthOptions|SettingsContainerInterface $options = new OAuthOptions,
29+
LoggerInterface $logger = new NullLogger,
30+
string|null $storagepath = null,
31+
){
32+
parent::__construct($options, $logger);
33+
34+
if($storagepath !== null){
35+
$storagepath = trim($storagepath);
36+
37+
if(!is_dir($storagepath) || !is_writable($storagepath)){
38+
throw new OAuthStorageException('invalid storage path');
39+
}
40+
41+
$storagepath = realpath($storagepath);
42+
}
3143

32-
$this->storagepath = ($storagepath ?? __DIR__);
44+
$this->storagepath = $storagepath;
3345
}
3446

3547
/**
@@ -38,18 +50,19 @@ public function __construct(SettingsContainerInterface $options = null, string $
3850
public function storeAccessToken(AccessToken $token, string $service = null):static{
3951
parent::storeAccessToken($token, $service);
4052

41-
$tokenfile = sprintf('%s/%s.token.json', $this->storagepath, $this->getServiceName($service));
53+
if($this->storagepath !== null){
54+
$tokenfile = sprintf('%s/%s.token.json', $this->storagepath, $this->getServiceName($service));
4255

43-
if(file_put_contents($tokenfile, $token->toJSON()) === false){
44-
throw new OAuthStorageException('unable to access file storage');
56+
if(file_put_contents($tokenfile, $token->toJSON()) === false){
57+
throw new OAuthStorageException('unable to access file storage');
58+
}
4559
}
4660

4761
return $this;
4862
}
4963

5064
/**
5165
* @inheritDoc
52-
* @phan-suppress PhanTypeMismatchReturnSuperType
5366
*/
5467
public function getAccessToken(string $service = null):AccessToken{
5568
$service = $this->getServiceName($service);
@@ -58,10 +71,12 @@ public function getAccessToken(string $service = null):AccessToken{
5871
return (new AccessToken)->fromJSON($_SESSION[$this->tokenVar][$service]);
5972
}
6073

61-
$tokenfile = sprintf('%s/%s.token.json', $this->storagepath, $service);
74+
if($this->storagepath !== null){
75+
$tokenfile = sprintf('%s/%s.token.json', $this->storagepath, $service);
6276

63-
if(file_exists($tokenfile)){
64-
return (new AccessToken)->fromJSON(file_get_contents($tokenfile));
77+
if(file_exists($tokenfile)){
78+
return (new AccessToken)->fromJSON(file_get_contents($tokenfile));
79+
}
6580
}
6681

6782
throw new OAuthStorageException('token not found');

examples/OAuthProviderFactory.php

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
<?php
2+
/**
3+
* Class OAuthProviderFactory
4+
*
5+
* @created 03.03.2024
6+
* @author smiley <smiley@chillerlan.net>
7+
* @copyright 2024 smiley
8+
* @license MIT
9+
*/
10+
11+
require_once __DIR__.'/OAuthExampleSessionStorage.php';
12+
13+
use chillerlan\DotEnv\DotEnv;
14+
use chillerlan\OAuth\Core\OAuth1Interface;
15+
use chillerlan\OAuth\Core\OAuth2Interface;
16+
use chillerlan\OAuth\Core\OAuthInterface;
17+
use chillerlan\OAuth\OAuthOptions;
18+
use chillerlan\OAuth\Storage\MemoryStorage;
19+
use chillerlan\Settings\SettingsContainerInterface;
20+
use Monolog\Formatter\LineFormatter;
21+
use Monolog\Handler\NullHandler;
22+
use Monolog\Handler\StreamHandler;
23+
use Monolog\Logger;
24+
use Psr\Http\Client\ClientInterface;
25+
use Psr\Http\Message\RequestFactoryInterface;
26+
use Psr\Http\Message\StreamFactoryInterface;
27+
use Psr\Http\Message\UriFactoryInterface;
28+
use Psr\Log\LoggerInterface;
29+
30+
/**
31+
*
32+
*/
33+
class OAuthProviderFactory{
34+
35+
protected DotEnv $dotEnv;
36+
protected LoggerInterface $logger;
37+
protected OAuthOptions|SettingsContainerInterface $options;
38+
39+
public function __construct(
40+
protected ClientInterface $http,
41+
protected RequestFactoryInterface $requestFactory,
42+
protected StreamFactoryInterface $streamFactory,
43+
protected UriFactoryInterface $uriFactory,
44+
protected string $cfgDir = __DIR__.'/../config',
45+
string $envFile = '.env',
46+
string $logLevel = null,
47+
){
48+
ini_set('date.timezone', 'Europe/Amsterdam');
49+
50+
$this->dotEnv = (new DotEnv($this->cfgDir, $envFile, false))->load();
51+
$this->logger = $this->initLogger($logLevel);
52+
}
53+
54+
protected function initLogger(string|null $logLevel):LoggerInterface{
55+
$logger = new Logger('log', [new NullHandler]);
56+
57+
if($logLevel !== null){
58+
$formatter = new LineFormatter(null, 'Y-m-d H:i:s', true, true);
59+
$formatter->setJsonPrettyPrint(true);
60+
61+
$logHandler = (new StreamHandler('php://stdout', $logLevel))->setFormatter($formatter);
62+
63+
$logger->pushHandler($logHandler);
64+
}
65+
66+
return $logger;
67+
}
68+
69+
public function getProvider(string $providerFQN, string $envVar, bool $sessionStorage = true):OAuthInterface|OAuth1Interface|OAuth2Interface{
70+
$options = new OAuthOptions;
71+
72+
$options->key = ($this->getEnvVar($envVar.'_KEY') ?? '');
73+
$options->secret = ($this->getEnvVar($envVar.'_SECRET') ?? '');
74+
$options->callbackURL = ($this->getEnvVar($envVar.'_CALLBACK_URL') ?? '');
75+
$options->tokenAutoRefresh = true;
76+
$options->sessionStart = true;
77+
78+
$storage = new MemoryStorage;
79+
80+
if($sessionStorage === true){
81+
$storage = new OAuthExampleSessionStorage(options: $options, storagepath: $this->cfgDir);
82+
}
83+
84+
return new $providerFQN(
85+
$options,
86+
$this->http,
87+
$this->requestFactory,
88+
$this->streamFactory,
89+
$this->uriFactory,
90+
$storage,
91+
$this->logger,
92+
);
93+
}
94+
95+
public function getEnvVar(string $var):mixed{
96+
return $this->dotEnv->get($var);
97+
}
98+
99+
public function getLogger():LoggerInterface{
100+
return $this->logger;
101+
}
102+
103+
public function getRequestFactory():RequestFactoryInterface{
104+
return $this->requestFactory;
105+
}
106+
107+
public function getStreamFactory():StreamFactoryInterface{
108+
return $this->streamFactory;
109+
}
110+
111+
public function getUriFactory():UriFactoryInterface{
112+
return $this->uriFactory;
113+
}
114+
115+
}

examples/create-docblocks.php

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,7 @@
77
* @license MIT
88
*/
99

10-
namespace chillerlan\OAuthExamples;
11-
1210
use chillerlan\OAuth\Core\{ClientCredentials, OAuth1Interface, OAuth2Interface, OAuthInterface};
13-
use DirectoryIterator, IteratorIterator, ReflectionClass, Throwable;
14-
15-
use function file_get_contents, file_put_contents, hash, implode, realpath, str_replace, strpos, substr;
1611

1712
/**
1813
* @var \Psr\Http\Client\ClientInterface $http
@@ -28,8 +23,8 @@
2823
];
2924

3025
foreach(getProviders(__DIR__.'/../src') as $p){
31-
/** @var \chillerlan\OAuth\Core\OAuthInterface $provider */
32-
$provider = new $p['fqcn']($http, $options, $logger);
26+
/** @var \OAuthProviderFactory $factory */
27+
$provider = $factory->getProvider($p['fqcn'], '', false);
3328

3429
$oauth = match(true){
3530
$provider instanceof OAuth2Interface => '2',
@@ -44,6 +39,7 @@
4439
' | '.(($provider instanceof ClientCredentials) ? '' : '').
4540
' |' ;
4641

42+
printf("%s\n", $p['fqcn']);
4743
}
4844

4945
$file = __DIR__.'/../README.md';

examples/get-token/Amazon.php

Lines changed: 4 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -8,47 +8,15 @@
88
* @license MIT
99
*/
1010

11-
use chillerlan\HTTP\Utils\MessageUtil;
1211
use chillerlan\OAuth\Providers\Amazon;
1312

14-
$ENVVAR = 'AMAZON';
13+
$ENVVAR ??= 'AMAZON';
1514

1615
require_once __DIR__.'/../provider-example-common.php';
1716

18-
/**
19-
* @var \Psr\Http\Client\ClientInterface $http
20-
* @var \chillerlan\OAuth\Storage\OAuthStorageInterface $storage
21-
* @var \chillerlan\Settings\SettingsContainerInterface $options
22-
* @var \Psr\Log\LoggerInterface $logger
23-
* @var array $SCOPES
24-
*/
25-
26-
$amazon = new Amazon($http, $options, $logger);
27-
$amazon->setStorage($storage);
28-
29-
$servicename = $amazon->serviceName;
30-
31-
// step 2: redirect to the provider's login screen
32-
if(isset($_GET['login']) && $_GET['login'] === $servicename){
33-
header('Location: '.$amazon->getAuthURL(null, $SCOPES));
34-
}
35-
// step 3: receive the access token
36-
elseif(isset($_GET['code']) && isset($_GET['state'])){
37-
$token = $amazon->getAccessToken($_GET['code'], $_GET['state']);
38-
39-
// save the token [...]
17+
/** @var \OAuthProviderFactory $factory */
18+
$provider = $factory->getProvider(Amazon::class, $ENVVAR);
4019

41-
// access granted, redirect
42-
header('Location: ?granted='.$servicename);
43-
}
44-
// step 4: verify the token and use the API
45-
elseif(isset($_GET['granted']) && $_GET['granted'] === $servicename){
46-
echo '<pre>'.print_r(MessageUtil::decodeJSON($amazon->me()), true).'</pre>';
47-
echo '<textarea cols="120" rows="3" onclick="this.select();">'.$storage->getAccessToken($servicename)->toJSON().'</textarea>';
48-
}
49-
// step 1 (optional): display a login link
50-
else{
51-
echo '<a href="?login='.$servicename.'">connect with '.$servicename.'!</a>';
52-
}
20+
require_once __DIR__.'/_flow-oauth2.php';
5321

5422
exit;

examples/get-token/BattleNet.php

Lines changed: 4 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -8,47 +8,15 @@
88
* @license MIT
99
*/
1010

11-
use chillerlan\HTTP\Utils\MessageUtil;
1211
use chillerlan\OAuth\Providers\BattleNet;
1312

14-
$ENVVAR = 'BATTLENET';
13+
$ENVVAR ??= 'BATTLENET';
1514

1615
require_once __DIR__.'/../provider-example-common.php';
1716

18-
/**
19-
* @var \Psr\Http\Client\ClientInterface $http
20-
* @var \chillerlan\OAuth\Storage\OAuthStorageInterface $storage
21-
* @var \chillerlan\Settings\SettingsContainerInterface $options
22-
* @var \Psr\Log\LoggerInterface $logger
23-
* @var array $SCOPES
24-
*/
25-
26-
$battlenet = new BattleNet($http, $options, $logger);
27-
$battlenet->setStorage($storage);
28-
29-
$servicename = $battlenet->serviceName;
30-
31-
// step 2: redirect to the provider's login screen
32-
if(isset($_GET['login']) && $_GET['login'] === $servicename){
33-
header('Location: '.$battlenet->getAuthURL(null, $SCOPES));
34-
}
35-
// step 3: receive the access token
36-
elseif(isset($_GET['code']) && isset($_GET['state'])){
37-
$token = $battlenet->getAccessToken($_GET['code'], $_GET['state']);
38-
39-
// save the token [...]
17+
/** @var \OAuthProviderFactory $factory */
18+
$provider = $factory->getProvider(BattleNet::class, $ENVVAR);
4019

41-
// access granted, redirect
42-
header('Location: ?granted='.$servicename);
43-
}
44-
// step 4: verify the token and use the API
45-
elseif(isset($_GET['granted']) && $_GET['granted'] === $servicename){
46-
echo '<pre>'.print_r(MessageUtil::decodeJSON($battlenet->me()), true).'</pre>';
47-
echo '<textarea cols="120" rows="3" onclick="this.select();">'.$storage->getAccessToken($servicename)->toJSON().'</textarea>';
48-
}
49-
// step 1 (optional): display a login link
50-
else{
51-
echo '<a href="?login='.$servicename.'">connect with '.$servicename.'!</a>';
52-
}
20+
require_once __DIR__.'/_flow-oauth2.php';
5321

5422
exit;

0 commit comments

Comments
 (0)