Passed
Pull Request — master (#14)
by Tom
02:23
created

DefaultTransformer::buildQueryString()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
cc 4
nc 8
nop 1
1
<?php
2
3
namespace TomHart\Restful\Transformers;
4
5
use TomHart\Restful\Builder;
6
use TomHart\Restful\Concerns\Transformer;
7
8
class DefaultTransformer implements Transformer
9
{
10
11
    /**
12
     * Assemble the query string from the builder.
13
     * @param Builder $builder
14
     * @return mixed[]
15
     */
16
    public function buildQueryString(Builder $builder): array
17
    {
18
        $queryString = [];
19
20
        // Add the where clauses to the query string.
21
        foreach ($builder->getWheres() as $where) {
22
            $queryString = $this->addWhereClause($where, $queryString);
23
        }
24
25
        // Add the order.
26
        if ($builder->getOrder()) {
27
            $queryString[config('api-database.query_string_keys.order', 'order')] = $builder->getOrder();
28
        }
29
30
        // Add the limit.
31
        if ($builder->getLimit()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $builder->getLimit() of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
32
            $queryString[config('api-database.query_string_keys.limit', 'limit')] = $builder->getLimit();
33
        }
34
35
        return $queryString;
36
    }
37
38
    /**
39
     * Adds a where clause to the query string.
40
     * @param string[] $where
41
     * @param mixed[] $queryString
42
     * @return string[]
43
     */
44
    private function addWhereClause(array $where, array $queryString): array
45
    {
46
        switch ($where['type']) {
47
            default:
48
                $queryString[$where['column']] = $where['value'];
49
                break;
50
            case 'In':
51
                $queryString[$where['column']] = $where['values'];
52
                break;
53
        }
54
55
        return $queryString;
56
    }
57
}
58