Skip to content

Commit a9e063c

Browse files
authored
Merge pull request #4 from chadicus/master
Add ExceptionWithContext
2 parents cc396e2 + 5d23a6e commit a9e063c

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

src/ExceptionWithContext.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace TraderInteractive\Exceptions;
4+
5+
use Throwable;
6+
7+
/**
8+
* Exception with variable context.
9+
*/
10+
class ExceptionWithContext extends \Exception
11+
{
12+
/**
13+
* @var array
14+
*/
15+
private $context;
16+
17+
/**
18+
* Construct a new instance of the exception.
19+
*
20+
* @param string $message The exception message.
21+
* @param array $context Any local context information.
22+
*/
23+
public function __construct(string $message, array $context = [], int $code = 0, Throwable $previous = null)
24+
{
25+
parent::__construct($message, $code, $previous);
26+
$this->context = $context;
27+
}
28+
29+
/**
30+
* Returns the specified context array associated with this exception.
31+
*
32+
* @return array
33+
*/
34+
public function getContext() : array
35+
{
36+
return $this->context;
37+
}
38+
}

tests/ExceptionWithContextTest.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
3+
namespace TraderInteractiveTest\Exceptions;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use TraderInteractive\Exceptions\ExceptionWithContext;
7+
8+
/**
9+
* @coversDefaultClass \TraderInteractive\Exceptions\ExceptionWithContext
10+
*/
11+
final class ExceptionWithContextTest extends TestCase
12+
{
13+
/**
14+
* @test
15+
* @covers ::getContext
16+
*
17+
* @return void
18+
*/
19+
public function contextIsOptional()
20+
{
21+
$this->assertSame([], (new ExceptionWithContext('a message'))->getContext());
22+
}
23+
24+
/**
25+
* @test
26+
* @covers ::getContext
27+
*
28+
* @return void
29+
*/
30+
public function getContextReturnsExpectedValues()
31+
{
32+
$context = ['foo' => 'bar'];
33+
$this->assertSame($context, (new ExceptionWithContext('a message', $context))->getContext());
34+
}
35+
36+
/**
37+
* @test
38+
* @covers ::__construct
39+
*
40+
* @return void
41+
*/
42+
public function exceptionInheritsParentProperties()
43+
{
44+
$this->assertSame(2, (new ExceptionWithContext('a message', [], 2))->getCode());
45+
}
46+
}

0 commit comments

Comments
 (0)