Passed
Pull Request — master (#47)
by Matthew
08:12
created

handleSalsifyRelationType()   B

Complexity

Conditions 10
Paths 16

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
dl 0
loc 24
rs 7.6666
c 2
b 0
f 0
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
    ];
20
21
    /**
22
     * @param string|DataObject $class
23
     * @param array $data
24
     * @param string $dataField
25
     * @param array $config
26
     * @param string $dbField
27
     *
28
     * @return int|DataObject|array
29
     * @throws \Exception
30
     */
31
    public function handleSalsifyRelationType($class, $data, $dataField, $config, $dbField)
32
    {
33
        if (!array_key_exists('salsify:relations', $data)) {
34
            return [];
35
        }
36
37
        $related = [];
38
        $fieldData = $data['salsify:relations'];
39
        foreach ($this->owner->yieldSingle($fieldData) as $relation) {
40
            if (array_key_exists('relation_type', $relation) && $relation['relation_type'] == $dataField) {
41
                $related[] = DataObject::get($class)->find('SalsifyID', $relation['salsify:target_product_id']);
42
            }
43
        }
44
45
        $related = array_filter($related);
46
47
        if (array_key_exists('single', $config) && $config['single'] == true) {
48
            if (count($related)) {
49
                $object = $related[0];
50
                return preg_match('/ID$/', $dbField) ? $object->ID : $object;
51
            }
52
            return preg_match('/ID$/', $dbField) ? 0 : null;
53
        }
54
        return $related;
55
    }
56
}
57