-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHstoreBehavior.php
76 lines (62 loc) · 1.89 KB
/
HstoreBehavior.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
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace vaseninm\behaviors;
use yii\base\InvalidCallException;
use yii\behaviors\AttributeBehavior;
use yii\db\BaseActiveRecord;
class HstoreBehavior extends AttributeBehavior
{
public $attribute = [];
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if (empty($this->attributes)) {
$this->attributes = [
BaseActiveRecord::EVENT_AFTER_VALIDATE => [$this->attribute],
BaseActiveRecord::EVENT_AFTER_FIND => [$this->attribute],
];
}
}
/**
* @inheritdoc
*/
protected function getValue($event)
{
switch ($event->name) {
case BaseActiveRecord::EVENT_AFTER_VALIDATE:
return $this->hstoreEncode($this->owner->{$this->attribute});
case BaseActiveRecord::EVENT_AFTER_FIND:
return $this->hstoreDecode($this->owner->{$this->attribute});
default:
throw new InvalidCallException('Invalid get value call');
}
}
protected function hstoreEncode($array) {
if (empty($array))
return null;
$string = '';
foreach ($array as $k => $v) {
if ($v !== null)
$string .= "\"{$this->quoteValue($k)}\"=>\"{$this->quoteValue($v)}\",";
else
$string .= "\"{$this->quoteValue($k)}\"=>NULL,";
}
return $string;
}
protected function hstoreDecode($raw) {
$raw = preg_replace('/([$])/u', "\\\\$1", $raw);
$unescapedHStore = array();
eval('$unescapedHStore = array(' . $raw . ');');
return $unescapedHStore;
}
protected function quoteValue($string) {
return addslashes($string);
}
}