You are here

public function Condition::compile in Apigee Edge 8

Compiles this conditional clause.

Parameters

$query: The query object this conditional clause belongs to.

Overrides ConditionInterface::compile

File

src/Entity/Query/Condition.php, line 48

Class

Condition
Defines the condition class for the Apigee Edge entity query.

Namespace

Drupal\apigee_edge\Entity\Query

Code

public function compile($query) {
  if (empty($this->conditions)) {
    return function () {
      return TRUE;
    };
  }

  // This closure will fold the conditions into a single closure if there are
  // more than one, depending on the conjunction.
  $fold = strtoupper($this->conjunction) === 'AND' ? function (array $filters) : callable {
    return function ($item) use ($filters) : bool {
      foreach ($filters as $filter) {
        if (!$filter($item)) {
          return FALSE;
        }
      }
      return TRUE;
    };
  } : function (array $filters) : callable {
    return function ($item) use ($filters) : bool {
      foreach ($filters as $filter) {
        if ($filter($item)) {
          return TRUE;
        }
      }
      return FALSE;
    };
  };
  $filters = [];
  foreach ($this->conditions as $condition) {

    // If the field is a condition object, compile it and add it to the
    // filters.
    if ($condition['field'] instanceof ConditionInterface) {
      $filters[] = $condition['field']
        ->compile($query);
    }
    else {

      // Set the default operator if it is not set.
      if (!isset($condition['operator'])) {
        $condition['operator'] = is_array($condition['value']) ? 'IN' : '=';
      }

      // Normalize the value to lower case.
      if (is_array($condition['value'])) {
        $condition['value'] = array_map('mb_strtolower', $condition['value']);
      }
      elseif (is_string($condition['value'])) {
        $condition['value'] = mb_strtolower($condition['value']);
      }
      $filters[] = static::matchProperty($condition);
    }
  }

  // Only fold in case of multiple filters.
  return count($filters) > 1 ? $fold($filters) : reset($filters);
}