summaryrefslogtreecommitdiff
path: root/matrix-specification/Requests/ClientLoginPostRequest.php
blob: 161c6de3a1ae79475b2add2a1ffac522fb2db7f9 (plain)
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
<?php

namespace Matrix\Requests;

use Matrix\Data\UserIdentifier;
use Matrix\Enums\ApiPathVersion;
use Matrix\Enums\LoginType;
use Matrix\Request;

class ClientLoginPostRequest extends Request implements RateLimited
{
  public function __construct(
    private LoginType $type,
    private ?string $deviceId = null,
    private ?UserIdentifier $identifier = null,
    private ?string $initialDeviceDisplayName = null,
    private ?string $password = null,
    private ?bool $refreshToken = null,
    private ?string $token = null,
  )
  {
    if ($type == LoginType::PASSWORD && is_null($password)) {
      throw new \InvalidArgumentException("password is required when using LoginType password");
    }

    if ($type == LoginType::TOKEN && is_null($token)) {
      throw new \InvalidArgumentException("token is required when using LoginType token");
    }
  }

  public function getUri(string $scheme, string $serverName, ApiPathVersion $version): string
  {
    return "{$scheme}://{$serverName}/_matrix/client/{$version}/login";
  }

  public function getQueryParameters(): array
  {
    return [];
  }

  public function getBody(): array
  {
    $request = [
      "device_id" => $this->deviceId,
      "identifier" => $this->identifier,
      "initial_device_display_name" => $this->initialDeviceDisplayName,
      "refresh_token" => $this->refreshToken,
      "type" => $this->type,
    ];

    $request += match ($this->type) {
      LoginType::PASSWORD => [
        "password" => $this->password,
      ],

      LoginType::TOKEN => [
        "token" => $this->token,
      ],

      default => [],
    };

    return array_filter($request, fn ($value) => ! is_null($value));
  }
}