Commit de79875c authored by David Maus's avatar David Maus
Browse files

Subfield: New function getNthSubfield()

parent 32bb0cfe
......@@ -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.
*
......
......@@ -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));
}
///
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment