CollectionExtractor::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\EntityState\Internal;
4
5
use function array_merge as these;
6
use function assert;
7
use function is_iterable;
8
use Stratadox\EntityState\PropertyState;
9
10
final class CollectionExtractor implements Extractor
11
{
12
    private $next;
13
14
    private function __construct(Extractor $next)
15
    {
16
        $this->next = $next;
17
    }
18
19
    public static function withAlternative(Extractor $next): Extractor
20
    {
21
        return new self($next);
22
    }
23
24
    public function extract(
25
        ExtractionRequest $request,
26
        Extractor $base = null
27
    ): array {
28
        if (!is_iterable($request->value())) {
29
            return $this->next->extract($request, $base);
30
        }
31
        assert($base !== null);
32
        $properties = [];
33
        $count = 0;
34
        foreach ($request->value() as $key => $value) {
35
            $properties[] = $base->extract($request->forCollectionItem(
36
                $request->value(),
37
                (string) $key,
38
                $value
39
            ));
40
            $count++;
41
        }
42
        return these(
43
            [PropertyState::with((string) $request->nameForCounting(), $count)],
44
            ...$properties
45
        );
46
    }
47
}
48