Completed
Push — master ( f8c4bd...25c22e )
by Nate
09:23 queued 07:32
created

ObjectId::transformerElementToId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 22
cp 0
rs 9.504
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
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\Element;
12
use craft\base\ElementInterface;
13
use craft\helpers\Json;
14
use flipbox\ember\helpers\SiteHelper;
15
use flipbox\hubspot\fields\Objects;
16
use flipbox\hubspot\HubSpot;
17
use Flipbox\Transform\Transformers\AbstractSimpleTransformer;
18
19
/**
20
 * @author Flipbox Factory <[email protected]>
21
 * @since 1.0.0
22
 */
23
class ObjectId extends AbstractSimpleTransformer
24
{
25
    /**
26
     * @var Objects
27
     */
28
    protected $field;
29
30
    /**
31
     * @param Objects $field
32
     * @inheritdoc
33
     */
34
    public function __construct(Objects $field, $config = [])
35
    {
36
        $this->field = $field;
37
        parent::__construct($config);
38
    }
39
40
    /**
41
     * @inheritdoc
42
     * @return string|null
43
     */
44
    public function __invoke($data, string $identifier = null)
45
    {
46
        if ($data instanceof ElementInterface) {
47
            return $this->transformerElementToId($data);
48
        }
49
50
        HubSpot::warning(sprintf(
51
            "Unable to determine HubSpot Id because data is not an element: %s",
52
            Json::encode($data)
53
        ));
54
55
        return null;
56
    }
57
58
    /**
59
     * @param Element|ElementInterface $element
60
     * @return null|string
61
     */
62
    protected function transformerElementToId(ElementInterface $element)
63
    {
64
        $objectId = HubSpot::getInstance()->getObjectAssociations()->getQuery([
65
            'select' => ['objectId'],
66
            'elementId' => $element->getId(),
67
            'siteId' => SiteHelper::ensureSiteId($element->siteId),
68
            'fieldId' => $this->field->id
69
        ])->scalar();
70
71
        if (!is_string($objectId)) {
72
            HubSpot::warning(sprintf(
73
                "HubSpot Id association was not found for element '%s'",
74
                $element->getId()
75
            ));
76
77
            return null;
78
        }
79
80
        HubSpot::info(sprintf(
81
            "HubSpot Id '%s' was found for element '%s'",
82
            $objectId,
83
            $element->getId()
84
        ));
85
86
        return $objectId;
87
    }
88
}
89