Passed
Push — master ( f8f76e...e5015c )
by Bas
12:29
created

FunctionExpression::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 3
b 0
f 0
nc 2
nop 2
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
1
<?php
2
3
namespace LaravelFreelancerNL\FluentAQL\Expressions;
4
5
use LaravelFreelancerNL\FluentAQL\Traits\NormalizesFunctions;
6
use LaravelFreelancerNL\FluentAQL\QueryBuilder;
7
8
/**
9
 * AQL literal expression.
10
 */
11
class FunctionExpression extends Expression implements ExpressionInterface
12
{
13
    use NormalizesFunctions;
14
15
    protected string $functionName;
16
17
    /**
18
     * @var array<mixed>
19
     */
20
    protected $parameters = [];
21
22
    /**
23
     * FunctionExpression constructor.
24
     *
25
     * @param string $functionName
26
     * @param mixed $parameters
27
     */
28 37
    public function __construct(string $functionName, mixed $parameters = [])
29
    {
30 37
        $this->functionName = $functionName;
31
32 37
        if (! is_array($parameters)) {
33 7
            $parameters = [$parameters];
34
        }
35
36 37
        $this->parameters = $parameters;
37 37
    }
38
39 37
    public function compile(QueryBuilder $queryBuilder): string
40
    {
41 37
        if (! empty($this->parameters)) {
42 36
            $normalizeFunction = $this->getNormalizeFunctionName();
43 36
            $this->$normalizeFunction($queryBuilder);
44
        }
45 37
        $output = strtoupper($this->functionName) . '(';
46 37
        $output .= implode(', ', $this->compileParameters($this->parameters, $queryBuilder));
47 37
        $output .= ')';
48
49 37
        return $output;
50
    }
51
52 37
    protected function compileParameters(?array $parameters, QueryBuilder $queryBuilder): array
53
    {
54 37
        $compiledParameters = [];
55 37
        foreach ($parameters as $key => $parameter) {
56 36
            if ($key === 'predicates') {
57 10
                $compiledParameters[] = $queryBuilder->compilePredicates($parameter);
58
59 10
                continue;
60
            }
61 36
            $compiledParameters[] = $parameter->compile($queryBuilder);
62
        }
63
64 37
        return $compiledParameters;
65
    }
66
67
    /**
68
     * Generate the name of the normalize function for this AQL function.
69
     */
70 36
    protected function getNormalizeFunctionName(): string
71
    {
72 36
        $value = ucwords(str_replace('_', ' ', strtolower($this->functionName)));
73
74 36
        return 'normalize' . str_replace(' ', '', $value);
75
    }
76
}
77