Passed
Push — master ( 76df74...7115c3 )
by Gordon
02:05
created

SpecsHelper   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 20
c 1
b 0
f 0
dl 0
loc 47
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A getFieldSpecs() 0 39 5
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\DataObjectSchema;
13
use Suilven\FreeTextSearch\Indexes;
14
15
class SpecsHelper
16
{
17
    /**
18
     * Helper method to get get field specs for a DataObject relevant to it's index definition
19
     *
20
     * @param string $indexName the name of the index
21
     * @return array<string,string>
22
     */
23
    public function getFieldSpecs(string $indexName): array
24
    {
25
        $indexes = new Indexes();
26
        $index = $indexes->getIndex($indexName);
27
        $singleton = \singleton((string)($index->getClass()));
28
29
        $helper = new IndexingHelper();
30
        $fields = $helper->getFields($indexName);
31
32
        /** @var \SilverStripe\ORM\DataObjectSchema $schema */
33
        $schema = $singleton->getSchema();
34
        $specs = $schema->fieldSpecs((string) $index->getClass(), DataObjectSchema::INCLUDE_CLASS);
35
36
        /** @var array<string,string> $filteredSpecs the DB specs for fields related to the index */
37
        $filteredSpecs = [];
38
39
        foreach ($fields as $field) {
40
            if ($field === 'Link') {
41
                continue;
42
            }
43
            $fieldType = $specs[$field];
44
45
            // fix likes of varchar(255)
46
            $fieldType = \explode('(', $fieldType)[0];
47
48
            // remove the class name
49
            $fieldType = \explode('.', $fieldType)[1];
50
51
            $filteredSpecs[$field] = $fieldType;
52
        }
53
54
        // if Link undefined in the original index specs, add it if the method exists on the singleton dataobject
55
        if (!isset($filteredSpecs['Link'])) {
56
            if (\method_exists($singleton, 'Link')) {
57
                $filteredSpecs['Link'] = 'Varchar';
58
            }
59
        }
60
61
        return $filteredSpecs;
62
    }
63
}
64