Skip to content

Commit

Permalink
Function to reindex all segments in a message
Browse files Browse the repository at this point in the history
  • Loading branch information
jay-knight committed Dec 6, 2024
1 parent 19b2fdc commit 364cda7
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/HL7/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Aranyasen\HL7;

use Aranyasen\Exceptions\HL7Exception;
use Aranyasen\HL7\Segments\MSH;
use InvalidArgumentException;

/**
Expand Down Expand Up @@ -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.
*
Expand Down
28 changes: 28 additions & 0 deletions tests/MessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}

0 comments on commit 364cda7

Please sign in to comment.