Passed
Push — refactor/improve-static-analys... ( ed4ce4 )
by Bas
15:29
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
declare(strict_types=1);
4
5
namespace LaravelFreelancerNL\Aranguent\Query\Concerns;
6
7
use Illuminate\Support\Arr;
8
9
trait ConvertsIdToKey
10
{
11 161
    protected function convertIdToKey(array|string $data): array|string
12
    {
13 161
        if (is_string($data)) {
0 ignored issues
show
introduced by
The condition is_string($data) is always false.
Loading history...
14 120
            return $this->convertIdInString($data);
15
        }
16
17 137
        if (! Arr::isAssoc($data)) {
18
            return $data;
19
        }
20
21 137
        return $this->convertIdInArrayKeys($data);
22
    }
23
24 161
    protected function convertIdInString(string $data): string
25
    {
26 161
        return preg_replace(
27 161
            "/(?<![_a-zA-Z0-9_\s\.][^\.])id$/",
28 161
            '_key',
29
            $data,
30 161
            1
31
        );
32
    }
33
34
    /**
35
     * @param array<mixed> $data
36
     * @return array<mixed>
37
     */
38 137
    protected function convertIdInArrayKeys(array $data): array
39
    {
40 137
        foreach ($data as $key => $value) {
41 137
            $newKey = $this->convertIdInString($key);
42 137
            $data[$newKey] = $value;
43 137
            if ($key !== $newKey) {
44 53
                unset($data[$key]);
45
            }
46
        }
47
48 137
        return $data;
49
    }
50
}
51