/
CopyValueBehavior.php
113 lines (94 loc) · 2.87 KB
/
CopyValueBehavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace voskobovich\behaviors;
use yii\base\Behavior;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\db\ActiveRecord;
/**
* Class CopyValueBehavior
* @package voskobovich\behaviors
*/
class CopyValueBehavior extends Behavior
{
/**
* Attributes list
* Format:
* [
* 'meta_title' => 'name'
* or
* 'meta_title' => [
* 'attribute' => 'name', -- required
* 'clearTags' => true \ false, -- NOT required
* 'maxLength' => integer -- NOT required
* ]
* ]
* @var
*/
public $attributes;
/**
* Clear from html tags?
* @var bool
*/
public $clearTags = false;
/**
* Cut to a specified number of characters?
* @var bool|integer
*/
public $maxLength = false;
/**
* @var bool
*/
public $forceCopy = false;
/**
* Init
*/
public function init()
{
if ($this->attributes == null) {
throw new InvalidConfigException('Property "attributes" must be set');
}
parent::init();
}
/**
* Events
* @return array
*/
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'copyAttributes',
ActiveRecord::EVENT_BEFORE_UPDATE => 'copyAttributes',
];
}
/**
* Processing
* @throws Exception
*/
function copyAttributes()
{
$owner = $this->owner;
foreach ($this->attributes as $destination => $source) {
if (is_array($source)) {
if (empty($source['attribute'])) {
throw new Exception('Where to get the data? Set key "attribute"!');
}
$sourceAttribute = $source['attribute'];
$clearTags = (bool)isset($source['clearTags']) ? $source['clearTags'] : $this->clearTags;
$maxLength = isset($source['maxLength']) ? $source['maxLength'] : $this->maxLength;
if ((empty($owner->{$destination}) || $this->forceCopy) && !empty($owner->{$sourceAttribute})) {
$value = $owner->{$sourceAttribute};
$value = $clearTags ? strip_tags($value) : $value;
$value = is_integer($maxLength) ? mb_substr($value, 0, $maxLength) : $value;
$owner->{$destination} = $value;
}
} else {
if ((empty($owner->{$destination}) || $this->forceCopy) && !empty($owner->{$source})) {
$value = $owner->{$source};
$value = $this->clearTags ? strip_tags($value) : $value;
$value = is_integer($this->maxLength) ? mb_substr($value, 0, $this->maxLength) : $value;
$owner->{$destination} = $value;
}
}
}
}
}