Completed
Push — develop ( 009567...fb0a26 )
by Nate
08:31
created

ResolverTrait::resolveRecord()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 13
c 0
b 0
f 0
ccs 0
cts 10
cp 0
rs 9.8333
cc 3
nc 3
nop 3
crap 12
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-integration/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-integration/
7
 */
8
9
namespace flipbox\craft\integration\actions;
10
11
use Craft;
12
use craft\base\Element;
13
use craft\base\ElementInterface;
14
use flipbox\craft\integration\db\IntegrationAssociationQuery;
15
use flipbox\craft\integration\fields\Integrations;
16
use yii\web\HttpException;
17
18
/**
19
 * @author Flipbox Factory <[email protected]>
20
 * @since 2.0.0
21
 */
22
trait ResolverTrait
23
{
24
    /**
25
     * @param string $field
26
     * @return Integrations
27
     * @throws HttpException
28
     */
29
    protected function resolveField(string $field): Integrations
30
    {
31
        $field = is_numeric($field) ?
32
            Craft::$app->getFields()->getFieldbyId($field) :
33
            Craft::$app->getFields()->getFieldByHandle($field);
34
35
        /** @var Integrations $field */
36
37
        if (!$field instanceof Integrations) {
38
            throw new HttpException(400, sprintf(
39
                "Field must be an instance of '%s', '%s' given.",
40
                Integrations::class,
41
                get_class($field)
42
            ));
43
        }
44
45
        return $field;
46
    }
47
48
    /**
49
     * @param string $element
50
     * @return ElementInterface|Element
51
     * @throws HttpException
52
     */
53
    protected function resolveElement(string $element): ElementInterface
54
    {
55
        if (null === ($element = Craft::$app->getElements()->getElementById($element))) {
56
            throw new HttpException(400, 'Invalid element');
57
        };
58
59
        return $element;
60
    }
61
62
    /**
63
     * @param Integrations $field
64
     * @param ElementInterface $element
65
     * @param string $id
66
     * @return array|mixed|null|\yii\base\BaseObject
67
     * @throws HttpException
68
     */
69
    protected function resolveRecord(Integrations $field, ElementInterface $element, string $id)
70
    {
71
        /** @var IntegrationAssociationQuery $query */
72
        if (null === ($query = $element->getFieldValue($field->handle))) {
73
            throw new HttpException(400, 'Field is not associated to element');
74
        }
75
76
        if (null === ($record = $query->objectId($id)->one())) {
77
            throw new HttpException(400, 'Invalid value');
78
        };
79
80
        return $record;
81
    }
82
}
83