33namespace SetBased \Exception ;
44
55//----------------------------------------------------------------------------------------------------------------------
6+ /**
7+ * Trait for exception classes with format string in constructor.
8+ *
9+ * Example:
10+ * ```
11+ * class MyException extends \Exception
12+ * {
13+ * use FormattedException;
14+ *
15+ * public function __construct()
16+ * {
17+ * list($message, $code, $previous) = self::formattedConstruct(func_get_args());
18+ *
19+ * parent::__construct($message, $code, $previous);
20+ * }
21+ * }
22+ * ```
23+ */
624trait FormattedException
725{
26+ /* PHP 5.4: doesn't allow us to use __construct in traits. This possible from PHP 5.5 and higher. */
827 //--------------------------------------------------------------------------------------------------------------------
928 /**
10- * Object constructor .
29+ * Returns a list of arguments for \Exception::_construct .
1130 *
12- * @param string|array $format The format string of the error message, see
13- * [sprintf](http://php.net/manual/function.sprintf.php).
14- * @param mixed $param,... The arguments for the format string. However, if the first argument is an exception
15- * it will be used as the [previous](http://php.net/manual/exception.construct.php)
16- * exception for the exception chaining.
31+ * @param \array $args The arguments for __construct.
32+ *
33+ * Below we give same samples of valid combinations for arguments for __construct.
34+ * ```
35+ * // Exception with message
36+ * new MyException('Something went wrong');
37+ *
38+ * // Exception with a format string
39+ * new MyException('There are %d monkeys in the %s', 5, 'tree');
40+ *
41+ * // Exception with an exception code
42+ * new MyException([$code], 'There are %d monkeys in the %s', 5, 'tree');
43+ *
44+ * // Exception with q previous exception
45+ * new MyException([$previous], 'There are %d monkeys in the %s', 5, 'tree');
46+ *
47+ * // Exception with an exception code and a previous exception
48+ * new MyException([$code,$previous], 'There are %d monkeys in the %s', 5, 'tree');
49+ * // or
50+ * new MyException([$previous,$code], 'There are %d monkeys in the %s', 5, 'tree');
51+ * ```
52+ *
53+ * @return \array[string,int,\Exception|null]
1754 */
18- public function __construct ( $ format )
55+ public static function formattedConstruct ( $ args )
1956 {
2057 $ code = 0 ;
2158 $ previous = null ;
22-
23- $ args = func_get_args ();
24- array_shift ($ args );
59+ $ format = array_shift ($ args );
2560
2661 if (is_array ($ format ))
2762 {
@@ -41,7 +76,7 @@ public function __construct($format)
4176 }
4277 }
4378
44- parent :: __construct ( vsprintf ($ format , $ args ), $ code , $ previous) ;
79+ return [ vsprintf ($ format , $ args ), $ code , $ previous] ;
4580 }
4681
4782 //--------------------------------------------------------------------------------------------------------------------
0 commit comments