PropertyHelper   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 25
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 1 1
A mapProperties() 0 20 3
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
7
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
8
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
9
 *
10
 * Copyright (c) 2024 Mykhailo Shtanko [email protected]
11
 *
12
 * For the full copyright and license information, please view the LICENSE.MD
13
 * file that was distributed with this source code.
14
 */
15
16
namespace FRZB\Component\DependencyInjection\Helper;
17
18
use Fp\Collections\ArrayList;
19
use JetBrains\PhpStorm\Immutable;
20
21
/** @internal */
22
#[Immutable]
23
final class PropertyHelper
24
{
25
    private function __construct() {}
26
27
    public static function mapProperties(object $target, array $excludeNames = [], bool $excludeEmpty = true): array
28
    {
29
        try {
30
            $rClass = new \ReflectionClass($target);
31
        } catch (\Throwable) {
32
            return [];
33
        }
34
35
        return ArrayList::collect($rClass->getProperties())
36
            ->filter(
37
                static fn (\ReflectionProperty $property) => $excludeEmpty
38
                    ? !empty($property->getValue($target))
39
                    : null !== $property->getValue($target)
40
            )
41
            ->filter(static fn (\ReflectionProperty $property) => !\in_array($property->getName(), $excludeNames, true))
42
            ->map(static fn (\ReflectionProperty $property) => match (true) {
43
                \is_array($property->getValue($target)) => $property->getValue($target),
44
                default => [$property->getName() => $property->getValue($target)],
45
            })
46
            ->toMergedArray()
47
        ;
48
    }
49
}
50