<?php
/*
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC. All rights reserved.                        |
 |                                                                    |
 | This work is published under the GNU AGPLv3 license with some      |
 | permitted exceptions and without any warranty. For full license    |
 | and copyright information, see https://civicrm.org/licensing       |
 +--------------------------------------------------------------------+
 */

/**
 * Base class for exceptions generated by CiviCRM.
 * This Exception returns more information than the default one. We are using it from the
 * form layer to allow redirects to occur without having redirects in the BAO
 * @param array $data
 *   Extra params to return. eg an extra array of ids. It is not mandatory, but can help the computer using the api. Keep in mind the api consumer isn't to be trusted. eg. the database password is NOT a good extra data.
 */
class CRM_Core_Exception extends PEAR_Exception {

  const UNAUTHORIZED = 'unauthorized';
  const NOT_IMPLEMENTED = 'not-found';

  private $errorData = [];

  /**
   * Class constructor.
   *
   * @param string $message
   *   The human friendly error message.
   * @param int|string $error_code
   *   A computer friendly error code. By convention, no space (but underscore
   *   allowed) (ex: mandatory_missing, duplicate, invalid_format).
   * @param array $errorData
   *   Extra params to return. eg an extra array of ids. It is not mandatory,
   *   but can help the computer using the api. Keep in mind the api consumer
   *   isn't to be trusted. eg. the database password is NOT a good extra data.
   * @param Throwable|NULL $previous
   *   A previous exception which caused this new exception.
   */
  public function __construct($message, $error_code = 0, $errorData = [], $previous = NULL) {

    if (($errorData['exception'] ?? NULL) instanceof DB_Error) {
      // Pass the exception to the PEAR_Exception parent as the code for it to handle.
      $code = $errorData['exception'];
    }
    elseif (is_numeric($error_code)) {
      // Using int for error code "old way") ?
      $code = $error_code;
    }
    else {
      $code = 0;
    }
    // DIVERGENCE: CRM_Core_Exception used `$message`. API_Exception and CiviCRM_API3_Exception used `ts($message)`.
    // IMHO, this seems like a terrible place to put `ts()` - civistrings won't detect, and it's hard dependency on l10n services.
    parent::__construct($message, $code, $previous);
    $this->errorData = $errorData + ['error_code' => $error_code];
  }

  /**
   * Custom string representation of object.
   *
   * @return string
   */
  public function __toString() {
    return __CLASS__ . ": [{$this->errorData['error_code']}: {$this->message}\n";
  }

  /**
   * Get error code.
   *
   * @return int|string
   */
  public function getErrorCode() {
    return $this->errorData['error_code'];
  }

  /**
   * Return specific error information.
   *
   * (Can be used for more detailed error messages or translation.)
   *
   * This method may be overridden in child exception classes in order
   * to add functionality not present in PEAR_Exception and is a placeholder
   * to define API
   *
   * The returned array must be an associative array of parameter => value like so:
   * <pre>
   * array('name' => $name, 'context' => array(...))
   * </pre>
   * @return array
   */
  public function getErrorData() {
    return $this->errorData;
  }

  /**
   * Get extra parameters.
   *
   * @return array
   * @deprecated Remove in v6.0. Compatibility with older API_Exception/CiviCRM_API3_Exception contracts.
   */
  public function getExtraParams() {
    return $this->errorData;
  }

  /**
   * Get a message suitable to be presented to the user.
   *
   * @return string
   */
  public function getUserMessage(): string {
    return $this->getMessage();
  }

  /**
   * Get error codes.
   *
   * DIVERGENCE: API_Exception defined a discoverable list of error-codes. CRM_Core_Exception and CiviCRM_API3_Exception did not.
   *
   * @return array
   */
  public function getErrorCodes() {
    return [
      2000 => '$params was not an array',
      2001 => 'Invalid Value for Date field',
      2100 => 'String value is longer than permitted length',
      self::UNAUTHORIZED => 'Unauthorized',
      self::NOT_IMPLEMENTED => 'Entity or method is not implemented',
    ];
  }

}
