-
Notifications
You must be signed in to change notification settings - Fork 2
/
Indexable.php
99 lines (85 loc) · 2.35 KB
/
Indexable.php
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
98
99
<?php
declare(strict_types=1);
namespace Netgen\IbexaSearchExtra\Core\FieldType\RichText;
use DOMDocument;
use DOMNode;
use Ibexa\Contracts\Core\FieldType\Indexable as IndexableInterface;
use Ibexa\Contracts\Core\Persistence\Content\Field;
use Ibexa\Contracts\Core\Persistence\Content\Type\FieldDefinition;
use Ibexa\Contracts\Core\Search;
use function mb_substr;
use function strtok;
use function trim;
/**
* Indexable definition for RichText field type.
*/
final class Indexable implements IndexableInterface
{
/**
* @var int
*/
private $shortTextMaxLength;
public function __construct($shortTextMaxLength = 256)
{
$this->shortTextMaxLength = $shortTextMaxLength;
}
public function getIndexData(Field $field, FieldDefinition $fieldDefinition): array
{
$document = new DOMDocument();
$document->loadXML($field->value->data);
$text = $this->extractText($document->documentElement);
$shortText = $this->shortenText($text);
return [
new Search\Field(
'fulltext',
$text,
new Search\FieldType\FullTextField(),
),
new Search\Field(
'value',
$shortText,
new Search\FieldType\StringField(),
),
];
}
public function getIndexDefinition(): array
{
return [
'value' => new Search\FieldType\StringField(),
];
}
public function getDefaultMatchField(): string
{
return 'value';
}
public function getDefaultSortField(): string
{
return $this->getDefaultMatchField();
}
/**
* Extracts text content of the given $node.
*
* @param \DOMNode $node
*
* @return string
*/
private function extractText(DOMNode $node): string
{
$text = '';
if ($node->childNodes !== null && $node->childNodes->length > 0) {
foreach ($node->childNodes as $child) {
$text .= $this->extractText($child);
}
} else {
$text .= $node->nodeValue . ' ';
}
return $text;
}
/**
* Shorten text from the given $text.
*/
private function shortenText(string $text): string
{
return mb_substr(trim(strtok($text, "\r\n")), 0, $this->shortTextMaxLength);
}
}