Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use forAll method of Doctrine ArrayCollection?

Can anybody show example of using forAll method of Doctrine\Common\Collections\ArrayCollection?

like image 222
Victor Bocharsky Avatar asked Dec 04 '22 06:12

Victor Bocharsky


1 Answers

It's pretty straightforward. The class you linked to implements the forAll method in a following manner:

foreach ($this->_elements as $key => $element) {
     if ( ! $p($key, $element)) {
         return false;
     }
}

So, based on that you should invoke the forAll like:

$collection = ... #some data

$collection->forAll(function($key, $item){
    // Your logic here, based on $key and $item
});

Hope this help....

EDIT (the example):

  • You have an object of entity Student, which has a OneToMany to student's marks.
  • You want to check if student has passed all the subjects he/she elected

    $student = ....
    $allPassed = $student->getMarks()->forAll(function($key, $mark){
        return $mark->getValue() != 'F';
    });
    

The $allPassed will hold TRUE if all marks were either 'A', 'B', 'C' or 'D'. Even if one of them were F if will be FALSE.

like image 126
Jovan Perovic Avatar answered Dec 09 '22 01:12

Jovan Perovic