Completed
Push — develop ( f37ae4...1d947e )
by Nate
18:30
created

HubSpotId   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 5
dl 0
loc 65
ccs 0
cts 38
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A __invoke() 0 13 2
A transformerElementToId() 0 26 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\elements;
10
11
use craft\base\ElementInterface;
12
use craft\helpers\Json;
13
use flipbox\hubspot\fields\Resources;
14
use flipbox\hubspot\HubSpot;
15
use Flipbox\Transform\Scope;
16
use Flipbox\Transform\Transformers\AbstractTransformer;
17
18
class HubSpotId extends AbstractTransformer
19
{
20
    /**
21
     * @var Resources
22
     */
23
    protected $field;
24
25
    /**
26
     * @param Resources $field
27
     * @inheritdoc
28
     */
29
    public function __construct(Resources $field, $config = [])
30
    {
31
        $this->field = $field;
32
        parent::__construct($config);
33
    }
34
35
    /**
36
     * @inheritdoc
37
     */
38
    public function __invoke($data, Scope $scope, string $identifier = null)
39
    {
40
        if ($data instanceof ElementInterface) {
41
            return $this->transformerElementToId($data);
42
        }
43
44
        HubSpot::warning(sprintf(
45
            "Unable to determine HubSpot Id because data is not an element: %s",
46
            Json::encode($data)
47
        ));
48
49
        return $data;
50
    }
51
52
    /**
53
     * @param ElementInterface $element
54
     * @return null|string
55
     */
56
    protected function transformerElementToId(ElementInterface $element)
57
    {
58
        $hubSpotId = HubSpot::getInstance()->getResourceAssociations()->getQuery([
59
            'select' => ['hubSpotId'],
60
            'elementId' => $element->getId(),
61
            'siteId' => $element->siteId,
62
            'fieldId' => $this->field->id
63
        ])->scalar();
64
65
        if (!is_string($hubSpotId)) {
66
            HubSpot::warning(sprintf(
67
                "HubSpot Id association was not found for element '%s'",
68
                $element->getId()
69
            ));
70
71
            return null;
72
        }
73
74
        HubSpot::info(sprintf(
75
            "HubSpot Id '%s' was found for element '%s'",
76
            $hubSpotId,
77
            $element->getId()
78
        ));
79
80
        return $hubSpotId;
81
    }
82
}
83