Passed
Push — master ( 010c64...640715 )
by Jesse
05:03
created

CollectionExtractor   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 40
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A extract() 0 26 3
A withAlternative() 0 3 1
A __construct() 0 3 1
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
use Stratadox\IdentityMap\MapsObjectsByIdentity as Map;
10
11
final class CollectionExtractor implements Extractor
12
{
13
    private $next;
14
15
    private function __construct(Extractor $next)
16
    {
17
        $this->next = $next;
18
    }
19
20
    public static function withAlternative(Extractor $next): Extractor
21
    {
22
        return new self($next);
23
    }
24
25
    public function extract(
26
        Name $name,
27
        $collection,
28
        Map $map,
29
        Visited $visited,
30
        Extractor $base = null
31
    ): array {
32
        if (!is_iterable($collection)) {
33
            return $this->next->extract($name, $collection, $map, $visited, $base);
34
        }
35
        assert($base !== null);
36
        $properties = [];
37
        $count = 0;
38
        foreach ($collection as $key => $value) {
39
            $properties[] = $base->extract(
40
                $name->forItem($collection, (string) $key),
41
                $value,
42
                $map,
43
                $visited,
44
                $base
45
            );
46
            $count++;
47
        }
48
        return these(
49
            [PropertyState::with((string) $name->toCount($collection), $count)],
50
            ...$properties
51
        );
52
    }
53
}
54