Skip to content

Commit

Permalink
ApiException::withPrevious() fix
Browse files Browse the repository at this point in the history
  • Loading branch information
mabar committed Dec 10, 2019
1 parent 051ae4a commit 02390f2
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 5 deletions.
3 changes: 0 additions & 3 deletions phpstan.neon
Expand Up @@ -7,9 +7,6 @@ parameters:
- '#^Variable property access on (\$this|static)\(Apitte\\Core\\Mapping\\(Request|Response)\\BasicEntity\)\.$#'
- '#^Variable property access on Apitte\\Core\\Mapping\\Request\\BasicEntity\.$#'

# Magic access
- '#^Access to private property \$previous of parent class Exception.$#'

# There is no apitte/negotiation dependency
- '#^Return typehint of method Apitte\\Core\\Http\\ApiResponse::getEntity\(\) has invalid type Apitte\\Negotiation\\Http\\AbstractEntity\.$#'
- '#^Parameter \$entity of method Apitte\\Core\\Http\\ApiResponse::withEntity\(\) has invalid typehint type Apitte\\Negotiation\\Http\\AbstractEntity\.$#'
Expand Down
4 changes: 4 additions & 0 deletions ruleset.xml
Expand Up @@ -15,6 +15,10 @@
</properties>
</rule>

<rule ref="SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly.ReferencedGeneralException">
<exclude-pattern>src/Exception/ExceptionExtra.php</exclude-pattern>
</rule>

<rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
<exclude-pattern>*tests/cases/*</exclude-pattern>
</rule>
Expand Down
8 changes: 6 additions & 2 deletions src/Exception/ExceptionExtra.php
Expand Up @@ -3,6 +3,7 @@
namespace Apitte\Core\Exception;

use Exception;
use ReflectionClass;
use Throwable;

/**
Expand Down Expand Up @@ -48,7 +49,11 @@ public function withMessage($message)
*/
public function withPrevious(Throwable $exception)
{
$this->previous = $exception;
$reflection = new ReflectionClass(Exception::class);
$property = $reflection->getProperty('previous');
$property->setAccessible(true);
$property->setValue($this, $exception);
$property->setAccessible(false);

return $this;
}
Expand All @@ -75,7 +80,6 @@ public function withTypedContext(string $type, $context)
return $this;
}


/**
* @return mixed
*/
Expand Down
22 changes: 22 additions & 0 deletions tests/cases/Exception/ExceptionExtra.phpt
@@ -0,0 +1,22 @@
<?php declare(strict_types = 1);

use Apitte\Core\Exception\Api\ClientErrorException;
use Apitte\Core\Http\ApiResponse;
use Tester\Assert;

require_once __DIR__ . '/../../bootstrap.php';

test(static function (): void {
$previous = new Exception('previous');

$exception = ClientErrorException::create()
->withCode(ApiResponse::S406_NOT_ACCEPTABLE)
->withMessage('test')
->withPrevious($previous)
->withTypedContext('foo', 'bar');

Assert::same(ApiResponse::S406_NOT_ACCEPTABLE, $exception->getCode());
Assert::same('test', $exception->getMessage());
Assert::same($previous, $exception->getPrevious());
Assert::same(['foo' => 'bar'], $exception->getContext());
});

0 comments on commit 02390f2

Please sign in to comment.