1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Created by PhpStorm. |
5
|
|
|
* User: gordon |
6
|
|
|
* Date: 24/3/2561 |
7
|
|
|
* Time: 20:36 น. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Suilven\FreeTextSearch\Base; |
11
|
|
|
|
12
|
|
|
use SilverStripe\ORM\DataObjectSchema; |
13
|
|
|
use Suilven\FreeTextSearch\Indexes; |
14
|
|
|
|
15
|
|
|
abstract class IndexCreator implements \Suilven\FreeTextSearch\Interfaces\IndexCreator |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* (Re)create an index of the given name, using the index configuration from YML |
19
|
|
|
* |
20
|
|
|
* @param string $indexName The name of the index |
21
|
|
|
*/ |
22
|
|
|
abstract public function createIndex(string $indexName): void; |
23
|
|
|
|
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Helper method to get get field specs for a DataObject relevant to it's index definition |
27
|
|
|
* |
28
|
|
|
* @param string $indexName the name of the index |
29
|
|
|
* @return array<string,string> |
30
|
|
|
*/ |
31
|
|
|
protected function getFieldSpecs(string $indexName): array |
32
|
|
|
{ |
33
|
|
|
$indexes = new Indexes(); |
34
|
|
|
$index = $indexes->getIndex($indexName); |
35
|
|
|
$singleton = \singleton($index->getClass()); |
36
|
|
|
|
37
|
|
|
$fields = $this->getFields($indexName); |
38
|
|
|
|
39
|
|
|
/** @var \SilverStripe\ORM\DataObjectSchema $schema */ |
40
|
|
|
$schema = $singleton->getSchema(); |
41
|
|
|
$specs = $schema->fieldSpecs($index->getClass(), DataObjectSchema::INCLUDE_CLASS); |
42
|
|
|
|
43
|
|
|
/** @var array<string,string> $filteredSpecs the DB specs for fields related to the index */ |
44
|
|
|
$filteredSpecs = []; |
45
|
|
|
|
46
|
|
|
foreach ($fields as $field) { |
47
|
|
|
$fieldType = $specs[$field]; |
48
|
|
|
|
49
|
|
|
// fix likes of varchar(255) |
50
|
|
|
$fieldType = \explode('(', $fieldType)[0]; |
51
|
|
|
|
52
|
|
|
// remove the class name |
53
|
|
|
$fieldType = \explode('.', $fieldType)[1]; |
54
|
|
|
|
55
|
|
|
$filteredSpecs[$field] = $fieldType; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $filteredSpecs; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param string $indexName |
64
|
|
|
* @return array<string,string> |
65
|
|
|
*/ |
66
|
|
|
protected function getFields($indexName) |
67
|
|
|
{ |
68
|
|
|
$indexes = new Indexes(); |
69
|
|
|
$index = $indexes->getIndex($indexName); |
70
|
|
|
|
71
|
|
|
foreach ($index->getFields() as $field) { |
72
|
|
|
$fields[] = $field; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
foreach ($index->getTokens() as $token) { |
76
|
|
|
$fields[] = $token; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return $fields; |
|
|
|
|
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|