Skip to content

Commit 45ae3f2

Browse files
committed
Create CountsQueries trait
1 parent 52d472d commit 45ae3f2

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/Traits/CountsQueries.php

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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+
}

0 commit comments

Comments
 (0)