DBStringExtension::KeepWordsTogether()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 10
c 2
b 0
f 0
dl 0
loc 16
rs 9.9332
cc 4
nc 8
nop 1
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