-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImplodeArrayBehavior.php
85 lines (74 loc) · 1.97 KB
/
ImplodeArrayBehavior.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
<?php
namespace lgxenos\yii2\admMixedGallery;
use yii\base\ErrorException;
use yii\db\ActiveRecord;
use yii\base\Behavior;
/**
* Бихевиор, который работает с массивом в поле, которое изначально представлено строкой с разделителями
*
* Class ImplodeArrayBehavior
* @package common\behaviors
*
*/
class ImplodeArrayBehavior extends Behavior {
/** @var string чем склеиваем */
public $glue = ';';
/** @var string поле, с которым идет работа */
public $field;
/**
* @return array
* @throws ErrorException
*/
public function events() {
if (!$this->field) {
throw new ErrorException('Не указано поле для обработки');
}
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'implodeField',
ActiveRecord::EVENT_BEFORE_UPDATE => 'implodeField',
ActiveRecord::EVENT_AFTER_FIND => 'explodeField',
];
}
/**
* @param $event
*/
public function implodeField($event) {
if(is_array($this->owner->{$this->field})) {
$itemsRaw = $this->owner->{$this->field};
$items = [];
// перебираем все элементы, выкидываем лишние пустые
foreach ($itemsRaw as $item){
$item = trim($item);
if($item != ''){
$items[] = $item;
}
}
$this->owner->{$this->field} = implode($this->glue, $items);
}
}
/**
* @param $event
*/
public function explodeField($event) {
if(trim($this->owner->{$this->field})==''){
$this->owner->{$this->field} = [];
return;
}
$this->owner->{$this->field} = explode($this->glue, $this->owner->{$this->field});
if(!is_array($this->owner->{$this->field})){
$this->owner->{$this->field} = [];
}
}
/**
* @param $field
* @param string $glue
*
* @return string
*/
public static function printFieldAsString($field, $glue = ','){
if(is_array($field)){
return implode($glue, $field);
}
return $field;
}
}