forked from tempestphp/tempest-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFieldStatement.php
More file actions
77 lines (58 loc) · 1.95 KB
/
FieldStatement.php
File metadata and controls
77 lines (58 loc) · 1.95 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
71
72
73
74
75
76
77
<?php
namespace Tempest\Database\QueryStatements;
use Stringable;
use Tempest\Database\Config\DatabaseDialect;
use Tempest\Database\QueryStatement;
use function Tempest\Support\arr;
final class FieldStatement implements QueryStatement
{
private null|bool|string $alias = null;
private ?string $aliasPrefix = null;
public function __construct(
private readonly string|Stringable $field,
) {}
public function compile(DatabaseDialect $dialect): string
{
$parts = explode(' AS ', str_replace(' as ', ' AS ', $this->field));
$field = $parts[0];
if (count($parts) === 1) {
$alias = null;
$aliasPrefix = $this->aliasPrefix ? "{$this->aliasPrefix}." : '';
if ($this->alias === true) {
$alias = $aliasPrefix . str_replace('`', '', $field);
} elseif ($this->alias) {
$alias = $aliasPrefix . $this->alias;
}
} else {
$alias = trim($parts[1], '`" ');
}
$field = arr(explode('.', $field))
->map(fn (string $part) => trim($part, '`" '))
->map(
function (string $part) use ($dialect) {
if (str_contains($part, '(')) {
return $part;
}
if ($dialect === DatabaseDialect::SQLITE) {
return $part;
}
return $dialect->quoteIdentifier($part);
},
)
->implode('.');
if ($alias === null) {
return $field;
}
return sprintf('%s AS %s', $field, $dialect->quoteIdentifier($alias));
}
public function withAliasPrefix(?string $prefix = null): self
{
$this->aliasPrefix = $prefix;
return $this;
}
public function withAlias(bool|string $alias = true): self
{
$this->alias = $alias;
return $this;
}
}