Handler::render()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 2
dl 0
loc 16
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace App\Exceptions;
4
5
use Exception;
6
use Illuminate\Http\Response;
7
use Illuminate\Auth\AuthenticationException;
8
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
9
use Bugsnag\BugsnagLaravel\BugsnagExceptionHandler as BugsnagExceptionHandler;
10
11
class Handler extends ExceptionHandler
12
{
13
    protected $dontReport = [
14
        \Illuminate\Auth\AuthenticationException::class,
15
        \Illuminate\Auth\Access\AuthorizationException::class,
16
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
17
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
18
        \Illuminate\Validation\ValidationException::class,
19
    ];
20
21
    public function report(Exception $e)
22
    {
23
        parent::report($e);
24
25
        if (app()->environment('production') && $this->shouldReport($e)) {
26
            app(BugsnagExceptionHandler::class)->report($e);
27
        }
28
    }
29
30
    public function render($request, Exception $e)
31
    {
32
        if ($this->isHttpException($e)) {
33
            return $this->renderHttpException($e);
0 ignored issues
show
Compatibility introduced by
$e of type object<Exception> is not a sub-type of object<Symfony\Component...xception\HttpException>. It seems like you assume a child class of the class Exception to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
34
        }
35
36
        if ($this->shouldntReport($e)) {
37
            return parent::render($request, $e);
38
        }
39
40
        if (config('app.debug')) {
41
            return $this->renderExceptionWithWhoops($e);
42
        }
43
44
        return parent::render($request, $e);
45
    }
46
47
    protected function renderExceptionWithWhoops(Exception $e): Response
48
    {
49
        $this->unsetSensitiveData();
50
51
        $whoops = new \Whoops\Run();
52
        $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler());
0 ignored issues
show
Documentation introduced by
new \Whoops\Handler\PrettyPageHandler() is of type object<Whoops\Handler\PrettyPageHandler>, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
53
54
        return new \Illuminate\Http\Response(
55
            $whoops->handleException($e),
0 ignored issues
show
Documentation introduced by
$e is of type object<Exception>, but the function expects a object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
56
            $e->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: Aws\Acm\Exception\AcmException, Aws\ApiGateway\Exception\ApiGatewayException, Aws\ApplicationAutoScali...ionAutoScalingException, Aws\ApplicationDiscovery...scoveryServiceException, Aws\Appstream\Exception\AppstreamException, Aws\AutoScaling\Exception\AutoScalingException, Aws\Batch\Exception\BatchException, Aws\Budgets\Exception\BudgetsException, Aws\CloudFormation\Excep...CloudFormationException, Aws\CloudFront\Exception\CloudFrontException, Aws\CloudHsm\Exception\CloudHsmException, Aws\CloudSearchDomain\Ex...udSearchDomainException, Aws\CloudSearch\Exception\CloudSearchException, Aws\CloudTrail\Exception\CloudTrailException, Aws\CloudWatchEvents\Exc...oudWatchEventsException, Aws\CloudWatchLogs\Excep...CloudWatchLogsException, Aws\CloudWatch\Exception\CloudWatchException, Aws\CodeBuild\Exception\CodeBuildException, Aws\CodeCommit\Exception\CodeCommitException, Aws\CodeDeploy\Exception\CodeDeployException, Aws\CodePipeline\Exception\CodePipelineException, Aws\CognitoIdentityProvi...entityProviderException, Aws\CognitoIdentity\Exce...ognitoIdentityException, Aws\CognitoSync\Exception\CognitoSyncException, Aws\ConfigService\Exception\ConfigServiceException, Aws\DataPipeline\Exception\DataPipelineException, Aws\DatabaseMigrationSer...grationServiceException, Aws\DeviceFarm\Exception\DeviceFarmException, Aws\DirectConnect\Exception\DirectConnectException, Aws\DirectoryService\Exc...rectoryServiceException, Aws\DynamoDbStreams\Exce...ynamoDbStreamsException, Aws\DynamoDb\Exception\DynamoDbException, Aws\Ec2\Exception\Ec2Exception, Aws\Ecr\Exception\EcrException, Aws\Ecs\Exception\EcsException, Aws\Efs\Exception\EfsException, Aws\ElastiCache\Exception\ElastiCacheException, Aws\ElasticBeanstalk\Exc...asticBeanstalkException, Aws\ElasticLoadBalancing...oadBalancingV2Exception, Aws\ElasticLoadBalancing...cLoadBalancingException, Aws\ElasticTranscoder\Ex...sticTranscoderException, Aws\ElasticsearchService...csearchServiceException, Aws\Emr\Exception\EmrException, Aws\Exception\AwsException, Aws\Firehose\Exception\FirehoseException, Aws\GameLift\Exception\GameLiftException, Aws\Glacier\Exception\GlacierException, Aws\Health\Exception\HealthException, Aws\Iam\Exception\IamException, Aws\ImportExport\Exception\ImportExportException, Aws\Inspector\Exception\InspectorException, Aws\IotDataPlane\Exception\IotDataPlaneException, Aws\Iot\Exception\IotException, Aws\KinesisAnalytics\Exc...nesisAnalyticsException, Aws\Kinesis\Exception\KinesisException, Aws\Kms\Exception\KmsException, Aws\Lambda\Exception\LambdaException, Aws\Lightsail\Exception\LightsailException, Aws\MachineLearning\Exce...achineLearningException, Aws\MarketplaceCommerceA...merceAnalyticsException, Aws\MarketplaceMetering\...tplaceMeteringException, Aws\OpsWorksCM\Exception\OpsWorksCMException, Aws\OpsWorks\Exception\OpsWorksException, Aws\Pinpoint\Exception\PinpointException, Aws\Polly\Exception\PollyException, Aws\Rds\Exception\RdsException, Aws\Redshift\Exception\RedshiftException, Aws\Rekognition\Exception\RekognitionException, Aws\Route53Domains\Excep...Route53DomainsException, Aws\Route53\Exception\Route53Exception, Aws\S3\Exception\PermanentRedirectException, Aws\S3\Exception\S3Exception, Aws\ServiceCatalog\Excep...ServiceCatalogException, Aws\Ses\Exception\SesException, Aws\Sfn\Exception\SfnException, Aws\Shield\Exception\ShieldException, Aws\Sms\Exception\SmsException, Aws\SnowBall\Exception\SnowBallException, Aws\Sns\Exception\SnsException, Aws\Sqs\Exception\SqsException, Aws\Ssm\Exception\SsmException, Aws\StorageGateway\Excep...StorageGatewayException, Aws\Sts\Exception\StsException, Aws\Support\Exception\SupportException, Aws\Swf\Exception\SwfException, Aws\WafRegional\Exception\WafRegionalException, Aws\Waf\Exception\WafException, Aws\WorkSpaces\Exception\WorkSpacesException, Aws\XRay\Exception\XRayException, Illuminate\Foundation\Ht...aintenanceModeException, 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...
57
            $e->getHeaders()
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 getHeaders() does only exist in the following sub-classes of Exception: Illuminate\Foundation\Ht...aintenanceModeException, 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...
58
        );
59
    }
60
61
    /*
62
     * Don't ever display sensitive data in Whoops pages.
63
     */
64
    protected function unsetSensitiveData()
65
    {
66
        foreach ($_ENV as $key => $value) {
67
            unset($_SERVER[$key]);
68
        }
69
70
        $_ENV = [];
71
    }
72
73
    /**
74
     * Convert an authentication exception into an unauthenticated response.
75
     *
76
     * @param \Illuminate\Http\Request                 $request
77
     * @param \Illuminate\Auth\AuthenticationException $e
78
     *
79
     * @return \Illuminate\Http\Response
80
     */
81
    protected function unauthenticated($request, AuthenticationException $e)
0 ignored issues
show
Unused Code introduced by
The parameter $e is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
82
    {
83
        if ($request->expectsJson()) {
84
            return response()->json(['error' => 'Unauthenticated.'], 401);
85
        }
86
87
        return redirect()->guest('login');
88
    }
89
}
90