Completed
Push — master ( 37c0e6...5c203e )
by Nate
08:56 queued 06:36
created

ObjectAssociation::ensureTableExists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 10
cp 0
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
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\craft\hubspot\records;
10
11
use Craft;
12
use flipbox\craft\hubspot\fields\ObjectsFieldInterface;
13
use flipbox\craft\hubspot\HubSpot;
14
use flipbox\craft\hubspot\migrations\ObjectAssociations;
15
use flipbox\craft\integration\records\IntegrationAssociation;
16
use Psr\Http\Message\ResponseInterface;
17
18
/**
19
 * @author Flipbox Factory <[email protected]>
20
 * @since 1.0.0
21
 *
22
 * @property int $fieldId
23
 * @property string $objectId
24
 */
25
class ObjectAssociation extends IntegrationAssociation
26
{
27
    /**
28
     * The table alias
29
     */
30
    const TABLE_ALIAS = 'hubspot_objects';
31
32
    /**
33
     * @inheritdoc
34
     * @throws \Throwable
35
     */
36
    public function __construct(array $config = [])
37
    {
38
        $this->ensureTableExists();
39
        parent::__construct($config);
40
    }
41
42
43
    /**
44
     * @throws \Throwable
45
     */
46
    public function ensureTableExists()
47
    {
48
        if (!in_array(
49
            Craft::$app->getDb()->tablePrefix . static::tableAlias(),
50
            Craft::$app->getDb()->getSchema()->tableNames,
51
            true
52
        )) {
53
            $this->createTable();
54
        }
55
    }
56
57
    /**
58
     * @return bool
59
     * @throws \Throwable
60
     */
61
    private function createTable(): bool
62
    {
63
        ob_start();
64
        (new ObjectAssociations())->up();
65
        ob_end_clean();
66
67
        return true;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public static function tableAlias()
74
    {
75
        return parent::tableAlias() . HubSpot::getInstance()->getSettings()->environmentTablePostfix;
76
    }
77
78
    /**
79
     * @return ResponseInterface
80
     */
81
    public function getObject(): ResponseInterface
82
    {
83
        if (null === ($field = $this->getField())) {
84
            return null;
85
        }
86
87
        if (!$field instanceof ObjectsFieldInterface) {
88
            return null;
89
        }
90
91
        $id = $this->objectId ?: self::DEFAULT_ID;
92
93
        return $field->readFromHubSpot($id);
94
    }
95
}
96