-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPageNode.php
More file actions
97 lines (80 loc) · 2.54 KB
/
PageNode.php
File metadata and controls
97 lines (80 loc) · 2.54 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace OneOffTech\Parse\Client\DocumentFormat;
use Countable;
use OneOffTech\Parse\Client\Exceptions\InvalidDocumentFormatException;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
class PageNode implements Countable
{
public function __construct(
public readonly array $content,
public readonly array $attributes = [],
) {}
public function type(): string
{
return 'page';
}
/**
* The number of elements in this page.
*/
public function count(): int
{
return count($this->content);
}
/**
* Test if the page is empty, i.e. contains no textual content
*/
public function isEmpty(): bool
{
return $this->count() === 0 || ! $this->hasContent();
}
/**
* Test if the page has discernible textual content
*/
public function hasContent(): bool
{
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($this->content), RecursiveIteratorIterator::LEAVES_ONLY) as $key => $value) {
if (($key === 'text' || $key === 'content') && ! empty($value)) {
return true;
}
}
return false;
}
/**
* The elements in this page
*/
public function items(): array
{
return $this->content;
}
public function text(): string
{
$text = [];
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($this->content), RecursiveIteratorIterator::LEAVES_ONLY) as $key => $value) {
if (($key === 'text' || $key === 'content') && ! empty($value)) {
$text[] = $value;
}
}
return implode(PHP_EOL, $text);
}
public function number(): int
{
return (int) $this->attributes['page'] ?? 1;
}
/**
* Create a page node from associative array
*/
public static function fromArray(array $data): PageNode
{
if (! (isset($data['category']) && isset($data['content']))) {
throw new InvalidDocumentFormatException('Unexpected document structure. Missing category or content.');
}
if ($data['category'] !== 'page') {
throw new InvalidDocumentFormatException("Unexpected node category. Expecting [doc] found [{$data['category']}].");
}
if (! is_array($data['content'])) {
throw new InvalidDocumentFormatException('Unexpected content format. Expecting [array].');
}
return new PageNode($data['content'] ?? [], $data['attributes'] ?? []);
}
}