Completed
Push — master ( 0042b2...b1b9f4 )
by Radu
01:49
created

App::logError()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 23
rs 9.4222
cc 5
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WebServCo\Framework;
6
7
/*
8
An example App implementation.
9
Can be copied or extended by projects.
10
Custom functionality in this class: add a log when an error occurs.
11
*/
12
class App extends Application
13
{
14
15
    /**
16
     * Handle CLI errors
17
     *
18
     * @param array<string,mixed> $errorInfo
19
     */
20
    protected function haltCli(array $errorInfo = []): bool
21
    {
22
        $this->logError($errorInfo, true);
23
        return parent::haltCli($errorInfo);
24
    }
25
26
    /**
27
     * Handle HTTP errors.
28
     *
29
     * @param array<string,mixed> $errorInfo
30
     */
31
    protected function haltHttp(array $errorInfo = []): bool
32
    {
33
        $this->logError($errorInfo, false);
34
        return parent::haltHttp($errorInfo);
35
    }
36
37
    /**
38
    * @param array<string,mixed> $errorInfo
39
    */
40
    protected function logError(array $errorInfo, bool $isCli = false): void
41
    {
42
        $logger = new \WebServCo\Framework\Log\FileLogger(
43
            \sprintf('error%s', $isCli ? 'CLI' : ''),
44
            $this->config()->get('app/path/log'),
45
        );
46
        $errorMessage = \sprintf('Error: %s in %s:%s', $errorInfo['message'], $errorInfo['file'], $errorInfo['line']);
47
        if ($errorInfo['exception'] instanceof \Exception) {
48
            $previous = $errorInfo['exception']->getPrevious();
49
            if ($previous instanceof \Exception) {
0 ignored issues
show
introduced by
$previous is always a sub-type of Exception.
Loading history...
50
                do {
51
                    $errorMessage .= \sprintf(
52
                        '%sPrevious: %s in %s:%s',
53
                        \PHP_EOL,
54
                        $previous->getMessage(),
55
                        $previous->getFile(),
56
                        $previous->getLine(),
57
                    );
58
                // phpcs:ignore SlevomatCodingStandard.ControlStructures.AssignmentInCondition.AssignmentInCondition
59
                } while ($previous = $previous->getPrevious());
60
            }
61
        }
62
        $logger->error($errorMessage, $errorInfo);
63
    }
64
}
65