Webmozart\Expression\Expr::filter PHP 메소드

filter() 공개 정적인 메소드

Filter a collection for entries matching the expression.
public static filter ( array | ArrayAcces\ArrayAccess | Traversabl\Traversable $collection, Webmozart\Expression\Expression $expr ) : array | ArrayAcces\ArrayAccess | Traversabl\Traversable
$collection array | ArrayAcces\ArrayAccess | Traversabl\Traversable An array or an object implementing Traversable and ArrayAccess.
$expr Webmozart\Expression\Expression The expression to evaluate for each entry.
리턴 array | ArrayAcces\ArrayAccess | Traversabl\Traversable The filtered collection.
    public static function filter($collection, Expression $expr)
    {
        if (is_array($collection)) {
            return array_filter($collection, array($expr, 'evaluate'));
        }
        if (!($collection instanceof Traversable && $collection instanceof ArrayAccess)) {
            throw new InvalidArgumentException(sprintf('Expected an array or an instance of Traversable and ArrayAccess. Got: %s', is_object($collection) ? get_class($collection) : gettype($collection)));
        }
        $clone = clone $collection;
        foreach ($collection as $key => $value) {
            if (!$expr->evaluate($value)) {
                unset($clone[$key]);
            }
        }
        return $clone;
    }

Usage Example

 public function testDomainExpressions()
 {
     $c1 = new Customer();
     $c1->setPremium(true);
     $c2 = new Customer();
     $c2->setBookings(array('booking1', 'booking2'));
     $c3 = new Customer();
     $c3->setPremium(true);
     $c3->setBookings(array('booking1'));
     $customers = array($c1, $c2, $c3);
     $this->assertEquals(array($c1, 2 => $c3), Expr::filter($customers, new IsPremium()));
     $this->assertEquals(array(1 => $c2, 2 => $c3), Expr::filter($customers, new HasPreviousBookings()));
     $this->assertEquals(array(2 => $c3), Expr::filter($customers, Expr::andX(array(new HasPreviousBookings(), new IsPremium()))));
 }
All Usage Examples Of Webmozart\Expression\Expr::filter