Skip to content

Commit b09a973

Browse files
committed
Add method fromClass to TemplatedMessageExceptionTrait
1 parent 2f289f7 commit b09a973

2 files changed

Lines changed: 49 additions & 5 deletions

File tree

src/Exception/TemplatedMessageExceptionTrait.php

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,23 @@
1515
* Boilerplate for an exception with templated message.
1616
*
1717
* @author Mathias Gelhausen <gelhausen@cross-solution.de>
18-
* @todo write tests
1918
*/
2019
trait 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
}

test/TestUtilsTest/Exception/TemplatedMessageExceptionTraitTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,13 @@ public function testCreateWithPrevious()
4141
static::assertSame($ex, $target->getPrevious());
4242
}
4343

44+
public function testFromClass()
45+
{
46+
$target = InvalidUsageException::fromClass('CLASS', '%s', 'value1');
47+
48+
static::assertEquals('CLASS: value1', $target->getMessage());
49+
}
50+
4451
public function testFromTrait()
4552
{
4653
$target = InvalidUsageException::fromTrait('TRAIT', 'CLASS', '%s', 'value1');

0 commit comments

Comments
 (0)