From 364cda772e64bee7d546af32e26c62139e2a72a8 Mon Sep 17 00:00:00 2001 From: Jay Knight Date: Fri, 6 Dec 2024 11:23:24 -0600 Subject: [PATCH] Function to reindex all segments in a message --- src/HL7/Message.php | 20 ++++++++++++++++++++ tests/MessageTest.php | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/HL7/Message.php b/src/HL7/Message.php index ee41ccf..950407f 100644 --- a/src/HL7/Message.php +++ b/src/HL7/Message.php @@ -5,6 +5,7 @@ namespace Aranyasen\HL7; use Aranyasen\Exceptions\HL7Exception; +use Aranyasen\HL7\Segments\MSH; use InvalidArgumentException; /** @@ -325,6 +326,25 @@ public function getSegments(): array return $this->segments; } + /** + * Reindex all of the segments in the message + */ + public function reindexSegments(): void + { + $indexes = []; + foreach ($this->segments as $segment) { + if (is_a($segment, MSH::class)) { + continue; + } + + if (!array_key_exists(get_class($segment), $indexes)) { + $indexes[get_class($segment)] = 1; + } + + $segment->setId($indexes[get_class($segment)]++); + } + } + /** * Return a string representation of this message. * diff --git a/tests/MessageTest.php b/tests/MessageTest.php index cfcfbfd..754f58f 100644 --- a/tests/MessageTest.php +++ b/tests/MessageTest.php @@ -635,4 +635,32 @@ public function segments_can_be_retrieved_by_class(): void $OBRs = $message->getSegmentsByClass(OBR::class); self::assertCount(0, $OBRs); } + + /** @test */ + public function reindex_message_segments(): void + { + $message = new Message(autoIncrementIndices: false); + $pid = new PID(); + $pid->setId(2); + $message->addSegment($pid); + + $obx1 = new OBX(); + $obx1->setId(3); + $obx1->setValueType("ST"); + $message->addSegment($obx1); + + $obx2 = new OBX(); + $obx2->setId(1); + $obx2->setValueType("CWE"); + $message->addSegment($obx2); + + $message->reindexSegments(); + $PIDs = $message->getSegmentsByClass(PID::class); + self::assertSame(1, $PIDs[0]->getId()); + $OBXs = $message->getSegmentsByClass(OBX::class); + self::assertSame(1, $OBXs[0]->getId()); + self::assertSame("ST", $OBXs[0]->getValueType()); + self::assertSame(2, $OBXs[1]->getId()); + self::assertSame("CWE", $OBXs[1]->getValueType()); + } }