Passed
Push — master ( 2f8bcf...138ef2 )
by Gordon
03:57 queued 02:01
created

SearchHelper::getTextFieldPayload()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 49
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 49
rs 8.5546
cc 7
nc 7
nop 1
1
<?php declare(strict_types = 1);
2
3
/**
4
 * Created by PhpStorm.
5
 * User: gordon
6
 * Date: 25/3/2561
7
 * Time: 17:01 น.
8
 */
9
10
namespace Suilven\FreeTextSearch\Helper;
11
12
use SilverStripe\ORM\DataObject;
13
use Suilven\FreeTextSearch\Indexes;
14
15
class SearchHelper
16
{
17
    /**
18
     * @param \SilverStripe\ORM\DataObject $dataObject the dataobject to extra text from
19
     * @return array<string,array<string,string>>
20
     */
21
    public function getTextFieldPayload(DataObject $dataObject): array
22
    {
23
        $helper = new IndexingHelper();
24
        $fullPayload = $helper->getFieldsToIndex($dataObject);
25
        $textPayload = [];
26
27
        $keys = \array_keys($fullPayload);
28
        $specsHelper = new SpecsHelper();
29
30
31
        foreach ($keys as $indexKey) {
32
            $indexes = new Indexes();
33
            $index = $indexes->getIndex($indexKey);
34
            $textualFields = $index->getFields();
35
36
            // if the index details are empty, skip
37
            if ($fullPayload[$indexKey] === []) {
38
                continue;
39
            }
40
41
            $textPayload[$indexKey] = [];
42
            $specs = $specsHelper->getFieldSpecs($indexKey);
43
44
            foreach (\array_keys($specs) as $field) {
45
                // skip non textual fields
46
                if (!\in_array($field, $textualFields, true)) {
47
                    continue;
48
                }
49
50
51
                $type = $specs[$field];
52
                if (!\in_array($type, ['Varchar', 'HTMLText'], true)) {
53
                    continue;
54
                }
55
56
                $fieldValue = (string) $fullPayload[$indexKey][$field];
57
                $barchars = ['!', ',', '.', '-'];
58
                $fieldValue = \strip_tags($fieldValue);
59
60
                foreach ($barchars as $badChar) {
61
                    $fieldValue = \str_replace($badChar, '', $fieldValue);
62
                }
63
64
                $fieldValue = \str_replace('/', ' ', $fieldValue);
65
                $textPayload[$indexKey][$field] = $fieldValue;
66
            }
67
        }
68
69
        return $textPayload;
70
    }
71
}
72