File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace LucasDotDev \DBQueriesCounter \Traits ;
4
+
5
+ use Illuminate \Support \Facades \DB ;
6
+
7
+ trait CountsQueries
8
+ {
9
+ protected bool $ hasDispatchedQueryCounter = false ;
10
+
11
+ protected bool $ isCountingQueries = false ;
12
+
13
+ protected int $ queryCount = 0 ;
14
+
15
+ public function whileCountingQueries (callable $ callback )
16
+ {
17
+ $ this ->startCountingQueries ();
18
+
19
+ $ result = $ callback ();
20
+
21
+ $ this ->stopCountingQueries ();
22
+
23
+ return $ result ;
24
+ }
25
+
26
+ public function startCountingQueries ()
27
+ {
28
+ if (!$ this ->hasDispatchedQueryCounter ) {
29
+ $ this ->dispatchQueryCounter ();
30
+ }
31
+
32
+ $ this ->isCountingQueries = true ;
33
+ $ this ->hasDispatchedQueryCounter = true ;
34
+ }
35
+
36
+ public function stopCountingQueries (): int
37
+ {
38
+ $ this ->isCountingQueries = false ;
39
+
40
+ return $ this ->getQueryCount ();
41
+ }
42
+
43
+ public function getQueryCount (): int
44
+ {
45
+ return $ this ->queryCount ;
46
+ }
47
+
48
+ public function assertDatabaseQueriesCount (int $ expectedCount )
49
+ {
50
+ return $ this ->assertEquals ($ expectedCount , $ this ->getQueryCount ());
51
+ }
52
+
53
+ private function dispatchQueryCounter ()
54
+ {
55
+ DB ::listen (function () {
56
+ if ($ this ->isCountingQueries ) {
57
+ $ this ->queryCount ++;
58
+ }
59
+ });
60
+ }
61
+ }
You can’t perform that action at this time.
0 commit comments