1515 * Boilerplate for an exception with templated message.
1616 *
1717 * @author Mathias Gelhausen <gelhausen@cross-solution.de>
18- * @todo write tests
1918 */
2019trait TemplatedMessageExceptionTrait
2120{
21+ /**
22+ * Creates an exception with templated message.
23+ *
24+ * Pass in arguments as you would to _sprintf_:
25+ * The first argument is the template string, the following
26+ * arguments are the replacements.
27+ *
28+ * If the last argument passed is an instanceof \Throwable, it is used
29+ * as previous exception argument to the \Exception constructor.
30+ *
31+ * @param array $args
32+ *
33+ * @return \Exception
34+ */
2235 public static function create (...$ args ): \Exception
2336 {
2437 $ ex = end ($ args ) instanceof \Throwable ? array_pop ($ args ) : null ;
@@ -27,12 +40,36 @@ public static function create(...$args): \Exception
2740 return new static ($ message , 0 , $ ex );
2841 }
2942
43+ /**
44+ * Creates an exception with templated message prepended by the class name.
45+ *
46+ * @param string $class
47+ * @param string $message
48+ * @param array ...$args
49+ *
50+ * @return \Exception
51+ */
52+ public static function fromClass (string $ class , string $ message , ...$ args ): \Exception
53+ {
54+ $ message = '%s: ' . $ message ;
55+
56+ return static ::create ($ message , $ class , ...$ args );
57+ }
58+
59+ /**
60+ * Creates an exception with templated message prepended by trait and class name.
61+ *
62+ * @param string $trait
63+ * @param string $class
64+ * @param string $message
65+ * @param array ...$args
66+ *
67+ * @return \Exception
68+ */
3069 public static function fromTrait (string $ trait , string $ class , string $ message , ...$ args ): \Exception
3170 {
32- if (count ($ args )) {
33- $ message = sprintf ($ message , ...$ args );
34- }
71+ $ message = '%s: %s: ' . $ message ;
3572
36- return static ::create (' %s: %s: %s ' , $ trait , $ class , $ message );
73+ return static ::create ($ message , $ trait , $ class , ... $ args );
3774 }
3875}
0 commit comments