@@ -153,18 +153,7 @@ public function drop()
153
153
154
154
public function find (Criteria |array |null $ criteria = null , ?int $ limit = null ): array
155
155
{
156
- if (!$ criteria ) {
157
- $ criteria = Criteria::allIterator ();
158
- } elseif (is_array ($ criteria )) {
159
- $ index = $ this ->castIndex (array_keys ($ criteria ));
160
- $ criteria = Criteria::eqIterator ()
161
- ->andIndex ($ index ['iid ' ])
162
- ->andKey ($ this ->getKey ($ criteria , $ index ));
163
- }
164
-
165
- if ($ limit ) {
166
- $ criteria = $ criteria ->andLimit ($ limit );
167
- }
156
+ $ criteria = $ this ->getCriteria ($ criteria , $ limit );
168
157
169
158
$ item = null ;
170
159
if ($ this ->cache ) {
@@ -195,6 +184,15 @@ public function findOne(Criteria|array|null $criteria = null)
195
184
196
185
public function findOrCreate (array $ query , ?array $ data = null )
197
186
{
187
+ if ($ this ->cache ) {
188
+ $ instance = $ this ->findOne ($ query );
189
+ if ($ instance ) {
190
+ return $ instance ;
191
+ }
192
+ $ criteria = $ this ->getCriteria ($ query , 1 );
193
+ $ this ->cache ->deleteItem (md5 (serialize ($ criteria )));
194
+ }
195
+
198
196
if ($ data == null ) {
199
197
$ data = $ query ;
200
198
} else {
@@ -230,14 +228,23 @@ public function findOrCreate(array $query, ?array $data = null)
230
228
'id_key ' => array_search ('id ' , $ this ->fields ) + 1
231
229
]
232
230
);
231
+
233
232
if (!$ present ) {
234
233
$ this ->mapper ->middleware ->register (
235
234
new InsertRequest ($ this ->id , $ tuple ),
236
235
new Response ([], [Keys::DATA => [$ tuple ]]),
237
236
);
238
237
}
239
238
240
- return $ this ->getInstance ($ tuple );
239
+ $ instance = $ this ->getInstance ($ tuple );
240
+ if ($ this ->cache ) {
241
+ $ criteria = $ this ->getCriteria ($ query , 1 );
242
+ $ item = $ this ->cache ->getItem (md5 (serialize ($ criteria )));
243
+ $ item ->set ([$ instance ]);
244
+ $ this ->cache ->save ($ item );
245
+ }
246
+
247
+ return $ instance ;
241
248
}
242
249
243
250
public function findOrFail (Criteria |array |null $ criteria = null )
@@ -250,6 +257,24 @@ public function findOrFail(Criteria|array|null $criteria = null)
250
257
throw new Exception ("Not found " );
251
258
}
252
259
260
+ public function getCriteria (Criteria |array |null $ criteria = null , ?int $ limit = null ): Criteria
261
+ {
262
+ if (!$ criteria ) {
263
+ $ criteria = Criteria::allIterator ();
264
+ } elseif (is_array ($ criteria )) {
265
+ $ index = $ this ->castIndex (array_keys ($ criteria ));
266
+ $ criteria = Criteria::eqIterator ()
267
+ ->andIndex ($ index ['iid ' ])
268
+ ->andKey ($ this ->getKey ($ criteria , $ index ));
269
+ }
270
+
271
+ if ($ limit ) {
272
+ $ criteria = $ criteria ->andLimit ($ limit );
273
+ }
274
+
275
+ return $ criteria ;
276
+ }
277
+
253
278
public function getFieldFormat (string $ name ): array
254
279
{
255
280
foreach ($ this ->format as $ field ) {
0 commit comments