<?php
class CRM_AnnualGrantBudgets_APIWrapper implements API_Wrapper {
  /**
   * the wrapper contains a method that allows you to alter the parameters of the api request (including the action and the entity)
   */
  public function fromApiInput($apiRequest) {
    $params = $apiRequest['params'];
    if (!empty($params['id'])) {
      $ids = explode('_', $params['id']);
      if (count($ids) == 2) {
        unset($params['id']);
        $gBParams = [
          'financial_type_id' => $ids[0],
          'fiscal_year' => $ids[1],
        ];
        try {
          $gBId = civicrm_api3('GrantBudget', 'getvalue', $gBParams + ['return' => 'id']);
          $params['id'] = $gBId;
        }
        catch (CiviCRM_API3_Exception $e) {
          $params += $gBParams;
        }
        $apiRequest['params'] = $params;
      }
    }
    return $apiRequest;
  }

  /**
   * alter the result before returning it to the caller.
   */
  public function toApiOutput($apiRequest, $result) {
    return $result;
  }

}