Passed
Push — master ( d25e4d...dba989 )
by Mr
06:54
created

EntityListTrait::fromNative()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17
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 17
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 Assert\Assert;
12
use Daikon\ValueObject\ValueObjectListTrait;
13
14
trait EntityListTrait
15
{
16
    use ValueObjectListTrait;
17
18
    /** @param null|array $state */
19 10
    public static function fromNative($state): self
20
    {
21 10
        Assert::that($state)->nullOr()->isTraversable(
22 10
            'State provided to '.static::class.' must be null or iterable'
23
        );
24
25 10
        $entities = [];
26 10
        $typeFactories = static::getTypeFactories();
27 10
        if (!is_null($state)) {
28 10
            foreach ($state as $data) {
29 10
                Assert::that($data)->keyExists(EntityInterface::TYPE_KEY, 'Entity state is missing type key.');
30 10
                $entityType = $data[EntityInterface::TYPE_KEY];
31 10
                $entities[] = call_user_func($typeFactories[$entityType], $data);
32
            }
33
        }
34
35 10
        return new static($entities);
36
    }
37
38
    public function diff(EntityListInterface $list): self
39
    {
40
        $differingEntities = [];
41
        foreach ($this as $pos => $entity) {
42
            /**
43
             * @psalm-suppress PossiblyNullArgument
44
             * @psalm-suppress ArgumentTypeCoercion
45
             */
46
            if (!$list->has($pos) || !(new EntityDiff)($entity, $list->get($pos))->isEmpty()) {
47
                $differingEntities[] = $entity;
48
            }
49
        }
50
        return new static($differingEntities);
51
    }
52
}
53