forked from tempestphp/tempest-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountStatement.php
More file actions
70 lines (59 loc) · 1.96 KB
/
CountStatement.php
File metadata and controls
70 lines (59 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
namespace Tempest\Database\QueryStatements;
use Tempest\Database\Builder\TableDefinition;
use Tempest\Database\Config\DatabaseDialect;
use Tempest\Database\QueryStatement;
use Tempest\Support\Arr\ImmutableArray;
use function Tempest\Support\arr;
final class CountStatement implements QueryStatement, HasWhereStatements
{
/**
* @param ImmutableArray<WhereStatement> $where
* @param ImmutableArray<JoinStatement> $joins
*/
public function __construct(
public readonly TableDefinition $table,
public ?string $column = null,
public ImmutableArray $where = new ImmutableArray(),
public bool $distinct = false,
public ImmutableArray $joins = new ImmutableArray(),
) {}
public function compile(DatabaseDialect $dialect): string
{
$countField = new FieldStatement(sprintf(
'COUNT(%s) AS %s',
$this->getCountArgument(),
$this->getKey(),
));
$query = arr([
sprintf('SELECT %s', $countField->compile($dialect)),
sprintf('FROM %s', $dialect->quoteIdentifier($this->table->name)),
]);
if ($this->joins->isNotEmpty()) {
foreach ($this->joins as $join) {
$query[] = $join->compile($dialect);
}
}
if ($this->where->isNotEmpty()) {
$query[] = 'WHERE ' . $this->where
->map(fn (QueryStatement $where) => $where->compile($dialect))
->filter(fn (string $compiled) => $compiled !== '')
->implode(' ');
}
return $query->implode(' ');
}
public function getCountArgument(): string
{
return $this->column === null || $this->column === '*'
? '*'
: sprintf(
'%s`%s`',
$this->distinct ? 'DISTINCT ' : '',
$this->column,
);
}
public function getKey(): string
{
return 'count';
}
}