PopulateTrait   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 1
dl 0
loc 47
ccs 0
cts 23
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
validBodyParams() 0 1 ?
A populate() 0 13 1
A attributeValuesFromBody() 0 16 4
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember/
7
 */
8
9
namespace flipbox\craft\ember\actions;
10
11
use Craft;
12
use yii\base\BaseObject;
13
14
/**
15
 * @author Flipbox Factory <[email protected]>
16
 * @since 2.0.0
17
 */
18
trait PopulateTrait
19
{
20
    /**
21
     * These are the default body params that we're accepting.  You can lock down specific fact attributes this way.
22
     *
23
     * @return array
24
     */
25
    abstract protected function validBodyParams(): array;
26
27
    /**
28
     * @param BaseObject $object
29
     * @return BaseObject
30
     */
31
    protected function populate(BaseObject $object): BaseObject
32
    {
33
        // Valid attribute values
34
        $attributes = $this->attributeValuesFromBody();
35
36
        /** @var BaseObject $object */
37
        $object = Craft::configure(
38
            $object,
39
            $attributes
40
        );
41
42
        return $object;
43
    }
44
45
    /**
46
     * @return array
47
     */
48
    protected function attributeValuesFromBody(): array
49
    {
50
        $request = Craft::$app->getRequest();
51
52
        $attributes = [];
53
        foreach ($this->validBodyParams() as $bodyParam => $attribute) {
54
            if (is_numeric($bodyParam)) {
55
                $bodyParam = $attribute;
56
            }
57
            if (($value = $request->getBodyParam($bodyParam)) !== null) {
58
                $attributes[$attribute] = $value;
59
            }
60
        }
61
62
        return $attributes;
63
    }
64
}
65