ConvertsIdToKey   A
last analyzed

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 360
    public function convertIdToKey(mixed $data): mixed
10
    {
11 360
        if (is_array($data) && array_is_list($data)) {
12 6
            foreach ($data as $key => $value) {
13 6
                $data[$key] = $this->convertIdInString($value);
14
            }
15 6
            return $data;
16
        }
17
18 360
        if (!is_array($data) && !is_string($data)) {
19 1
            return $data;
20
        }
21
22 360
        if (is_string($data)) {
23 357
            return $this->convertIdInString($data);
24
        }
25
26 116
        return $this->convertIdInArrayKeys($data);
27
    }
28
29 360
    protected function convertIdInString(string $data): string
30
    {
31 360
        $replace = [
32 360
            "/^id$/" => '_key',
33 360
            "/\.id$/" => '._key',
34 360
        ];
35
        //TODO: we probably only want to replace .id if the prefix is a table or table alias.
36
37 360
        return (string) preg_replace(
38 360
            array_keys($replace),
39 360
            $replace,
40 360
            $data,
41 360
            1,
42 360
        );
43
    }
44
45
    /**
46
     * @param  array<mixed>  $data
47
     * @return array<mixed>
48
     */
49 116
    protected function convertIdInArrayKeys(array $data): array
50
    {
51 116
        foreach ($data as $key => $value) {
52 116
            if (!is_string($key)) {
53
                continue;
54
            }
55 116
            $newKey = $this->convertIdInString($key);
56
57 116
            $data[$newKey] = $value;
58 116
            if ($key !== $newKey) {
59 81
                unset($data[$key]);
60
            }
61
        }
62
63 116
        return $data;
64
    }
65
}
66