5
5
use yii \permission \models \CasbinRule ;
6
6
use Casbin \Model \Model ;
7
7
use Casbin \Persist \Adapter as AdapterContract ;
8
+ use Casbin \Persist \BatchAdapter as BatchAdapterContract ;
8
9
use Casbin \Persist \AdapterHelper ;
9
10
10
11
/**
11
12
* DatabaseAdapter.
12
13
*
13
14
14
15
*/
15
- class Adapter implements AdapterContract
16
+ class Adapter implements AdapterContract, BatchAdapterContract
16
17
{
17
18
use AdapterHelper;
18
19
@@ -85,6 +86,37 @@ public function addPolicy(string $sec, string $ptype, array $rule): void
85
86
$ this ->savePolicyLine ($ ptype , $ rule );
86
87
}
87
88
89
+ /**
90
+ * Adds a policy rules to the storage.
91
+ * This is part of the Auto-Save feature.
92
+ *
93
+ * @param string $sec
94
+ * @param string $ptype
95
+ * @param string[][] $rules
96
+ */
97
+ public function addPolicies (string $ sec , string $ ptype , array $ rules ): void
98
+ {
99
+ $ rows = [];
100
+ $ columns = array_keys ($ rules [0 ]);
101
+ array_walk ($ columns , function (&$ item ) {
102
+ $ item = 'v ' . strval ($ item );
103
+ });
104
+ array_unshift ($ columns , 'ptype ' );
105
+
106
+ foreach ($ rules as $ rule ) {
107
+ $ temp ['`ptype` ' ] = $ ptype ;
108
+ foreach ($ rule as $ key => $ value ) {
109
+ $ temp ['`v ' . strval ($ key ) . '` ' ] = $ value ;
110
+ }
111
+ $ rows [] = $ temp ;
112
+ $ temp = [];
113
+ }
114
+
115
+ $ command = $ this ->casbinRule ->getDb ()->createCommand ();
116
+ $ tableName = $ this ->casbinRule ->tableName ();
117
+ $ command ->batchInsert ($ tableName , $ columns , $ rows )->execute ();
118
+ }
119
+
88
120
/**
89
121
* This is part of the Auto-Save feature.
90
122
*
@@ -104,6 +136,27 @@ public function removePolicy(string $sec, string $ptype, array $rule): void
104
136
$ this ->casbinRule ->deleteAll ($ where );
105
137
}
106
138
139
+ /**
140
+ * Removes policy rules from the storage.
141
+ * This is part of the Auto-Save feature.
142
+ *
143
+ * @param string $sec
144
+ * @param string $ptype
145
+ * @param string[][] $rules
146
+ */
147
+ public function removePolicies (string $ sec , string $ ptype , array $ rules ): void
148
+ {
149
+ $ transaction = $ this ->casbinRule ->getDb ()->beginTransaction ();
150
+ try {
151
+ foreach ($ rules as $ rule ) {
152
+ $ this ->removePolicy ($ sec , $ ptype , $ rule );
153
+ }
154
+ $ transaction ->commit ();
155
+ } catch (\Exception $ e ) {
156
+ $ transaction ->rollBack ();
157
+ }
158
+ }
159
+
107
160
/**
108
161
* RemoveFilteredPolicy removes policy rules that match the filter from the storage.
109
162
* This is part of the Auto-Save feature.
0 commit comments