Completed
Branch develop (1d947e)
by Nate
02:28
created

DynamicModelError   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 5
dl 0
loc 70
ccs 0
cts 40
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 22 3
A populateSource() 0 14 3
A transformErrors() 0 13 2
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/hubspot/license
6
 * @link       https://www.flipboxfactory.com/software/hubspot/
7
 */
8
9
namespace flipbox\hubspot\transformers;
10
11
use craft\base\ElementInterface;
12
use flipbox\hubspot\HubSpot;
13
use flipbox\hubspot\transformers\error\Interpret;
14
use Flipbox\Transform\Factory;
15
use Flipbox\Transform\Scope;
16
use Flipbox\Transform\Transformers\AbstractTransformer;
17
use yii\base\DynamicModel;
18
19
/**
20
 * This transformer will take an API response and create/populate a User element.
21
 */
22
class DynamicModelError extends AbstractTransformer
23
{
24
    /**
25
     * @param $data
26
     * @param Scope $scope
27
     * @param string|null $identifier
28
     * @param ElementInterface|null $source
29
     * @param string|null $resource
30
     * @return mixed
31
     */
32
    public function __invoke(
33
        $data,
34
        Scope $scope,
35
        string $identifier = null,
36
        ElementInterface $source = null,
37
        string $resource = null
38
    ) {
39
        if (!is_array($data)) {
40
            $data = [$data];
41
        }
42
43
        $errors = $this->transformErrors($data);
44
45
        if (null !== $source) {
46
            $this->populateSource($source, $errors);
47
        }
48
49
        $model = new DynamicModel();
50
        $model->addErrors($errors);
51
52
        return $model;
53
    }
54
55
    /**
56
     * @param $object
57
     * @param array $errors
58
     */
59
    protected function populateSource($object, array $errors)
60
    {
61
        if (!is_object($object) || !method_exists($object, 'addErrors')) {
62
            HubSpot::warning(
63
                "Unable to populate object errors.",
64
                __METHOD__
65
            );
66
67
            return;
68
        }
69
70
        /** @noinspection PhpUndefinedMethodInspection */
71
        $object->addErrors($errors);
72
    }
73
74
    /**
75
     * @param array $data
76
     * @return array
77
     */
78
    protected function transformErrors(array $data): array
79
    {
80
        $errors = Factory::item(
81
            new Interpret,
82
            $data
83
        );
84
85
        if (!$errors) {
86
            $errors = [$errors];
87
        }
88
89
        return array_filter($errors);
90
    }
91
}
92