Passed
Push — master ( 062d38...16e64f )
by Gordon
02:32 queued 43s
created

BulkIndexer::indexDataObjects()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 13
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 21
rs 9.8333
1
<?php declare(strict_types=1);
2
3
/**
4
 * Created by PhpStorm.
5
 * User: gordon
6
 * Date: 24/3/2561
7
 * Time: 21:14 น.
8
 */
9
10
namespace Suilven\ManticoreSearch\Service;
11
12
use SilverStripe\ORM\DataObject;
13
use Suilven\FreeTextSearch\Helper\IndexingHelper;
14
15
/**
16
 * Class BulkIndexer
17
 * @package Suilven\ManticoreSearch\Service
18
 *
19
 * @todo Move some of this into a base indexer
20
 */
21
class BulkIndexer  implements \Suilven\FreeTextSearch\Interfaces\BulkIndexer
22
{
23
    protected $bulkIndexData;
24
25
    /** @var string */
26
    protected $index;
27
28
29
    public function __construct()
30
    {
31
        $this->resetBulkIndexData();
32
    }
33
34
    /** @param string $newIndex the new index name */
35
    public function setIndex(string $newIndex): void
36
    {
37
        $this->index = $newIndex;
38
    }
39
40
41
    /**
42
     * Note this makes the assumption of unique IDs, along with one index
43
     *
44
     * @param DataObject $dataObject
45
     */
46
    public function addDataObject(DataObject $dataObject): void
47
    {
48
        $helper = new IndexingHelper();
49
        $payload = $helper->getFieldsToIndex($dataObject);
50
        $this->bulkIndexData[$dataObject->ID] = $payload[$this->index];
51
    }
52
53
54
    public function indexDataObjects()
55
    {
56
        $body = [];
57
58
        foreach(array_keys($this->bulkIndexData) as $dataObjectID)
59
        {
60
            $docPayload = [
61
                'replace' => [
62
                    'index' => $this->index,
63
                    'id' => $dataObjectID,
64
                    'doc' => $this->bulkIndexData[$dataObjectID]
65
                ]
66
            ];
67
            $body[] = $docPayload;
68
        }
69
70
        $coreClient = new Client();
71
        $client = $coreClient->getConnection();
72
        $payload = ['body' => $body];
73
        $client->bulk($payload);
74
        $this->resetBulkIndexData();
75
    }
76
77
78
    private function resetBulkIndexData(): void
79
    {
80
        $this->bulkIndexData = [];
81
82
    }
83
84
}
85