From de79875c4c832a450733af80b3f7edce3d997858 Mon Sep 17 00:00:00 2001 From: David Maus <maus@hab.de> Date: Mon, 5 Mar 2012 10:21:37 +0100 Subject: [PATCH] Subfield: New function getNthSubfield() --- src/php/HAB/Pica/Record/Field.php | 21 ++++++++++++++++ .../php/HAB/Pica/Record/FieldTest.php | 25 ++++++++++++++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/php/HAB/Pica/Record/Field.php b/src/php/HAB/Pica/Record/Field.php index 1b3e2d7..eb0037f 100644 --- a/src/php/HAB/Pica/Record/Field.php +++ b/src/php/HAB/Pica/Record/Field.php @@ -236,6 +236,27 @@ class Field { } } + /** + * Return the nth occurrence of a subfield with specified code. + * + * @param string $code Subfield code + * @param integer $n Zero-based subfield index + * @return \HAB\Pica\record\Subfield|null The requested subfield or NULL if + * none exists + */ + public function getNthSubfield ($code, $n) { + $count = 0; + foreach ($this->getSubfields() as $subfield) { + if ($subfield->getCode() == $code) { + if ($count == $n) { + return $subfield; + } + $count++; + } + } + return null; + } + /** * Return the field tag. * diff --git a/src/tests/unit-tests/php/HAB/Pica/Record/FieldTest.php b/src/tests/unit-tests/php/HAB/Pica/Record/FieldTest.php index 8637a32..fa3bad8 100644 --- a/src/tests/unit-tests/php/HAB/Pica/Record/FieldTest.php +++ b/src/tests/unit-tests/php/HAB/Pica/Record/FieldTest.php @@ -120,6 +120,20 @@ class FieldTest extends \PHPUnit_FrameWork_TestCase { return $f; } + public function testGetNthSubfield () { + $f = new Field('003@', 0, array(new Subfield('a', 'first a'), + new Subfield('b', 'first b'), + new Subfield('a', 'second a'))); + $s = $f->getNthSubfield('a', 0); + $this->assertInstanceOf('HAB\Pica\Record\Subfield', $s); + $this->assertEquals('first a', $s->getValue()); + $s = $f->getNthSubfield('a', 1); + $this->assertInstanceOf('HAB\Pica\Record\Subfield', $s); + $this->assertEquals('second a', $s->getValue()); + $s = $f->getNthSubfield('a', 2); + $this->assertNull($s); + } + /** * @depends testSetSubfields */ @@ -133,9 +147,12 @@ class FieldTest extends \PHPUnit_FrameWork_TestCase { */ public function testGetSubfieldsWithCode (Field $f) { $this->assertEquals(5, count($f->getSubfields('x', 'x', 'x', 'x', 'x'))); - $this->assertEquals('first d', reset($f->getSubfields('d'))); - $this->assertEquals('first a', reset($f->getSubfields('a'))); - $this->assertEquals('second a', end($f->getSubfields('a', 'd', 'a'))); + $s = $f->getSubfields('d'); + $this->assertEquals('first d', reset($s)); + $s = $f->getSubfields('a'); + $this->assertEquals('first a', reset($s)); + $s = $f->getSubfields('a', 'd', 'a'); + $this->assertEquals('second a', end($s));; return $f; } @@ -147,7 +164,7 @@ class FieldTest extends \PHPUnit_FrameWork_TestCase { $f->addSubfield($s); $c = clone($f); $this->assertNotSame($c, $f); - $this->assertNotSame($s, reset($c->getSubfields('a'))); + $this->assertNotSame($s, $c->getNthSubfield('a', 0)); } /// -- GitLab