Debian Codegraph @

vendor/spomky-labs/otphp/src/Url.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace OTPHP;
6
7 use function array_key_exists;
8 use function is_string;
9 use OTPHP\Exception\InvalidProvisioningUriException;
10
11 /**
12 * @readonly
13 *
14 * @internal
15 */
16 final class Url
17 {
18 /**
19 * @param non-empty-string $scheme
20 * @param non-empty-string $host
21 * @param non-empty-string $path
22 * @param non-empty-string $secret
23 * @param array<non-empty-string, mixed> $query
24 */
25 public function __construct(
26 private readonly string $scheme,
27 private readonly string $host,
28 private readonly string $path,
29 private readonly string $secret,
30 private readonly array $query
31 ) {
32 }
33
34 /**
35 * @return non-empty-string
36 */
37 public function getScheme(): string
38 {
39 return $this->scheme;
40 }
41
42 /**
43 * @return non-empty-string
44 */
45 public function getHost(): string
46 {
47 return $this->host;
48 }
49
50 /**
51 * @return non-empty-string
52 */
53 public function getPath(): string
54 {
55 return $this->path;
56 }
57
58 /**
59 * @return non-empty-string
60 */
61 public function getSecret(): string
62 {
63 return $this->secret;
64 }
65
66 /**
67 * @return array<non-empty-string, mixed>
68 */
69 public function getQuery(): array
70 {
71 return $this->query;
72 }
73
74 /**
75 * @param non-empty-string $uri
76 */
77 public static function fromString(string $uri): self
78 {
79 $parsed_url = parse_url($uri);
80 $parsed_url !== false || throw new InvalidProvisioningUriException('Invalid URI.');
81 foreach (['scheme', 'host', 'path', 'query'] as $key) {
82 array_key_exists($key, $parsed_url) || throw new InvalidProvisioningUriException(
83 'Not a valid OTP provisioning URI'
84 );
85 }
86 $scheme = $parsed_url['scheme'] ?? null;
87 $host = $parsed_url['host'] ?? null;
88 $path = $parsed_url['path'] ?? null;
89 $query = $parsed_url['query'] ?? null;
90 $scheme === 'otpauth' || throw new InvalidProvisioningUriException('Not a valid OTP provisioning URI');
91 (is_string($host) && $host !== '') || throw new InvalidProvisioningUriException('Invalid URI.');
92 (is_string($path) && $path !== '') || throw new InvalidProvisioningUriException('Invalid URI.');
93 is_string($query) || throw new InvalidProvisioningUriException('Invalid URI.');
94 $parsedQuery = [];
95 parse_str($query, $parsedQuery);
96 array_key_exists('secret', $parsedQuery) || throw new InvalidProvisioningUriException(
97 'Not a valid OTP provisioning URI'
98 );
99 $secret = $parsedQuery['secret'];
100 (is_string($secret) && $secret !== '') || throw new InvalidProvisioningUriException('Invalid URI.');
101 unset($parsedQuery['secret']);
102
103 return new self($scheme, $host, $path, $secret, $parsedQuery);
104 }
105 }