ScopeURI.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Twilio\Jwt\Client;
  3. /**
  4. * Scope URI implementation
  5. *
  6. * Simple way to represent configurable privileges in an OAuth
  7. * friendly way. For our case, they look like this:
  8. *
  9. * scope:<service>:<privilege>?<params>
  10. *
  11. * For example:
  12. * scope:client:incoming?name=jonas
  13. */
  14. class ScopeURI {
  15. public $service;
  16. public $privilege;
  17. public $params;
  18. public function __construct($service, $privilege, $params = array()) {
  19. $this->service = $service;
  20. $this->privilege = $privilege;
  21. $this->params = $params;
  22. }
  23. public function toString() {
  24. $uri = "scope:{$this->service}:{$this->privilege}";
  25. if (count($this->params)) {
  26. $uri .= "?" . http_build_query($this->params, '', '&');
  27. }
  28. return $uri;
  29. }
  30. /**
  31. * Parse a scope URI into a ScopeURI object
  32. *
  33. * @param string $uri The scope URI
  34. * @return ScopeURI The parsed scope uri
  35. * @throws \UnexpectedValueException
  36. */
  37. public static function parse($uri) {
  38. if (strpos($uri, 'scope:') !== 0) {
  39. throw new \UnexpectedValueException(
  40. 'Not a scope URI according to scheme');
  41. }
  42. $parts = explode('?', $uri, 1);
  43. $params = null;
  44. if (count($parts) > 1) {
  45. parse_str($parts[1], $params);
  46. }
  47. $parts = explode(':', $parts[0], 2);
  48. if (count($parts) != 3) {
  49. throw new \UnexpectedValueException(
  50. 'Not enough parts for scope URI');
  51. }
  52. list($scheme, $service, $privilege) = $parts;
  53. return new ScopeURI($service, $privilege, $params);
  54. }
  55. }