-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathScopes.php
More file actions
108 lines (92 loc) · 2.64 KB
/
Scopes.php
File metadata and controls
108 lines (92 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
declare(strict_types=1);
namespace Shopify\Auth;
final class Scopes
{
public const SCOPE_DELIMITER = ',';
/** @var array */
private $compressedScopes;
/** @var array */
private $expandedScopes;
/**
* @param string|array $scopes
*/
public function __construct($scopes)
{
if (is_string($scopes)) {
$scopesArray = explode(self::SCOPE_DELIMITER, $scopes);
} else {
$scopesArray = $scopes ?? [];
}
$scopesArray = array_unique(array_filter(array_map('trim', $scopesArray)));
$impliedScopes = $this->getImpliedScopes($scopesArray);
$this->compressedScopes = array_diff($scopesArray, $impliedScopes);
$this->expandedScopes = array_merge($scopesArray, $impliedScopes);
}
/**
* Converts the scopes in this object to a valid string.
*
* @return string
*/
public function toString(): string
{
return implode(self::SCOPE_DELIMITER, $this->toArray());
}
/**
* Converts the scopes in this object to a valid array.
*
* @return array
*/
public function toArray(): array
{
return $this->compressedScopes;
}
/**
* Checks whether the scopes in this object encapsulate the given scopes.
*
* @param string|array|Scopes $scopes The scopes to check
*
* @return bool
*/
public function has($scopes): bool
{
if (!($scopes instanceof self)) {
$scopes = new self($scopes);
}
return count(array_diff($scopes->toArray(), $this->expandedScopes)) === 0;
}
/**
* Checks whether the given scopes are equal to the scopes in this object.
*
* @param string|array|Scopes $scopes The scopes to check
*
* @return bool
*/
public function equals($scopes): bool
{
if (!($scopes instanceof self)) {
$scopes = new self($scopes);
}
return (
count($this->compressedScopes) === count($scopes->compressedScopes) &&
count(array_diff($this->compressedScopes, $scopes->compressedScopes)) === 0
);
}
/**
* Returns any scopes that are implied by any of the given ones.
*
* @param array $scopes The scopes to check
*
* @return array
*/
private function getImpliedScopes(array $scopes): array
{
$impliedScopes = [];
foreach ($scopes as $scope) {
if (preg_match('/^(unauthenticated_)?write_(.*)$/', $scope, $matches)) {
$impliedScopes[] = ($matches[1] ?? '') . "read_{$matches[2]}";
}
}
return $impliedScopes;
}
}