TomSelectMultiField::saveInto()   B
last analyzed

Complexity

Conditions 10
Paths 13

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 15
c 1
b 0
f 0
nc 13
nop 1
dl 0
loc 28
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace LeKoala\FormElements;
4
5
use Exception;
6
use SilverStripe\ORM\Relation;
7
use SilverStripe\ORM\DataObject;
8
use SilverStripe\Forms\ListboxField;
9
use SilverStripe\ORM\DataObjectInterface;
10
11
/**
12
 * @link https://tom-select.js.org/
13
 */
14
class TomSelectMultiField extends ListboxField implements AjaxPoweredField, LocalizableField, TagsField
15
{
16
    use TomSelect;
0 ignored issues
show
introduced by
The trait LeKoala\FormElements\TomSelect requires some properties which are not provided by LeKoala\FormElements\TomSelectMultiField: $ID, $db
Loading history...
17
18
    /**
19
     * @param DataObject|DataObjectInterface $record The record to save into
20
     */
21
    public function saveInto(DataObjectInterface $record)
22
    {
23
        $fieldName = $this->getName();
24
        if (empty($fieldName) || empty($record)) {
25
            return;
26
        }
27
28
        /** @var Relation $relation */
29
        $relation = $record->hasMethod($fieldName) ? $record->$fieldName() : null;
30
31
        // Detect DB relation or field
32
        $items = $this->getValueArray();
33
        if ($relation && $relation instanceof Relation) {
0 ignored issues
show
introduced by
$relation is always a sub-type of SilverStripe\ORM\Relation.
Loading history...
34
            foreach ($items as $idx => $item) {
35
                // If the item is a string, it's not an ID and needs to be created
36
                if (!is_numeric($item)) {
37
                    $cb = $this->onNewTag;
38
                    if (!$cb) {
39
                        throw new Exception("Please define a onNewTag callback");
40
                    }
41
                    $items[$idx] = $cb($item);
42
                }
43
            }
44
            // Save ids into relation
45
            $relation->setByIDList(array_values($items));
46
        } elseif ($record->hasField($fieldName)) {
47
            // Save dataValue into field
48
            $record->$fieldName = $this->stringEncode($items);
49
        }
50
    }
51
}
52