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

DynamicModelError::__invoke()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 18
cp 0
rs 9.568
c 0
b 0
f 0
cc 3
nc 4
nop 5
crap 12
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