Completed
Push — master ( a20c7b...d885ca )
by Nate
02:36
created

ResolverTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 2
dl 0
loc 38
ccs 0
cts 21
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A resolveField() 0 16 3
A resolveElement() 0 8 2
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 yii\web\HttpException;
16
17
/**
18
 * @author Flipbox Factory <[email protected]>
19
 * @since 2.0.0
20
 */
21
trait ResolverTrait
22
{
23
    /**
24
     * @param string $field
25
     * @return FieldInterface
26
     * @throws HttpException
27
     */
28
    protected function resolveField(string $field): FieldInterface
29
    {
30
        $field = is_numeric($field) ?
31
            Craft::$app->getFields()->getFieldbyId($field) :
32
            Craft::$app->getFields()->getFieldByHandle($field);
33
34
        if (!$field instanceof FieldInterface) {
35
            throw new HttpException(400, sprintf(
36
                "Field must be an instance of '%s', '%s' given.",
37
                FieldInterface::class,
38
                get_class($field)
39
            ));
40
        }
41
42
        return $field;
43
    }
44
45
    /**
46
     * @param string $element
47
     * @return ElementInterface|Element
48
     * @throws HttpException
49
     */
50
    protected function resolveElement(string $element): ElementInterface
51
    {
52
        if (null === ($element = Craft::$app->getElements()->getElementById($element))) {
53
            throw new HttpException(400, 'Invalid element');
54
        };
55
56
        return $element;
57
    }
58
}
59