Passed
Push — main ( c05ac9...4fe852 )
by smiley
01:41
created

OAuthStorageAbstract::fromStorage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 8
rs 10
cc 2
nc 2
nop 1
1
<?php
2
/**
3
 * Class OAuthStorageAbstract
4
 *
5
 * @created      09.07.2017
6
 * @author       Smiley <[email protected]>
7
 * @copyright    2017 Smiley
8
 * @license      MIT
9
 */
10
11
namespace chillerlan\OAuth\Storage;
12
13
use chillerlan\OAuth\{Core\AccessToken, OAuthOptions};
14
use chillerlan\Settings\SettingsContainerInterface;
15
use Psr\Log\{LoggerAwareTrait, LoggerInterface, NullLogger};
16
use function is_string;
17
18
/**
19
 * Implements an abstract OAuth storage adapter
20
 */
21
abstract class OAuthStorageAbstract implements OAuthStorageInterface{
22
	use LoggerAwareTrait;
23
24
	protected OAuthOptions|SettingsContainerInterface $options;
25
	protected string $serviceName;
26
27
	/**
28
	 * OAuthStorageAbstract constructor.
29
	 */
30
	public function __construct(OAuthOptions|SettingsContainerInterface $options = null, LoggerInterface $logger = null){
31
		$this->options = $options ?? new OAuthOptions;
32
		$this->logger  = $logger ?? new NullLogger;
33
	}
34
35
	/**
36
	 * @inheritDoc
37
	 */
38
	public function setServiceName(string $service):OAuthStorageInterface{
39
		$service = trim($service);
40
41
		if(empty($service)){
42
			throw new OAuthStorageException('service name must not be empty');
43
		}
44
45
		$this->serviceName = $service;
46
47
		return $this;
48
	}
49
50
	/**
51
	 * @inheritDoc
52
	 */
53
	public function getServiceName(string $service = null):string{
54
55
		if($service === null && !isset($this->serviceName)){
56
			throw new OAuthStorageException('invalid service');
57
		}
58
59
		$name = trim($service ?? $this->serviceName);
60
61
		if(empty($name)){
62
			throw new OAuthStorageException('service name must not be empty');
63
		}
64
65
		return $name;
66
	}
67
68
	/**
69
	 * @inheritDoc
70
	 */
71
	public function toStorage(AccessToken $token):string{
72
		return $token->toJSON();
73
	}
74
75
	/**
76
	 * @inheritDoc
77
	 * @phan-suppress PhanTypeMismatchReturnSuperType
78
	 */
79
	public function fromStorage(mixed $data):AccessToken{
80
81
		if(!is_string($data)){
82
			throw new OAuthStorageException('invalid data');
83
		}
84
85
		/** @noinspection PhpIncompatibleReturnTypeInspection */
86
		return (new AccessToken)->fromJSON($data);
87
	}
88
89
}
90