DataRemover::removeIndexed()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 36
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 18
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 36
rs 9.0444
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Communibase\DataBag;
6
7
final class DataRemover
8
{
9
    /**
10
     * @var array<string,array>
11
     */
12
    private $data;
13
14
    /**
15
     * @param array<string,mixed> $data
16
     */
17
    public function removeByPath(array &$data, string $path): void
18
    {
19
        $this->data = &$data;
20
21
        [$entityType, $path] = explode('.', $path, 2);
22
23
        // Direct property
24
        if (strpos($path, '.') === false) {
25
            if (!isset($this->data[$entityType][$path])) {
26
                return;
27
            }
28
            $data[$entityType][$path] = null;
29
            return;
30
        }
31
32
        $this->removeIndexed($path, $entityType);
33
    }
34
35
    private function removeIndexed(string $path, string $entityType): void
36
    {
37
        [$path, $index] = explode('.', $path);
38
39
        // Target doesn't exist, nothing to remove
40
        if (empty($this->data[$entityType][$path])) {
41
            return;
42
        }
43
44
        if (is_numeric($index)) {
45
            $index = (int)$index;
46
            // Remove all (higher) values to prevent a new value after re-indexing
47
            if ($index === 0) {
48
                $this->data[$entityType][$path] = null;
49
                return;
50
            }
51
            $this->data[$entityType][$path] = \array_slice($this->data[$entityType][$path], 0, $index);
52
            return;
53
        }
54
55
        // Filter out all nodes of the specified type
56
        $this->data[$entityType][$path] = array_filter(
57
            $this->data[$entityType][$path],
58
            static function ($node) use ($index) {
59
                return empty($node['type']) || $node['type'] !== $index;
60
            }
61
        );
62
63
        // If we end up with an empty array make it NULL
64
        if (empty($this->data[$entityType][$path])) {
65
            $this->data[$entityType][$path] = null;
66
            return;
67
        }
68
69
        // Re-index
70
        $this->data[$entityType][$path] = array_values($this->data[$entityType][$path]);
71
    }
72
}
73