DBStringExtension   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 6
eloc 17
c 2
b 0
f 0
dl 0
loc 32
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A KeepWordsTogether() 0 16 4
A replaceKeepWordsTogether() 0 8 2
1
<?php
2
3
namespace Sunnysideup\KeepWordsTogether;
4
5
use SilverStripe\Core\Extension;
6
use SilverStripe\ORM\FieldType\DBField;
7
use SilverStripe\ORM\FieldType\DBHTMLText;
8
9
class DBStringExtension extends Extension
10
{
11
    private const SPAN_START = '<span class="keep-together">';
12
13
    private const SPAN_END = '</span>';
14
15
    public function KeepWordsTogether(?string $words = '')
16
    {
17
        $text = $this->owner->getValue();
18
        $replacers = WordsToKeepTogether::get();
19
        if ($words) {
20
            $text = $this->replaceKeepWordsTogether($text, $words);
21
        }
22
        foreach ($replacers as $replacer) {
23
            $text = $this->replaceKeepWordsTogether($text, $replacer->Title);
24
        }
25
        $field = DBField::create_field(DBHTMLText::class, $text);
26
        if ($field instanceof DBHTMLText) {
27
            $field->setProcessShortcodes(true);
28
        }
29
30
        return $field;
31
    }
32
33
    protected function replaceKeepWordsTogether(string $text, string $words)
34
    {
35
        if (stripos($text, $words) !== false) {
36
            $newString = self::SPAN_START . $words . self::SPAN_END;
37
            $text = str_ireplace($words, $newString, $text);
38
        }
39
40
        return $text;
41
    }
42
}
43