Completed
Push — devops/catch-breaking-changes-... ( 88c9a6 )
by Bas
28s queued 18s
created

ConvertsIdToKey   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 88.24%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 18
c 1
b 0
f 0
dl 0
loc 43
ccs 15
cts 17
cp 0.8824
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A convertIdToKey() 0 11 3
A convertIdInArrayKeys() 0 14 4
A convertIdInString() 0 7 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 129
    protected function convertIdToKey(array|string $data): array|string
12
    {
13 129
        if (is_string($data)) {
0 ignored issues
show
introduced by
The condition is_string($data) is always false.
Loading history...
14 126
            return $this->convertIdInString($data);
15
        }
16
17 22
        if (! Arr::isAssoc($data)) {
18
            return $data;
19
        }
20
21 22
        return $this->convertIdInArrayKeys($data);
22
    }
23
24 129
    protected function convertIdInString(string $data): string
25
    {
26 129
        return preg_replace(
27
            "/(?<![_a-zA-Z0-9_\s\.][^\.])id$/",
28
            '_key',
29
            $data,
30
            1
31
        );
32
    }
33
34
    /**
35
     * @param array<mixed> $data
36
     * @return array<mixed>
37
     */
38 22
    protected function convertIdInArrayKeys(array $data): array
39
    {
40 22
        foreach ($data as $key => $value) {
41 22
            if (! is_string($key)) {
42
                continue;
43
            }
44 22
            $newKey = $this->convertIdInString($key);
45 22
            $data[$newKey] = $value;
46 22
            if ($key !== $newKey) {
47 17
                unset($data[$key]);
48
            }
49
        }
50
51 22
        return $data;
52
    }
53
}
54