From 608042dee60ebcf660d8e5f253187ca0c57f54bd Mon Sep 17 00:00:00 2001 From: David Maus <maus@hab.de> Date: Fri, 17 Feb 2012 09:55:11 +0100 Subject: [PATCH] Add Record::getMaximumOccurrenceOf(), return maximum occurrence value of fields identified by a tag --- src/php/HAB/Pica/Record/Record.php | 22 +++++++++++++++++++ .../php/HAB/Pica/Record/LocalRecordTest.php | 17 ++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/php/HAB/Pica/Record/Record.php b/src/php/HAB/Pica/Record/Record.php index be2a18d..21ce5a0 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 2dc1ac3..ecc1972 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 -- GitLab