From 32bb0cfe512cb081e39fb946637a2ff4e1a00fd9 Mon Sep 17 00:00:00 2001
From: David Maus <maus@hab.de>
Date: Mon, 5 Mar 2012 10:05:45 +0100
Subject: [PATCH] Record: New function getFirstMatchingField

Returns the first of all fields that are matched by a field selector.
---
 src/php/HAB/Pica/Record/Record.php             | 18 ++++++++++++++++++
 .../php/HAB/Pica/Record/RecordTest.php         |  7 +++++++
 2 files changed, 25 insertions(+)

diff --git a/src/php/HAB/Pica/Record/Record.php b/src/php/HAB/Pica/Record/Record.php
index 3157807..fe41422 100644
--- a/src/php/HAB/Pica/Record/Record.php
+++ b/src/php/HAB/Pica/Record/Record.php
@@ -229,6 +229,24 @@ abstract class Record {
     }
   }
 
+  /**
+   * Return the first field that matches a selector.
+   *
+   * @see \HAB\Pica\Record\getFields()
+   *
+   * @param  string $selector Body of regular expression
+   * @return \HAB\Pica\Record\Field|null The first matching field or NULL if
+   *         no match
+   */
+  public function getFirstMatchingField ($selector) {
+    $fields = $this->getFields($selector);
+    if (empty($fields)) {
+      return null;
+    } else {
+      return reset($fields);
+    }
+  }
+
  /**
    * Finalize the clone() operation.
    *
diff --git a/src/tests/unit-tests/php/HAB/Pica/Record/RecordTest.php b/src/tests/unit-tests/php/HAB/Pica/Record/RecordTest.php
index ab8123c..4c7d038 100644
--- a/src/tests/unit-tests/php/HAB/Pica/Record/RecordTest.php
+++ b/src/tests/unit-tests/php/HAB/Pica/Record/RecordTest.php
@@ -38,6 +38,13 @@ class RecordTest extends \PHPUnit_FrameWork_TestCase {
     $this->assertInstanceOf('HAB\Pica\Record\AuthorityRecord', $record);
   }
 
+  public function testGetFirstMatchingField () {
+    $record = new AuthorityRecord(array(new Field('001@', 0),
+                                        new Field('001@', 1)));
+    $this->assertNull($record->getFirstMatchingField('002@/00'));
+    $this->assertInstanceOf('HAB\Pica\Record\Field', $record->getFirstMatchingField('001@'));
+  }
+
   ///
 
   /**
-- 
GitLab