Passed
Push — master ( f27e95...6a73f4 )
by Chema
08:35 queued 11s
created

TransactionMessage::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EdifactParser;
6
7
use EdifactParser\Segments\SegmentInterface;
8
use EdifactParser\Segments\UNHMessageHeader;
9
10
/** @psalm-immutable */
11
final class TransactionMessage
12
{
13
    /** @var array<string, array<string,SegmentInterface>> */
14
    private array $groupedSegments;
15
16
    /**
17
     * A message starts with the "UNHMessageHeader" segment until another
18
     * "UNHMessageHeader" segment appears, then starts another segment and so on.
19
     *
20
     * @psalm-pure
21
     * @psalm-return list<TransactionMessage>
22
     */
23 6
    public static function groupSegmentsByMessage(SegmentInterface...$segments): array
24
    {
25 6
        $messages = [];
26 6
        $groupedSegments = [];
27
28 6
        foreach ($segments as $segment) {
29 6
            if ($segment instanceof UNHMessageHeader && $groupedSegments) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $groupedSegments of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
30 2
                $messages[] = self::groupSegmentsByName(...$groupedSegments);
31 2
                $groupedSegments = [];
32
            }
33 6
            $groupedSegments[] = $segment;
34
        }
35
36 6
        $messages[] = self::groupSegmentsByName(...$groupedSegments);
37
38 6
        return $messages;
39
    }
40
41
    /** @param array<string, array<string,SegmentInterface>> $groupedSegments */
42 6
    public function __construct(array $groupedSegments)
43
    {
44 6
        $this->groupedSegments = $groupedSegments;
45 6
    }
46
47 2
    public function segmentByName(string $name): array
48
    {
49 2
        return $this->groupedSegments[$name] ?? [];
50
    }
51
52
    /** @psalm-pure */
53 6
    private static function groupSegmentsByName(SegmentInterface...$segments): self
54
    {
55 6
        $return = [];
56
57 6
        foreach ($segments as $s) {
58 6
            $return[$s->name()] ??= [];
59 6
            $return[$s->name()][$s->subSegmentKey()] = $s;
60
        }
61
62 6
        return new self($return);
63
    }
64
}
65