1+ <?php
2+
3+ namespace SoftinkLab \LaravelKeyvalueStorage ;
4+
5+ use Illuminate \Database \Eloquent \Model ;
6+
7+ class KVOption extends Model
8+ {
9+ /**
10+ * Indicates if the model should be timestamped.
11+ *
12+ * @var bool
13+ */
14+ public $ timestamps = false ;
15+
16+ /**
17+ * The table associated with the model.
18+ *
19+ * @var string
20+ */
21+ protected $ table = 'kv_storage ' ;
22+
23+ /**
24+ * The attributes that are mass assignable.
25+ *
26+ * @var [type]
27+ */
28+ protected $ fillable = [
29+ 'key ' ,
30+ 'value ' ,
31+ 'comment ' ,
32+ ];
33+
34+ /**
35+ * Determine if the given key exists.
36+ *
37+ * @param string $key
38+ * @return bool
39+ */
40+ public function exists ($ key )
41+ {
42+ return $ this ->where ('key ' , $ key )->exists ();
43+ }
44+
45+ /**
46+ * Get the specified option by key.
47+ *
48+ * @param string $key
49+ * @return mixed
50+ */
51+ public function get ($ key )
52+ {
53+ if ($ option = $ this ->where ('key ' , $ key )->first ()) {
54+ return $ option ->value ;
55+ }
56+
57+ return null ;
58+ }
59+
60+ /**
61+ * Set a given option.
62+ *
63+ * @param string $key
64+ * @param string $comment
65+ * @param mixed $value
66+ * @return void
67+ */
68+ public function set ($ key , $ value , $ comment )
69+ {
70+ $ this ->updateOrCreate (
71+ ['key ' => $ key ],
72+ ['value ' => $ value , 'comment ' => $ comment ]
73+ );
74+ }
75+
76+ /**
77+ * Set given options of array.
78+ *
79+ * @param array $array
80+ * @return void
81+ */
82+ public function setArray ($ array )
83+ {
84+ foreach ($ array as $ option ) {
85+ // Check if comment is available.
86+ if (count ($ option ) == 2 ){
87+ $ this ->updateOrCreate (
88+ ['key ' => $ option [0 ]],
89+ ['value ' => $ option [1 ]]
90+ );
91+ }else {
92+ $ this ->updateOrCreate (
93+ ['key ' => $ option [0 ]],
94+ ['value ' => $ option [1 ], 'comment ' => $ option [2 ]]
95+ );
96+ }
97+ }
98+ }
99+
100+ /**
101+ * Delete the specified option.
102+ *
103+ * @param string $key
104+ * @return bool
105+ */
106+ public function remove ($ key )
107+ {
108+ return (bool ) $ this ->where ('key ' , $ key )->delete ();
109+ }
110+
111+ }
0 commit comments