Passed
Push — master ( 0135fb...fb3806 )
by Gordon
05:08 queued 02:15
created

IndexCreator::getFieldSpecs()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 35
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 35
rs 9.7
cc 4
nc 8
nop 1
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
        $fields = [];
36
        $singleton = \singleton($index->getClass());
37
38
        foreach ($index->getFields() as $field) {
39
            $fields[] = $field;
40
        }
41
42
        foreach ($index->getTokens() as $token) {
43
            $fields[] = $token;
44
        }
45
46
        /** @var \SilverStripe\ORM\DataObjectSchema $schema */
47
        $schema = $singleton->getSchema();
48
        $specs = $schema->fieldSpecs($index->getClass(), DataObjectSchema::INCLUDE_CLASS);
49
50
        /** @var array<string,string> $filteredSpecs the DB specs for fields related to the index */
51
        $filteredSpecs = [];
52
53
        foreach ($fields as $field) {
54
            $fieldType = $specs[$field];
55
56
            // fix likes of varchar(255)
57
            $fieldType = \explode('(', $fieldType)[0];
58
59
            // remove the class name
60
            $fieldType = \explode('.', $fieldType)[1];
61
62
            $filteredSpecs[$field] = $fieldType;
63
        }
64
65
        return $filteredSpecs;
66
    }
67
}
68