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

namespace Matrix\Requests;

use Matrix\Enums\LoginType;
use Matrix\UserIdentifier;

class ClientLoginPostRequest implements RateLimited, \JsonSerializable
{
  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 jsonSerialize(): 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, "is_null");
  }
}