+60
src/Data/Record.php
+60
src/Data/Record.php
···
1
+
<?php
2
+
3
+
namespace SocialDept\AtpClient\Data;
4
+
5
+
use Illuminate\Contracts\Support\Arrayable;
6
+
7
+
/**
8
+
* Generic wrapper for AT Protocol records.
9
+
*
10
+
* @template T
11
+
*/
12
+
class Record
13
+
{
14
+
/**
15
+
* @param T $value
16
+
*/
17
+
public function __construct(
18
+
public readonly string $uri,
19
+
public readonly string $cid,
20
+
public readonly mixed $value,
21
+
) {}
22
+
23
+
/**
24
+
* @template U
25
+
* @param array $data
26
+
* @param callable(array): U $transformer
27
+
* @return self<U>
28
+
*/
29
+
public static function fromArray(array $data, callable $transformer): self
30
+
{
31
+
return new self(
32
+
uri: $data['uri'],
33
+
cid: $data['cid'],
34
+
value: $transformer($data['value']),
35
+
);
36
+
}
37
+
38
+
/**
39
+
* Create without transforming value.
40
+
*/
41
+
public static function fromArrayRaw(array $data): self
42
+
{
43
+
return new self(
44
+
uri: $data['uri'],
45
+
cid: $data['cid'],
46
+
value: $data['value'],
47
+
);
48
+
}
49
+
50
+
public function toArray(): array
51
+
{
52
+
return [
53
+
'uri' => $this->uri,
54
+
'cid' => $this->cid,
55
+
'value' => $this->value instanceof Arrayable
56
+
? $this->value->toArray()
57
+
: $this->value,
58
+
];
59
+
}
60
+
}
+58
src/Data/RecordCollection.php
+58
src/Data/RecordCollection.php
···
1
+
<?php
2
+
3
+
namespace SocialDept\AtpClient\Data;
4
+
5
+
/**
6
+
* Collection wrapper for paginated AT Protocol records.
7
+
*
8
+
* @template T
9
+
*/
10
+
class RecordCollection
11
+
{
12
+
/**
13
+
* @param array<Record<T>> $records
14
+
*/
15
+
public function __construct(
16
+
public readonly array $records,
17
+
public readonly ?string $cursor = null,
18
+
) {}
19
+
20
+
/**
21
+
* @template U
22
+
* @param array $data
23
+
* @param callable(array): U $transformer
24
+
* @return self<U>
25
+
*/
26
+
public static function fromArray(array $data, callable $transformer): self
27
+
{
28
+
return new self(
29
+
records: array_map(
30
+
fn (array $record) => Record::fromArray($record, $transformer),
31
+
$data['records'] ?? []
32
+
),
33
+
cursor: $data['cursor'] ?? null,
34
+
);
35
+
}
36
+
37
+
/**
38
+
* Create without transforming values.
39
+
*/
40
+
public static function fromArrayRaw(array $data): self
41
+
{
42
+
return new self(
43
+
records: array_map(
44
+
fn (array $record) => Record::fromArrayRaw($record),
45
+
$data['records'] ?? []
46
+
),
47
+
cursor: $data['cursor'] ?? null,
48
+
);
49
+
}
50
+
51
+
public function toArray(): array
52
+
{
53
+
return [
54
+
'records' => array_map(fn (Record $r) => $r->toArray(), $this->records),
55
+
'cursor' => $this->cursor,
56
+
];
57
+
}
58
+
}