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

SalsifyRelationHandler   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B handleSalsifyRelationType() 0 24 10
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