ResolverTrait   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 3
dl 0
loc 52
ccs 0
cts 28
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A resolveField() 0 16 3
A resolveElement() 0 8 2
A resolveSiteId() 0 8 3
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-element-lists/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-element-lists/
7
 */
8
9
namespace flipbox\craft\element\lists\actions;
10
11
use Craft;
12
use craft\base\Element;
13
use craft\base\ElementInterface;
14
use craft\base\FieldInterface;
15
use flipbox\craft\ember\helpers\SiteHelper;
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 FieldInterface
27
     * @throws HttpException
28
     */
29
    protected function resolveField(string $field): FieldInterface
30
    {
31
        $field = is_numeric($field) ?
32
            Craft::$app->getFields()->getFieldbyId($field) :
33
            Craft::$app->getFields()->getFieldByHandle($field);
34
35
        if (!$field instanceof FieldInterface) {
36
            throw new HttpException(400, sprintf(
37
                "Field must be an instance of '%s', '%s' given.",
38
                FieldInterface::class,
39
                get_class($field)
40
            ));
41
        }
42
43
        return $field;
44
    }
45
46
    /**
47
     * @param string $element
48
     * @return ElementInterface|Element
49
     * @throws HttpException
50
     */
51
    protected function resolveElement(string $element): ElementInterface
52
    {
53
        if (null === ($element = Craft::$app->getElements()->getElementById($element))) {
54
            throw new HttpException(400, 'Invalid element');
55
        };
56
57
        return $element;
58
    }
59
60
    /**
61
     * @param int|null $siteId
62
     * @return int|null
63
     * @throws \craft\errors\SiteNotFoundException
64
     */
65
    protected function resolveSiteId(int $siteId = null)
66
    {
67
        if (!Craft::$app->getIsMultiSite() || Craft::$app->getSites()->getCurrentSite()->primary) {
68
            return null;
69
        }
70
71
        return SiteHelper::ensureSiteId($siteId);
72
    }
73
}
74