PostgresqlFunctionRepository   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 26.32%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
eloc 16
c 3
b 0
f 1
dl 0
loc 57
ccs 5
cts 19
cp 0.2632
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A buildSqlFunction() 0 14 2
A runDatabaseFunction() 0 5 1
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