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\behaviors; |
10
|
|
|
|
11
|
|
|
use craft\base\Element; |
12
|
|
|
use craft\base\ElementInterface; |
13
|
|
|
use flipbox\spark\records\Record; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @package flipbox\spark\behaviors |
17
|
|
|
* @author Flipbox Factory <[email protected]> |
18
|
|
|
* @since 1.0.0 |
19
|
|
|
*/ |
20
|
|
View Code Duplication |
class ElementRecordAccessor extends ObjectRecordAccessor |
|
|
|
|
21
|
|
|
{ |
22
|
|
|
|
23
|
|
|
/******************************************* |
24
|
|
|
* ELEMENT -to- RECORD |
25
|
|
|
*******************************************/ |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param ElementInterface $element |
29
|
|
|
* @param Record $record |
30
|
|
|
* @param bool $mirrorScenario |
31
|
|
|
*/ |
32
|
|
|
public function transferToRecord(ElementInterface $element, Record $record, $mirrorScenario = true) |
33
|
|
|
{ |
34
|
|
|
|
35
|
|
|
/** @var $element Element */ |
36
|
|
|
|
37
|
|
|
if ($mirrorScenario === true) { |
38
|
|
|
|
39
|
|
|
// Mirror scenarios |
40
|
|
|
$record->setScenario($element->getScenario()); |
41
|
|
|
|
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// Transfer attributes |
45
|
|
|
$record->setAttributes($element->toArray()); |
46
|
|
|
|
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param ElementInterface $element |
51
|
|
|
* @param bool $mirrorScenario |
52
|
|
|
* @return Record |
53
|
|
|
*/ |
54
|
|
|
public function toRecord(ElementInterface $element, $mirrorScenario = true) |
55
|
|
|
{ |
56
|
|
|
|
57
|
|
|
if ($id = $element->getId()) { |
58
|
|
|
|
59
|
|
|
$record = $this->findRecordByCondition( |
60
|
|
|
['id' => $id] |
61
|
|
|
); |
62
|
|
|
|
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
if (empty($record)) { |
66
|
|
|
|
67
|
|
|
// Create new record |
68
|
|
|
$record = $this->createRecord(); |
69
|
|
|
|
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
// Populate the record attributes |
73
|
|
|
$this->transferToRecord($element, $record, $mirrorScenario); |
74
|
|
|
|
75
|
|
|
return $record; |
76
|
|
|
|
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
} |
80
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.