diff --git a/src/HL7/Message.php b/src/HL7/Message.php index 95574df..660a77a 100644 --- a/src/HL7/Message.php +++ b/src/HL7/Message.php @@ -73,7 +73,9 @@ public function __construct(string $msgStr = null, array $hl7Globals = null, boo $segments = preg_split("/[\n\r" . $this->segmentSeparator . ']/', $msgStr, -1, PREG_SPLIT_NO_EMPTY); // The first segment should be the control segment - preg_match('/^([A-Z0-9]{3})(.)(.)(.)(.)(.)(.)/', $segments[0], $matches); + if (!preg_match('/^([A-Z0-9]{3})(.)(.)(.)(.)(.)(.)/', $segments[0], $matches)) { + throw new HL7Exception('Not a valid message: invalid control segment', E_USER_ERROR); + } [$dummy, $hdr, $fieldSep, $compSep, $repSep, $esc, $subCompSep, $fieldSepCtrl] = $matches; diff --git a/tests/MessageTest.php b/tests/MessageTest.php index aeaa286..b0dcfee 100644 --- a/tests/MessageTest.php +++ b/tests/MessageTest.php @@ -223,4 +223,14 @@ public function a_segment_can_be_retrieved_as_a_string() $this->assertSame('1', $msg->getSegmentFieldAsString(0, 3), 'MSH(3) as string'); $this->assertSame('a^b1&b2^c', $msg->getSegmentFieldAsString(1, 2), 'XXX(2) as string'); } + + /** + * @test + * @expectedException Aranyasen\Exceptions\HL7Exception + * @expectedExceptionMessage Not a valid message: invalid control segment + */ + public function an_exception_will_be_throw_in_invalid_string() + { + $msg = new Message("I'm an invalid message"); + } }