Completed
Push — develop ( f8c4bd...63ca71 )
by Nate
02:47
created

ObjectId::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 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\Objects;
14
use flipbox\hubspot\HubSpot;
15
use Flipbox\Transform\Transformers\AbstractSimpleTransformer;
16
17
class ObjectId extends AbstractSimpleTransformer
18
{
19
    /**
20
     * @var Objects
21
     */
22
    protected $field;
23
24
    /**
25
     * @param Objects $field
26
     * @inheritdoc
27
     */
28
    public function __construct(Objects $field, $config = [])
29
    {
30
        $this->field = $field;
31
        parent::__construct($config);
32
    }
33
34
    /**
35
     * @inheritdoc
36
     * @return string|null
37
     */
38
    public function __invoke($data, 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 null;
50
    }
51
52
    /**
53
     * @param ElementInterface $element
54
     * @return null|string
55
     */
56
    protected function transformerElementToId(ElementInterface $element)
57
    {
58
        $objectId = HubSpot::getInstance()->getObjectAssociations()->getQuery([
59
            'select' => ['objectId'],
60
            'elementId' => $element->getId(),
61
            'siteId' => $element->siteId,
62
            'fieldId' => $this->field->id
63
        ])->scalar();
64
65
        if (!is_string($objectId)) {
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
            $objectId,
77
            $element->getId()
78
        ));
79
80
        return $objectId;
81
    }
82
}
83