11<?php
2- //----------------------------------------------------------------------------------------------------------------------
2+ declare (strict_types=1 );
3+
34namespace SetBased \Exception ;
45
5- //----------------------------------------------------------------------------------------------------------------------
6+ use Exception ;
7+
68/**
79 * Trait for exception classes with format string in constructor.
810 *
2325 */
2426trait FormattedException
2527{
26- /* PHP 5.4: doesn't allow us to use __construct in traits. This possible from PHP 5.5 and higher. */
28+ //--------------------------------------------------------------------------------------------------------------------
29+ /**
30+ * Object constructor.
31+ *
32+ * @param mixed ... The arguments, see {@see formattedConstruct()}.
33+ *
34+ * @since 2.0.0
35+ * @api
36+ */
37+ public function __construct ()
38+ {
39+ list ($ message , $ code , $ previous ) = self ::formattedConstruct (func_get_args ());
40+
41+ parent ::__construct ($ message , $ code , $ previous );
42+ }
43+
2744 //--------------------------------------------------------------------------------------------------------------------
2845 /**
2946 * Returns a list of arguments for \Exception::_construct.
@@ -38,6 +55,9 @@ trait FormattedException
3855 * // Exception with a format string
3956 * new MyException('There are %d monkeys in the %s', 5, 'tree');
4057 *
58+ * // Exception with a message
59+ * new MyException('Of all monkey 50% are in the tree');
60+ *
4161 * // Exception with an exception code
4262 * new MyException([$code], 'There are %d monkeys in the %s', 5, 'tree');
4363 *
@@ -55,7 +75,7 @@ trait FormattedException
5575 * @since 1.0.0
5676 * @api
5777 */
58- public static function formattedConstruct ($ args )
78+ public static function formattedConstruct ($ args ): array
5979 {
6080 $ code = 0 ;
6181 $ previous = null ;
@@ -70,13 +90,13 @@ public static function formattedConstruct($args)
7090 {
7191 if (isset ($ special [$ i ]))
7292 {
73- if ($ special [$ i ] instanceof \ Exception) $ previous = $ special [$ i ];
93+ if ($ special [$ i ] instanceof Exception) $ previous = $ special [$ i ];
7494 elseif (is_int ($ special [$ i ])) $ code = $ special [$ i ];
7595 }
7696 }
7797 }
7898
79- return [vsprintf ($ format , $ args ), $ code , $ previous ];
99+ return [empty ( $ args ) ? $ format : vsprintf ($ format , $ args ), $ code , $ previous ];
80100 }
81101
82102 //--------------------------------------------------------------------------------------------------------------------
0 commit comments