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

FunctionExpression   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 24
c 3
b 0
f 0
dl 0
loc 64
ccs 25
cts 25
cp 1
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A compile() 0 11 2
A compileParameters() 0 13 3
A __construct() 0 9 2
A getNormalizeFunctionName() 0 5 1
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