Completed
Pull Request — 1.x (#214)
by Yuu
03:24 queued 55s
created

VndErrorHandler::handle()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 27
ccs 12
cts 12
cp 1
rs 8.5806
cc 4
eloc 17
nc 4
nop 2
crap 4
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\Sunday\Extension\Error\ErrorInterface;
13
use BEAR\Sunday\Extension\Router\RouterMatch as Request;
14
use BEAR\Sunday\Extension\Transfer\TransferInterface;
15
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...
16
17
/**
18
 * vnd.error for BEAR.Package
19
 *
20
 * @see https://github.com/blongden/vnd.error
21
 */
22
class VndErrorHandler implements ErrorInterface
23
{
24
    /**
25
     * @var int
26
     */
27
    private $code;
28
29
    /**
30
     * @var array
31
     */
32
    private $body = ['message' => '', 'logref' => ''];
33
34
    /**
35
     * @var string
36
     */
37
    private $logDir;
38
39
    /**
40
     * @var ErrorPage
41
     */
42
    private $errorPage;
43
44
    /**
45
     * @var TransferInterface
46
     */
47
    private $responder;
48
49
    /**
50
     * @var string
51
     */
52
    private $lastErrorFile;
53
54
    /**
55
     * @var ExceptionAsString
56
     */
57
    private $exceptionString;
58
59 8
    public function __construct(AbstractAppMeta $appMeta, TransferInterface $responder)
60
    {
61 8
        $this->logDir = $appMeta->logDir;
62 8
        $this->lastErrorFile = $this->logDir . '/last_error.log';
63 8
        $this->responder = $responder;
64
        $this->exceptionString = new ExceptionAsString;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70 4
    public function handle(\Exception $e, Request $request)
71
    {
72
        $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...
73
74
        $isCodeError = array_key_exists($e->getCode(), (new Code)->statusText);
75 1
        $code = $isCodeError ? $e->getCode() : Code::ERROR;
76
        $message = $code . ' ' . (new Code)->statusText[$code];
77
        // Client error
78 4
        if (400 <= $code && $code < 500) {
79
            $this->log($e, $request);
80 2
            $this->code = $code;
81 2
            $this->body = [
82
                'message' => $message
83 2
            ];
84
85 2
            return $this;
86
        }
87
        // Server error
88
        $logRef = $this->log($e, $request);
89 2
        $this->code = $code;
90 2
        $this->body = [
91
            'message' => $message,
92
            'logref' => $logRef
93 2
        ];
94
95 2
        return $this;
96 4
    }
97
98
    /**
99
     * @param \Exception $e
100
     * @param string     $lastErrorFile
101
     *
102
     * @return \BEAR\Package\Provide\Error\ErrorPage|ErrorPage
103
     */
104 4
    private function getErrorPage(\Exception $e, $lastErrorFile)
105
    {
106
        return PHP_SAPI === 'cli' ? new CliErrorPage($this->exceptionString->summery($e, $lastErrorFile)) : new ErrorPage;
107 4
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112 4
    public function transfer()
113
    {
114 4
        $ro = $this->errorPage;
115 4
        $ro->code = $this->code;
116 4
        $ro->headers['content-type'] = 'application/vnd.error+json';
117 4
        $ro->body = $this->body;
118
        $this->responder->__invoke($ro, []);
119 4
    }
120
121
    /**
122
     * @param \Exception $e
123
     * @param Request    $request
124
     *
125
     * @return int logRef
126
     */
127 4
    private function log(\Exception $e, Request $request)
128
    {
129
        $logRefId = $this->getLogRefId($e);
130
        $logRefFile = sprintf('%s/e.%s.log', $this->logDir, $logRefId);
131
        $log = $this->exceptionString->detail($e, $request);
132
        file_put_contents($this->lastErrorFile, $log);
133
        file_put_contents($logRefFile, $log);
134
135 4
        return $logRefId;
136 4
    }
137
138
    /**
139
     * Return log ref id
140
     *
141
     * @param \Exception $e
142
     *
143
     * @return string
144
     */
145 4
    private function getLogRefId(\Exception $e)
146
    {
147
        return (string) crc32(get_class($e) . $e->getMessage() . $e->getFile() . $e->getLine());
148 4
    }
149
}
150