Element::toRecord()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 13
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 4
nop 2
crap 12
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
            // Mirror scenarios
40
            $record->setScenario($element->getScenario());
41
        }
42
43
        // Transfer attributes
44
        $record->setAttributes($element->toArray());
45
    }
46
47
    /**
48
     * @param ElementInterface $element
49
     * @param bool $mirrorScenario
50
     * @return Record
51
     */
52
    public function toRecord(ElementInterface $element, $mirrorScenario = true)
53
    {
54
55
        if ($id = $element->getId()) {
56
            $record = $this->findRecordByCondition(
57
                ['id' => $id]
58
            );
59
        }
60
61
        if (empty($record)) {
62
            // Create new record
63
            $record = $this->createRecord();
64
        }
65
66
        // Populate the record attributes
67
        $this->transferToRecord($element, $record, $mirrorScenario);
68
69
        return $record;
70
    }
71
}
72