Passed
Push — main ( e293a6...eec931 )
by Michael
04:53 queued 01:34
created

PostgresqlFunctionRepository   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 38.46%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 12
c 3
b 0
f 0
dl 0
loc 47
ccs 5
cts 13
cp 0.3846
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A runDatabaseFunction() 0 5 1
A __construct() 0 10 3
A buildSqlFunction() 0 6 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
     *
35
     * @return array
36
     */
37
    public function runDatabaseFunction(string $name, array $parameters = []): array
38
    {
39
        return DB::connection($this->connection)->select(
40
            $this->buildSqlFunction($name, $parameters),
41
            $parameters
42
        );
43
    }
44
45
    /**
46
     * @param string $name
47
     * @param array  $parameters
48
     *
49
     * @return string
50
     */
51
    protected function buildSqlFunction(string $name, array $parameters): string
52
    {
53
        return $this->select . $name . str(implode('?, ', $parameters))
54
                ->replaceLast(', ', '')
55
                ->start('(')
56
                ->finish(')');
57
    }
58
}
59