PHP Lithium: Filtering an existing DocumentSet and getting the first match
I am fetching DocumentSet in lithium from MongoDB but I don't want to process documents right away. Instead, I would like to have a filter that I could say something like this:
$manyDocuments->giveMeTheOneWhere(array('foo' => 'bar'));
I already tried this but it didn't work:
$manyDocuments->find(function($singleDocument){
return ($singleDocument->foo == 'bar');
});
Even if I manually return true inside the closure, it always returns an empty DocumentSet.
Just to be clear: I'm not looking for a database job, I want to get one of the pre-existing DocumentSet instead. Is there a fancy way to achieve this, or do I need to iterate with a custom function?
+3
source to share
3 answers
I'm on the latest of the lithium master branch and wrote this unit test that works for me. I'm not sure why you are getting an empty DocumentSet.
$docs = new DocumentSet(array('data' => array(
new Document(array('data' => array(
'id' => 1,
'foo' => 'bar'
))),
new Document(array('data' => array(
'id' => 2,
'foo' => 'baz'
))),
new Document(array('data' => array(
'id' => 3,
'foo' => 'bar'
))),
new Document(array('data' => array(
'id' => 4,
'blah' => 'ack'
)))
)));
$filtered = $docs->find(function($doc) {
return $doc->foo === 'bar';
});
$expected = array(
'0' => array('id' => 1, 'foo' => 'bar'),
'2' => array('id' => 3, 'foo' => 'bar')
);
$this->assertIdentical($expected, $filtered->data());
+1
source to share