Passed
Push — next ( d224bd...9e651f )
by Bas
15:29 queued 11:57
created

ConvertsIdToKey   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 96.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
c 1
b 0
f 0
dl 0
loc 57
ccs 29
cts 30
cp 0.9667
rs 10
wmc 12

3 Methods

Rating   Name   Duplication   Size   Complexity  
A convertIdInString() 0 13 1
B convertIdToKey() 0 18 7
A convertIdInArrayKeys() 0 15 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LaravelFreelancerNL\Aranguent\Query\Concerns;
6
7
trait ConvertsIdToKey
8
{
9 225
    public function convertIdToKey(mixed $data): mixed
10
    {
11 225
        if (is_array($data) && array_is_list($data)) {
12 4
            foreach($data as $key => $value) {
13 4
                $data[$key] = $this->convertIdInString($value);
14
            }
15 4
            return $data;
16
        }
17
18 225
        if (!is_array($data) && !is_string($data)) {
19 1
            return $data;
20
        }
21
22 225
        if (is_string($data)) {
23 223
            return $this->convertIdInString($data);
24
        }
25
26 38
        return $this->convertIdInArrayKeys($data);
27
    }
28
29 225
    protected function convertIdInString(string $data): string
30
    {
31 225
        $replace = [
32 225
            "/^id$/" => '_key',
33 225
            "/\.id$/" => '._key'
34 225
        ];
35
        //TODO: we probably only want to replace .id if the prefix is a table or table alias.
36
37 225
        return (string) preg_replace(
38 225
            array_keys($replace),
39 225
            $replace,
40 225
            $data,
41 225
            1
42 225
        );
43
    }
44
45
    /**
46
     * @param  array<mixed>  $data
47
     * @return array<mixed>
48
     */
49 38
    protected function convertIdInArrayKeys(array $data): array
50
    {
51 38
        foreach ($data as $key => $value) {
52 38
            if (!is_string($key)) {
53
                continue;
54
            }
55 38
            $newKey = $this->convertIdInString($key);
56
57 38
            $data[$newKey] = $value;
58 38
            if ($key !== $newKey) {
59 21
                unset($data[$key]);
60
            }
61
        }
62
63 38
        return $data;
64
    }
65
}
66