Passed
Push — master ( f2dea1...58a092 )
by Nate
04:47
created

Element::transferToRecord()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
nc 2
cc 2
eloc 4
nop 3
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipbox/spark/blob/master/LICENSE
6
 * @link       https://github.com/flipbox/spark
7
 */
8
9
namespace flipbox\spark\services\traits;
10
11
use craft\base\Element as BaseElement;
12
use craft\base\ElementInterface;
13
use flipbox\spark\records\Record;
14
15
/**
16
 * @author Flipbox Factory <[email protected]>
17
 * @since 1.1.0
18
 */
19
trait Element
20
{
21
22
    use Object;
23
24
    /*******************************************
25
     * ELEMENT -to- RECORD
26
     *******************************************/
27
28
    /**
29
     * @param ElementInterface $element
30
     * @param Record $record
31
     * @param bool $mirrorScenario
32
     */
33
    public function transferToRecord(ElementInterface $element, Record $record, $mirrorScenario = true)
34
    {
35
36
        /** @var $element BaseElement */
37
38
        if ($mirrorScenario === true) {
39
40
            // Mirror scenarios
41
            $record->setScenario($element->getScenario());
42
43
        }
44
45
        // Transfer attributes
46
        $record->setAttributes($element->toArray());
47
48
    }
49
50
    /**
51
     * @param ElementInterface $element
52
     * @param bool $mirrorScenario
53
     * @return Record
54
     */
55
    public function toRecord(ElementInterface $element, $mirrorScenario = true)
56
    {
57
58
        if ($id = $element->getId()) {
59
60
            $record = $this->findRecordByCondition(
61
                ['id' => $id]
62
            );
63
64
        }
65
66
        if (empty($record)) {
67
68
            // Create new record
69
            $record = $this->createRecord();
70
71
        }
72
73
        // Populate the record attributes
74
        $this->transferToRecord($element, $record, $mirrorScenario);
75
76
        return $record;
77
78
    }
79
80
}
81