handleSalsifyRelationType()   B
last analyzed

Complexity

Conditions 10
Paths 16

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 24
rs 7.6666
cc 10
nc 16
nop 5

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 Dynamic\Salsify\TypeHandler\Relation;
4
5
use SilverStripe\Core\Extension;
6
use SilverStripe\ORM\DataObject;
7
8
/**
9
 * Class SalsifyRelation
10
 * @package Dynamic\Salsify\TypeHandler\Relation
11
 */
12
class SalsifyRelationHandler extends Extension
13
{
14
    /**
15
     * @var array
16
     */
17
    private static $field_types = [
0 ignored issues
show
introduced by
The private property $field_types is not used, and could be removed.
Loading history...
18
        'SalsifyRelation' => [
19
            'requiresWrite' => false,
20
            'requiresSalsifyObjects' => true,
21
            'allowsModification' => false,
22
        ],
23
        'SalsifyRelationsUpdatedAt' => [
24
            'requiresWrite' => false,
25
            'requiresSalsifyObjects' => true,
26
            'allowsModification' => false,
27
            'fallback' => 'Raw',
28
        ],
29
    ];
30
31
    /**
32
     * @param string|DataObject $class
33
     * @param array $data
34
     * @param string $dataField
35
     * @param array $config
36
     * @param string $dbField
37
     *
38
     * @return int|DataObject|array
39
     * @throws \Exception
40
     */
41
    public function handleSalsifyRelationType($class, $data, $dataField, $config, $dbField)
42
    {
43
        if (!array_key_exists('salsify:relations', $data)) {
44
            return [];
45
        }
46
47
        $related = [];
48
        $fieldData = $data['salsify:relations'];
49
        foreach ($this->owner->yieldSingle($fieldData) as $relation) {
50
            if (array_key_exists('relation_type', $relation) && $relation['relation_type'] == $dataField) {
51
                $related[] = DataObject::get($class)->find('SalsifyID', $relation['salsify:target_product_id']);
52
            }
53
        }
54
55
        $related = array_filter($related);
56
57
        if (array_key_exists('single', $config) && $config['single'] == true) {
58
            if (count($related)) {
59
                $object = $related[0];
60
                return preg_match('/ID$/', $dbField) ? $object->ID : $object;
61
            }
62
            return preg_match('/ID$/', $dbField) ? 0 : null;
63
        }
64
        return $related;
65
    }
66
}
67