rhymix/classes/object/Object.class.php
Kijin Sung 9a83e71bff Allow adding error message and sprintf() variables using setError()
xpressengine/xe-core#2181 적용시 에러 반환 문법을 단순화하기 위한 조치

기존 방식: return new Object(-1, '에러메시지');
XE 제안 방식: return class_exists('BaseObject') ? new BaseObject(-1, '에러메시지') : new Object('에러메시지');
라이믹스 방식: return $this->setError('에러메시지');

기존의 setError() 메소드가 에러 코드만 받을 수 있어서 호환성 보장에 도움이 안 되므로
에러 코드와 에러 메시지를 동시에 넣을 수 있도록 개선하고,
에러 코드를 넣지 않고 에러 메시지만 지정해도 자동으로 -1 에러 코드가 들어가도록 하였음.
(첫 번째 인자가 정수인지 아닌지에 따라 판단함.)

setError(), setMessage(), setMessageType() 등 기존에 무의미한 반환값을 가지던 메소스들 모두
$this를 반환하도록 함으로써 액션이나 트리거 등의 반환값으로 유효하도록 하고,
원할 경우 method chaining까지 사용할 수 있음.

또한 에러메시지에 변수를 넣어야 할 경우
return new Object(-1, sprintf(Context::getLang('error_msg'), $var1, $var2));
이렇게 복잡해지는 문제도 해결하기 위해
setError()에 추가로 넣은 인자는 모두 자동으로 sprintf() 처리를 거치도록 함.
예: return $this->setError('error_msg', $var1, $var2);

즉, 아래와 같은 호출 형태가 모두 유효함.

  - $this->setError(-1);
  - $this->setError(-1, 'error_msg');
  - $this->setError(-1, 'error_msg', $var1, $var2);
  - $this->setError('error_msg');
  - $this->setError('error_msg', $var1, $var2);

단, 이 커밋 이후 신규 작성하는 코어 클래스나 서드파티 자료에서만 사용할 수 있음.
기존 버전과의 호환성을 유지하기를 원하는 서드파티 자료는 XE에서 제안한 삼항식을 사용해야 함.
2017-11-27 16:33:33 +09:00

277 lines
5.2 KiB
PHP

<?php
/* Copyright (C) NAVER <http://www.navercorp.com> */
/**
* Every modules inherits from Object class. It includes error, message, and other variables for communicatin purpose.
*
* @author NAVER (developers@xpressengine.com)
*/
class Object
{
/**
* Error code. If `0`, it is not an error.
* @var int
*/
var $error = 0;
/**
* Error message. If `success`, it is not an error.
* @var string
*/
var $message = 'success';
/**
* An additional variable
* @var array
*/
var $variables = array();
/**
* http status code.
* @var int
*/
var $httpStatusCode = 200;
/**
* Constructor
*
* @param int $error Error code
* @param string $message Error message
* @return void
*/
function __construct($error = 0, $message = 'success')
{
$this->setError($error);
$this->setMessage($message);
}
/**
* Setter to set error code or message
*
* @param int|strong $error error code or message
* @return $this
*/
function setError($error = 0)
{
// If the first argument is an integer, treat it as an error code. Otherwise, treat it as an error message.
$args = func_get_args();
if(strval(intval($error)) === strval($error))
{
$this->error = intval($error);
array_shift($args);
}
else
{
$this->error = -1;
}
// Convert the error message into the correct language and interpolate any other variables into it.
if(count($args))
{
$this->message = lang(array_shift($args));
if(count($args))
{
$this->message = vsprintf($this->message, $args);
}
}
return $this;
}
/**
* Getter to retrieve error code
*
* @return int Returns an error code
*/
function getError()
{
return $this->error;
}
/**
* Setter to set HTTP status code
*
* @param int $code HTTP status code. Default value is `200` that means successful
* @return $this
*/
function setHttpStatusCode($code = 200)
{
$this->httpStatusCode = (int) $code;
return $this;
}
/**
* Getter to retrieve HTTP status code
*
* @return int Returns HTTP status code
*/
function getHttpStatusCode()
{
return $this->httpStatusCode;
}
/**
* Setter to set set the error message
*
* @param string $message Error message
* @param string $type type of message (error, info, update)
* @return $this
*/
function setMessage($message = 'success', $type = null)
{
$this->message = lang($message);
if($type !== null)
{
$this->setMessageType($type);
}
return $this;
}
/**
* Getter to retrieve an error message
*
* @return string Returns message
*/
function getMessage()
{
return $this->message;
}
/**
* set type of message
* @param string $type type of message (error, info, update)
* @return $this
* */
function setMessageType($type)
{
$this->add('message_type', $type);
return $this;
}
/**
* get type of message
* @return string $type
* */
function getMessageType()
{
$type = $this->get('message_type');
$typeList = array('error' => 1, 'info' => 1, 'update' => 1);
if(!isset($typeList[$type]))
{
$type = $this->getError() ? 'error' : 'info';
}
return $type;
}
/**
* Setter to set a key/value pair as an additional variable
*
* @param string $key A variable name
* @param mixed $val A value for the variable
* @return $this
*/
function add($key, $val)
{
$this->variables[$key] = $val;
return $this;
}
/**
* Method to set multiple key/value pairs as an additional variables
*
* @param Object|array $object Either object or array containg key/value pairs to be added
* @return $this
*/
function adds($object)
{
if(is_object($object))
{
$object = get_object_vars($object);
}
if(is_array($object))
{
foreach($object as $key => $val)
{
$this->variables[$key] = $val;
}
}
return $this;
}
/**
* Method to retrieve a corresponding value to a given key
*
* @param string $key
* @return string Returns value to a given key
*/
function get($key)
{
return $this->variables[$key];
}
/**
* Method to retrieve an object containing a key/value pairs
*
* @return Object Returns an object containing key/value pairs
*/
function gets()
{
$args = func_get_args();
$output = new stdClass();
foreach($args as $arg)
{
$output->{$arg} = $this->get($arg);
}
return $output;
}
/**
* Method to retrieve an array of key/value pairs
*
* @return array
*/
function getVariables()
{
return $this->variables;
}
/**
* Method to retrieve an object of key/value pairs
*
* @return Object
*/
function getObjectVars()
{
$output = new stdClass();
foreach($this->variables as $key => $val)
{
$output->{$key} = $val;
}
return $output;
}
/**
* Method to return either true or false depnding on the value in a 'error' variable
*
* @return bool Retruns true : error isn't 0 or false : otherwise.
*/
function toBool()
{
// TODO This method is misleading in that it returns true if error is 0, which should be true in boolean representation.
return ($this->error == 0);
}
/**
* Method to return either true or false depnding on the value in a 'error' variable
*
* @return bool
*/
function toBoolean()
{
return $this->toBool();
}
}
/* End of file Object.class.php */
/* Location: ./classes/object/Object.class.php */