Skip to content

Instantly share code, notes, and snippets.

@f0t0n
Created May 17, 2012 18:51
Show Gist options
  • Save f0t0n/2720875 to your computer and use it in GitHub Desktop.
Save f0t0n/2720875 to your computer and use it in GitHub Desktop.
<?php
interface ApiErrorCode {
const WRONG_ACTION = 0;
const WRONG_PARAMETERS_SET = 1;
public function getError();
}
interface ChartusApiErrorCode extends ApiErrorCode {
const WRONG_USER_CREDENTIALS = 2;
const CANT_RETRIEVE_AUTH_TOKEN = 3;
}
class ApiError implements ApiErrorCode {
public $message;
public $code;
/** @var ApiError */
protected static $_instance;
protected $messageByCode;
protected function init() {
$this->messageByCode = array(
self::WRONG_ACTION => 'Wrong action',
self::WRONG_PARAMETERS_SET => 'Wrong parameters set',
);
}
protected function __construct() {
$this->init();
}
public static function instance() {
if(self::$_instance === null) {
self::$_instance = new ApiError();
}
return self::$_instance;
}
public function getError($errorCode) {
$this->code = $errorCode;
$this->message = $this->messageByCode[$errorCode];
return $this;
}
}
class ChartusApiError extends ApiError {
public static function instance() {
if(self::$_instance === null) {
self::$_instance = new ChartusApiError();
}
return self::$_instance;
}
protected function init() {
parent::init();
$this->messageByCode = array_merge($this->messageByCode, array(
self::WRONG_USER_CREDENTIALS => 'Wrong user credentials.',
self::CANT_RETRIEVE_AUTH_TOKEN => 'Can\'t retrieve authentication token',
));
}
}
// usage like:
class MyClass {
protected function myMethod() {
$error = ChartusApiError::instance()
->getError(ChartusApiErrorCode::WRONG_USER_CREDENTIALS);
}
protected function throwError(ApiError$error,
$className = 'ChartusApiException') {
throw new $className($error->message, $error->code);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment