Passed
Push — dependabot/github_actions/depe... ( d1016c )
by
unknown
11:16
created

ConvertsIdToKey::convertIdToKey()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

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