Completed
Pull Request — 1.x (#214)
by Yuu
05:10
created

VndErrorHandler   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 128
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 10
c 5
b 0
f 0
lcom 1
cbo 6
dl 0
loc 128
ccs 41
cts 41
cp 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B handle() 0 27 4
A getErrorPage() 0 4 2
A transfer() 0 8 1
A log() 0 10 1
A getLogRefId() 0 4 1
1
<?php
2
/**
3
 * This file is part of the BEAR.Package package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace BEAR\Package\Provide\Error;
8
9
use BEAR\AppMeta\AbstractAppMeta;
10
use BEAR\Package\Provide\Error\ErrorPage as CliErrorPage;
11
use BEAR\Resource\Code;
12
use BEAR\Resource\Exception\BadRequestException as BadRequest;
13
use BEAR\Resource\Exception\ResourceNotFoundException as NotFound;
14
use BEAR\Sunday\Extension\Error\ErrorInterface;
15
use BEAR\Sunday\Extension\Router\RouterMatch as Request;
16
use BEAR\Sunday\Extension\Transfer\TransferInterface;
17
use BEAR\Sunday\Provide\Error\ErrorPage;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, BEAR\Package\Provide\Error\ErrorPage.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
18
19
/**
20
 * vnd.error for BEAR.Package
21
 *
22
 * @see https://github.com/blongden/vnd.error
23
 */
24
class VndErrorHandler implements ErrorInterface
25
{
26
    /**
27
     * @var int
28
     */
29
    private $code;
30
31
    /**
32
     * @var array
33
     */
34
    private $body = ['message' => '', 'logref' => ''];
35
36
    /**
37
     * @var string
38
     */
39
    private $logDir;
40
41
    /**
42
     * @var ErrorPage
43
     */
44
    private $errorPage;
45
46
    /**
47
     * @var TransferInterface
48
     */
49
    private $responder;
50
51
    /**
52
     * @var string
53
     */
54
    private $lastErrorFile;
55
56
    /**
57
     * @var ExceptionAsString
58
     */
59
    private $exceptionString;
60
61 8
    public function __construct(AbstractAppMeta $appMeta, TransferInterface $responder)
62
    {
63 8
        $this->logDir = $appMeta->logDir;
64 8
        $this->lastErrorFile = $this->logDir . '/last_error.log';
65 8
        $this->responder = $responder;
66 8
        $this->exceptionString = new ExceptionAsString;
67 8
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 4
    public function handle(\Exception $e, Request $request)
73
    {
74 4
        $this->errorPage = $this->getErrorPage($e, $this->lastErrorFile);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getErrorPage($e, $this->lastErrorFile) can also be of type object<BEAR\Package\Provide\Error\ErrorPage>. However, the property $errorPage is declared as type object<BEAR\Sunday\Provide\Error\ErrorPage>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
75
76 4
        $isCodeError = array_key_exists($e->getCode(), (new Code)->statusText);
77 4
        $code = $isCodeError ? $e->getCode() : Code::ERROR;
78 4
        $message = $code . ' ' . (new Code)->statusText[$code];
79
        // Client error
80 4
        if (400 <= $code && $code < 500) {
81 2
            $this->log($e, $request);
82 2
            $this->code = $code;
83 2
            $this->body = [
84
                'message' => $message
85 2
            ];
86
87 2
            return $this;
88
        }
89
        // Server error
90 2
        $logRef = $this->log($e, $request);
91 2
        $this->code = $code;
92 2
        $this->body = [
93 2
            'message' => $message,
94
            'logref' => $logRef
95 2
        ];
96
97 2
        return $this;
98
    }
99
100
    /**
101
     * @param \Exception $e
102
     * @param string     $lastErrorFile
103
     *
104
     * @return \BEAR\Package\Provide\Error\ErrorPage|ErrorPage
105
     */
106 4
    private function getErrorPage(\Exception $e, $lastErrorFile)
107
    {
108 4
        return PHP_SAPI === 'cli' ? new CliErrorPage($this->exceptionString->summery($e, $lastErrorFile)) : new ErrorPage;
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114 4
    public function transfer()
115
    {
116 4
        $ro = $this->errorPage;
117 4
        $ro->code = $this->code;
118 4
        $ro->headers['content-type'] = 'application/vnd.error+json';
119 4
        $ro->body = $this->body;
120 4
        $this->responder->__invoke($ro, []);
121 4
    }
122
123
    /**
124
     * @param \Exception $e
125
     * @param Request    $request
126
     *
127
     * @return int logRef
128
     */
129 4
    private function log(\Exception $e, Request $request)
130
    {
131 4
        $logRefId = $this->getLogRefId($e);
132 4
        $logRefFile = sprintf('%s/e.%s.log', $this->logDir, $logRefId);
133 4
        $log = $this->exceptionString->detail($e, $request);
134 4
        file_put_contents($this->lastErrorFile, $log);
135 4
        file_put_contents($logRefFile, $log);
136
137 4
        return $logRefId;
138
    }
139
140
    /**
141
     * Return log ref id
142
     *
143
     * @param \Exception $e
144
     *
145
     * @return string
146
     */
147 4
    private function getLogRefId(\Exception $e)
148
    {
149 4
        return (string) crc32(get_class($e) . $e->getMessage() . $e->getFile() . $e->getLine());
150
    }
151
}
152