Completed
Push — master ( f39e81...ee54ed )
by Benedikt
02:15
created

Handler::getJsonMessage()   C

Complexity

Conditions 8
Paths 48

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 12
nc 48
nop 3
dl 0
loc 25
rs 5.3846
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Tfboe\FmLib\Exceptions;
5
6
use Exception;
7
use Illuminate\Validation\ValidationException;
8
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
9
10
/**
11
 * Class Handler
12
 * @package Tfboe\FmLib\Exceptions
13
 */
14
class Handler extends ExceptionHandler
15
{
16
//<editor-fold desc="Fields">
17
  /**
18
   * A list of the exception types that should not be reported.
19
   *
20
   * @var array
21
   */
22
  protected $dontReport = [
23
    ValidationException::class,
24
  ];
25
//</editor-fold desc="Fields">
26
27
//<editor-fold desc="Public Methods">
28
  /** @noinspection PhpMissingParentCallCommonInspection */
29
  /**
30
   * Render an exception into an HTTP response.
31
   *
32
   * @param  \Illuminate\Http\Request $request
33
   * @param  \Exception $exception
34
   * @param  bool $printTrace if true a trace will be appended to the exception message
35
   * @return \Illuminate\Http\Response
36
   * @SuppressWarnings(PHPMD.UnusedFormalParameter)
37
   */
38
  public function render($request, Exception $exception, $printTrace = false)
39
  {
40
    //don't throw html exceptions always render using json
41
    $statusCode = $this->getExceptionHTTPStatusCode($exception);
42
43
    return response()->json(
0 ignored issues
show
Bug introduced by
The method json does only exist in Laravel\Lumen\Http\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
44
      $this->getJsonMessage($exception, $statusCode, $printTrace),
45
      $statusCode
46
    );
47
  }
48
//</editor-fold desc="Public Methods">
49
50
//<editor-fold desc="Protected Methods">
51
  /**
52
   * Extracts the status code of an exception
53
   * @param Exception $exception the exception to extract from
54
   * @return int|mixed the status code or 500 if no status code found
55
   */
56
  protected function getExceptionHTTPStatusCode(Exception $exception)
57
  {
58
    // Not all Exceptions have a http status code
59
    // We will give Error 500 if none found
60
    if ($exception instanceof ValidationException) {
61
      return $exception->getResponse()->getStatusCode();
62
    }
63
    return method_exists($exception, 'getStatusCode') ? $exception->getStatusCode() :
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method getStatusCode() does only exist in the following sub-classes of Exception: Illuminate\Http\Exceptions\PostTooLargeException, Symfony\Component\HttpKe...cessDeniedHttpException, Symfony\Component\HttpKe...BadRequestHttpException, Symfony\Component\HttpKe...n\ConflictHttpException, Symfony\Component\HttpKe...ption\GoneHttpException, Symfony\Component\HttpKe...Exception\HttpException, Symfony\Component\HttpKe...thRequiredHttpException, Symfony\Component\HttpKe...NotAllowedHttpException, Symfony\Component\HttpKe...AcceptableHttpException, Symfony\Component\HttpKe...n\NotFoundHttpException, Symfony\Component\HttpKe...tionFailedHttpException, Symfony\Component\HttpKe...onRequiredHttpException, Symfony\Component\HttpKe...navailableHttpException, Symfony\Component\HttpKe...nyRequestsHttpException, Symfony\Component\HttpKe...authorizedHttpException, Symfony\Component\HttpKe...ableEntityHttpException, Symfony\Component\HttpKe...dMediaTypeHttpException. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
64
      ($exception->getCode() > 0 ? $exception->getCode() : 500);
65
  }
66
67
  /**
68
   * Gets the exception name of an exception which is used by clients to identify the type of the error.
69
   * @param Exception $exception the exception whose name we want
70
   * @return string the exception name
71
   */
72
  protected function getExceptionName(Exception $exception): string
73
  {
74
    if ($exception instanceof AuthenticationException) {
75
      return ExceptionNames::AUTHENTICATION_EXCEPTION;
76
    }
77
    if ($exception instanceof DuplicateException) {
78
      return ExceptionNames::DUPLICATE_EXCEPTION;
79
    }
80
    if ($exception instanceof UnorderedPhaseNumberException) {
81
      return ExceptionNames::UNORDERED_PHASE_NUMBER_EXCEPTION;
82
    }
83
    if ($exception instanceof ReferenceException) {
84
      return ExceptionNames::REFERENCE_EXCEPTION;
85
    }
86
    if ($exception instanceof PlayerAlreadyExists) {
87
      return ExceptionNames::PLAYER_ALREADY_EXISTS_EXCEPTION;
88
    }
89
    if ($exception instanceof ValidationException) {
90
      return ExceptionNames::VALIDATION_EXCEPTION;
91
    }
92
    return ExceptionNames::INTERNAL_EXCEPTION;
93
  }
94
95
  /**
96
   * Extracts the status and the message from the given exception and status code
97
   * @param Exception $exception the raised exception
98
   * @param string|null $statusCode the status code or null if unknown
99
   * @param  bool $printTrace if true a trace will be appended to the exception message
100
   * @return array containing the infos status and message
101
   */
102
  protected function getJsonMessage(Exception $exception, $statusCode = null, $printTrace = false)
103
  {
104
105
    $result = method_exists($exception, 'getJsonMessage') ? $exception->getJsonMessage() :
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method getJsonMessage() does only exist in the following sub-classes of Exception: Tfboe\FmLib\Exceptions\DuplicateException, Tfboe\FmLib\Exceptions\MethodNotExistingException, Tfboe\FmLib\Exceptions\PlayerAlreadyExists, Tfboe\FmLib\Exceptions\P...rtyNotExistingException, Tfboe\FmLib\Exceptions\ReferenceException, Tfboe\FmLib\Exceptions\U...redPhaseNumberException. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
106
      ['message' => $exception->getMessage()];
107
108
    if ($exception instanceof ValidationException) {
109
      $result["errors"] = $exception->errors();
110
    }
111
112
    if (!array_key_exists('status', $result)) {
113
      $result['status'] = $statusCode !== null ? $statusCode : "false";
114
    }
115
116
    if (!array_key_exists('name', $result)) {
117
      $result['name'] = $this->getExceptionName($exception);
118
    }
119
120
    if ($printTrace || env('APP_DEBUG') === true) {
121
      //attach trace back
122
      $result['trace'] = $exception->getTrace();
123
    }
124
125
    return $result;
126
  }
127
//</editor-fold desc="Protected Methods">
128
}
129