From 4eaccf28fe5fc0b8805a488be9a79a126d9206a7 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Tue, 16 Aug 2022 18:25:46 -0700 Subject: [PATCH] (REF) Extract method Array::single() Note: If you're reading this, you may notice that the exception-type looks different. `API_Exception` is just an alias of `CRM_Core_Exception`. --- CRM/Utils/Array.php | 29 +++++++++++++++++++++++++++++ Civi/Api4/Generic/Result.php | 16 +--------------- 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/CRM/Utils/Array.php b/CRM/Utils/Array.php index 12822ae357..45649a167d 100644 --- a/CRM/Utils/Array.php +++ b/CRM/Utils/Array.php @@ -1211,6 +1211,35 @@ class CRM_Utils_Array { } } + /** + * Take one well-defined item out of a single-item list. + * + * Assert that the list genuinely contains *exactly* one item. + * + * @param iterable $items + * @param string $recordTypeLabel + * @return mixed + * The first (and only) item from the $items list. + * @throws \CRM_Core_Exception + */ + public static function single(iterable $items, string $recordTypeLabel = 'record') { + $result = NULL; + foreach ($items as $values) { + if ($result === NULL) { + $result = $values; + } + else { + throw new \CRM_Core_Exception("Expected to find one {$recordTypeLabel}, but there were multiple."); + } + } + + if ($result === NULL) { + throw new \CRM_Core_Exception("Expected to find one {$recordTypeLabel}, but there were zero."); + } + + return $result; + } + /** * Convert a simple dictionary into separate key+value records. * diff --git a/Civi/Api4/Generic/Result.php b/Civi/Api4/Generic/Result.php index c1896890bf..fb8401e4d1 100644 --- a/Civi/Api4/Generic/Result.php +++ b/Civi/Api4/Generic/Result.php @@ -87,21 +87,7 @@ class Result extends \ArrayObject implements \JsonSerializable { * @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; + return \CRM_Utils_Array::single($this, "{$this->entity} record"); } /** -- 2.25.1