|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace MichaelRubel\SqlFunctionRepository\Repositories; |
|
6
|
|
|
|
|
7
|
|
|
use Illuminate\Support\Facades\DB; |
|
8
|
|
|
use MichaelRubel\SqlFunctionRepository\SqlFunctionRepository; |
|
9
|
|
|
|
|
10
|
|
|
class PostgresqlFunctionRepository implements SqlFunctionRepository |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @param string|null $connection |
|
14
|
|
|
* @param string|null $select |
|
15
|
|
|
*/ |
|
16
|
1 |
|
public function __construct( |
|
17
|
|
|
public ?string $connection = null, |
|
18
|
|
|
public ?string $select = null, |
|
19
|
|
|
) { |
|
20
|
1 |
|
if (is_null($this->connection)) { |
|
21
|
1 |
|
$this->connection = config('sql-function-repository.connection', DB::getDefaultConnection()); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
1 |
|
if (is_null($this->select)) { |
|
25
|
1 |
|
$this->select = config('sql-function-repository.select', 'select * from '); |
|
26
|
|
|
} |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Execute the database function. |
|
31
|
|
|
* |
|
32
|
|
|
* @param string $name |
|
33
|
|
|
* @param array $parameters |
|
34
|
|
|
* @param string $as |
|
35
|
|
|
* |
|
36
|
|
|
* @return array |
|
37
|
|
|
*/ |
|
38
|
|
|
public function runDatabaseFunction(string $name, array $parameters = [], string $as = ''): array |
|
39
|
|
|
{ |
|
40
|
|
|
return DB::connection($this->connection)->select( |
|
41
|
|
|
$this->buildSqlFunction($name, $parameters, $as), |
|
42
|
|
|
$parameters |
|
43
|
|
|
); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* @param string $name |
|
48
|
|
|
* @param array $parameters |
|
49
|
|
|
* @param string $as |
|
50
|
|
|
* |
|
51
|
|
|
* @return string |
|
52
|
|
|
*/ |
|
53
|
|
|
protected function buildSqlFunction(string $name, array $parameters, string $as): string |
|
54
|
|
|
{ |
|
55
|
|
|
$prepareForBindings = collect($parameters)->implode(fn () => '?, '); |
|
|
|
|
|
|
56
|
|
|
|
|
57
|
|
|
$function = str($prepareForBindings) |
|
58
|
|
|
->replaceLast(', ', '') |
|
59
|
|
|
->start('(') |
|
60
|
|
|
->finish(')'); |
|
61
|
|
|
|
|
62
|
|
|
if (! empty($as)) { |
|
63
|
|
|
$function = $function->finish(' as ' . $as); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $this->select . $name . $function; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|