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

Proposal: Add getAsCollection() method #8

Open
jodiedunlop opened this issue Sep 24, 2018 · 6 comments
Open

Proposal: Add getAsCollection() method #8

jodiedunlop opened this issue Sep 24, 2018 · 6 comments
Labels
enhancement New feature or request

Comments

@jodiedunlop
Copy link
Contributor

When you call get('some.node') if the node doesn't exist you get null (or pass a default value) .

Suggest adding getAsCollection() to ensure a collection is always returned regardless of whether the node exists, or if the node is an item/collection. This is useful due to chaining.

Example:

$response->getAsCollection('recipients.data')->each(function($recipient) { ... }); 
  • If the node doesn't exist an empty (ArrayObject) collection will be returned
  • If the node exists but isn't a collection (eg. a scalar or an associative array), then it will be wrapped in a collection with a single item
@jodiedunlop jodiedunlop added the enhancement New feature or request label Sep 24, 2018
@jodiedunlop
Copy link
Contributor Author

May need to supplement this with getAsItem() to pull the first item off a collection, but a non-existing node would still need to return null/default value.

@cerbero90
Copy link

Nice proposal, Alex went through this a couple of days ago if I'm not wrong.

It's just a matter of personal taste but what do you think about:

  • $response->collect('recipients.data') instead of getAsCollection()
  • $response->first('recipients.data') instead of getAsItem()

Perhaps getAsCollection() and getAsItem() are more descriptive though.

@jodiedunlop
Copy link
Contributor Author

I like collect() and first() already exists but it does not ensure you get a single item (eg. the first item in a collection could be a collection)

@jodiedunlop
Copy link
Contributor Author

I mean you can also do $response->get('recipients.data.0') so maybe it's not needed at all, just the collect('node') method

@cerbero90
Copy link

Good point, maybe a tad less elegant though, personally I like the idea of having an alternative method like getAsItem(), getItem(), getValue() or however we prefer to name it

@jodiedunlop
Copy link
Contributor Author

Yeah the problem with xxitem() is you can't ensure they get an item. You either get a scalar value for primitive types or a boxed item. Boxing scalars would be a really bad idea.

I think you were right with first() and i was overthinking it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Development

No branches or pull requests

2 participants