APIv4 - Add $result->single() helper
authorTim Otten <totten@civicrm.org>
Wed, 28 Oct 2020 02:44:41 +0000 (19:44 -0700)
committerTim Otten <totten@civicrm.org>
Wed, 28 Oct 2020 21:10:58 +0000 (14:10 -0700)
Civi/Api4/Generic/Result.php
tests/phpunit/api/v4/Action/ContactGetTest.php

index afc30c217ade1d5b7dde54284881ac457609ae4b..77720c9685737983e66abb378c5497d828701716 100644 (file)
@@ -67,6 +67,32 @@ class Result extends \ArrayObject implements \JsonSerializable {
     return array_pop($items);
   }
 
+  /**
+   * Return the one-and-only result record.
+   *
+   * If there are too many or too few results, then throw an exception.
+   *
+   * @return array
+   * @throws \API_Exception
+   */
+  public function single() {
+    $result = NULL;
+    foreach ($this as $values) {
+      if ($result === NULL) {
+        $result = $values;
+      }
+      else {
+        throw new \API_Exception("Expected to find one {$this->entity} record, but there were multiple.");
+      }
+    }
+
+    if ($result === NULL) {
+      throw new \API_Exception("Expected to find one {$this->entity} record, but there were zero.");
+    }
+
+    return $result;
+  }
+
   /**
    * @param int $index
    * @return array|null
index 3fc8f6928f0df43dd9e8f7dd15ed1e0bb11647db..7524a2db83998560f15772efb6b28eb2591700b2 100644 (file)
@@ -88,6 +88,16 @@ class ContactGetTest extends \api\v4\UnitTestCase {
     $limit2 = Contact::get(FALSE)->setLimit(2)->addSelect('sort_name', 'row_count')->execute();
     $this->assertCount(2, (array) $limit2);
     $this->assertCount($num, $limit2);
+    try {
+      $limit2->single();
+    }
+    catch (\API_Exception $e) {
+      $this->assertRegExp(';Expected to find one Contact record;', $e->getMessage());
+    }
+    $limit1 = Contact::get(FALSE)->setLimit(1)->execute();
+    $this->assertCount(1, (array) $limit1);
+    $this->assertCount(1, $limit1);
+    $this->assertTrue(!empty($limit1->single()['sort_name']));
   }
 
 }