Dave Jarvis' Repositories

git clone https://repo.autonoma.ca/repo/recipe-fiddle.git
<?php
namespace com\whitemagicsoftware;

require "constants.php";
require "class.Ajax.php";

/**
 * Handles Ajax requests for ingredients.
 */
class AjaxIngredientSearch extends Ajax {
  function __construct() {
    parent::__construct();
  }

  /**
   * Used for the ingredients selection box when entering an ingredient.
   *
   * @param $search Ingredient name search term to match.
   * @param $category Set to true to search for the categories, as well.
   *
   */
  private function getIngredients( $search, $category = false ) {
    $search = mb_strtolower( $search );
    $proc   = "search_ingredient";

    if( $category ) {
      $proc = $proc . "_category";
    }

    return $this->call( $proc, "id, label", $search );
  }

  public function handleAjaxRequest() {
    $search      = $this->getParameter( "term" );
    $category    = $this->getParameter( "category" );
    $ingredients = $this->getIngredients( $search, $category );

    $result = array();

    // The autocomplete widget requires fields in a specific format.
    //
    foreach( $ingredients as $key => $value ) {
      $value["value"] = $value["label"];
      array_push( $result, $value );
    }

    return json_encode( $result, true );
  }
}