Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

APIv4 - Add $result->single() helper #18871

Merged
merged 1 commit into from
Oct 28, 2020

Conversation

totten
Copy link
Member

@totten totten commented Oct 28, 2020

Overview

This is a developer-experience improvement for the common case where one uses APIv4 to work with exactly one record (e.g. because having fewer or more records indicates a violation of a pre-condition).

Before

I have found myself writing this guard several times:

$result = civicrm_api4('Foo', 'bar', [
  'whiz' => 123,
  'bang' => 456,
]);
if ($result->count() !== 1) {
  throw new Exception(sprintf("This operation is defined for exactly one result. Found %d records.", 
    $result->count()));
}
$record = $result->first();

Note that the Result object has a first() method, which you could call fluently. That would be clean/pretty. However, this is a soft method which does not complain if there are zero or multiple records.

After

If the situation calls for exactly one record, then use single():

$record = civicrm_api4('Foo', 'bar', [
  'whiz' => 123,
  'bang' => 456,
])->single();

@civibot
Copy link

civibot bot commented Oct 28, 2020

(Standard links)

@civibot civibot bot added the master label Oct 28, 2020
@seamuslee001
Copy link
Contributor

I like this but will leave for @colemanw to comment

@colemanw
Copy link
Member

There is already something very similar:

$result = civicrm_api4('Foo', 'bar', [...], 0);

The 4th param is $index and in this case we're requesting the item at index 0. An exception will be thrown if no items are found. The only difference between this and your ->single() method is that an exception will not be thrown if 2 or more items are found (the first one will be returned without complaint). I've found that serves my purposes well enough, but sure we can merge this if you like.

@eileenmcnaughton
Copy link
Contributor

OK - so no objection from @colemanw & it's a yes from me. Lock it in caller

@eileenmcnaughton eileenmcnaughton merged commit c2b4ced into civicrm:master Oct 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants