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

ConvertsIdToKey::convertIdToKey()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 9
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 18
ccs 10
cts 10
cp 1
crap 7
rs 8.8333
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