Passed
Push — experiment/id-key-conversion ( cbc737...bb5ee1 )
by Bas
03:11
created

ConvertsIdToKey::convertIdInString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace LaravelFreelancerNL\Aranguent\Query\Concerns;
4
5
use Illuminate\Support\Arr;
6
7
trait ConvertsIdToKey
8
{
9 161
    protected function convertIdToKey(array|string $data): array|string
10
    {
11 161
        if (is_string($data)) {
0 ignored issues
show
introduced by
The condition is_string($data) is always false.
Loading history...
12 120
            return $this->convertIdInString($data);
13
        }
14
15 137
        if (! Arr::isAssoc($data)) {
16
            return $data;
17
        }
18
19 137
        return $this->convertIdInArrayKeys($data);
20
    }
21
22 161
    protected function convertIdInString(string $data): string
23
    {
24 161
        return preg_replace(
25 161
            "/(?<![_a-zA-Z0-9_\s\.][^\.])id$/",
26 161
            '_key',
27
            $data,
28 161
            1
29
        );
30
    }
31
32
    /**
33
     * @param array<mixed> $data
34
     * @return array<mixed>
35
     */
36 137
    protected function convertIdInArrayKeys(array $data): array
37
    {
38 137
        foreach ($data as $key => $value) {
39 137
            $newKey = $this->convertIdInString($key);
40 137
            $data[$newKey] = $value;
41 137
            if ($key !== $newKey) {
42 53
                unset($data[$key]);
43
            }
44
        }
45
46 137
        return $data;
47
    }
48
}
49