<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

class ArrayMatchByPredicate
{
  private $kriteriumFunctions = array();

  public function add($kFunc)
  {
    $this->kriteriumFunctions[] = $kFunc;

    return $this;
  }

  public function getBestMatch($datamodulArray)
  {
    if (count($datamodulArray) == 1) {
      return $datamodulArray[0];
    }

    return $this->matchOne($datamodulArray, $this->kriteriumFunctions);
  }

  private function matchOne($datamodulArray, $pKriterien)
  {
    if (count($pKriterien) == 0) {
      return $datamodulArray[0];
    }
    $match = array();
    foreach ($datamodulArray as $datamodul) {
      if (call_user_func($pKriterien[0], $datamodul)) {
        $match[] = $datamodul;
      }
    }
    if (count($match) == 1) {
      return $match[0];
    } elseif (count($match) == 0) {
      return $this->matchOne($datamodulArray, ArrayOperations::tail($pKriterien));
    } else {
      return $this->matchOne($match, ArrayOperations::tail($pKriterien));
    }
  }
}