diff --git a/src/php/HAB/Pica/Record/Record.php b/src/php/HAB/Pica/Record/Record.php index be2a18dca7d7b03f70b420f3b03f14bbdcaa16c7..21ce5a0147666dad6f33d5edbd69b0baa50eed2d 100644 --- a/src/php/HAB/Pica/Record/Record.php +++ b/src/php/HAB/Pica/Record/Record.php @@ -164,6 +164,28 @@ abstract class Record { } } + /** + * Return the maximum occurrence value of a field. + * + * @throws \InvalidArgumentException Invalid field tag + * @param string $tag Field tag + * @return int|null Maximum occurrence of field or NULL if field does not + * exist + */ + public function getMaximumOccurrenceOf ($tag) { + if (!preg_match(Field::TAG_RE, $tag)) { + throw new \InvalidArgumentException("Invalid field tag: {$tag}"); + } + return array_reduce($this->getFields($tag), + function ($maxOccurrence, Field $field) { + if ($field->getOccurrence() > $maxOccurrence || $maxOccurrence === null) { + return $field->getOccurrence(); + } else { + return $maxOccurrence; + } + }, null); + } + /** * Return TRUE if the record is empty. * diff --git a/src/tests/unit-tests/php/HAB/Pica/Record/LocalRecordTest.php b/src/tests/unit-tests/php/HAB/Pica/Record/LocalRecordTest.php index 2dc1ac33e7bbb9a071099e1ae2d95926a935aa5c..ecc1972823e098a91327f6158b921b8fd6cf83e5 100644 --- a/src/tests/unit-tests/php/HAB/Pica/Record/LocalRecordTest.php +++ b/src/tests/unit-tests/php/HAB/Pica/Record/LocalRecordTest.php @@ -92,6 +92,15 @@ class LocalRecordTest extends \PHPUnit_FrameWork_TestCase { $this->assertFalse($r->isEmpty()); } + public function testGetMaximumOccurrenceOf () { + $r = new LocalRecord(); + $this->assertNull($r->getMaximumOccurrenceOf('144Z')); + $r->append(new Field('144Z', 0)); + $this->assertEquals(0, $r->getMaximumOccurrenceOf('144Z')); + $r->append(new Field('144Z', 10)); + $this->assertEquals(10, $r->getMaximumOccurrenceOf('144Z')); + } + /// /** @@ -129,4 +138,12 @@ class LocalRecordTest extends \PHPUnit_FrameWork_TestCase { $r = new LocalRecord(); $r->append(new Field('003@', 0)); } + + /** + * @expectedException \InvalidArgumentException + */ + public function testGetMaximumOccurrenceOfThrowsExceptionOnInvalidFieldTag () { + $r = new LocalRecord(); + $r->getMaximumOccurrenceOf('@@@@'); + } } \ No newline at end of file