Passed
Push — master ( 15cff9...9fe245 )
by Mr
02:02
created

EntityList::fromNative()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 16
ccs 11
cts 11
cp 1
rs 9.9332
cc 3
nc 2
nop 1
crap 3
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the daikon-cqrs/entity project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Daikon\Entity;
10
11
use Daikon\Interop\Assertion;
12
use Daikon\ValueObject\ValueObjectList;
13
14
/**
15
 * @type(Daikon\Entity\EntityInterface)
16
 */
17
class EntityList extends ValueObjectList
18
{
19
    /**
20
     * @param null|iterable $state
21
     * @return static
22
     */
23 10
    public static function fromNative($state): self
24
    {
25 10
        Assertion::nullOrIsTraversable($state, "State provided to '".static::class."' must be null or iterable.");
26
27 10
        $entities = [];
28 10
        $typeFactories = static::inferTypeFactories();
29 10
        if (!is_null($state)) {
30 10
            foreach ($state as $data) {
31 10
                Assertion::keyExists($data, EntityInterface::TYPE_KEY, 'Entity state is missing type key.');
32 10
                $entityType = $data[EntityInterface::TYPE_KEY];
33 10
                Assertion::isCallable($typeFactories[$entityType], "Entity factory for '$entityType' is not valid.");
34 10
                $entities[] = $typeFactories[$entityType]($data);
35
            }
36
        }
37
38 10
        return new static($entities);
39
    }
40
41
    /** @return static */
42
    public function diff(self $list): self
43
    {
44
        $differingEntities = [];
45
        foreach ($this as $pos => $entity) {
46
            /**
47
             * @psalm-suppress PossiblyNullArgument
48
             * @psalm-suppress ArgumentTypeCoercion
49
             */
50
            if (!$list->has($pos) || !(new EntityDiff)($entity, $list->get($pos))->isEmpty()) {
51
                $differingEntities[] = $entity;
52
            }
53
        }
54
        return new static($differingEntities);
55
    }
56
}
57