runDatabaseFunction()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
rs 10
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 () => '?, ');
0 ignored issues
show
Bug introduced by
$parameters of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

55
        $prepareForBindings = collect(/** @scrutinizer ignore-type */ $parameters)->implode(fn () => '?, ');
Loading history...
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