ErrorHandlerTrait::logException()   B
last analyzed

Complexity

Conditions 7
Paths 21

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
nc 21
nop 1
dl 0
loc 32
ccs 17
cts 17
cp 1
crap 7
rs 8.4746
c 0
b 0
f 0
1
<?php
2
/**
3
 * Error Handler allows errors to be logged to the audit_error table.
4
 */
5
6
namespace bedezign\yii2\audit\components\base;
7
8
use bedezign\yii2\audit\Audit;
9
use bedezign\yii2\audit\models\AuditError;
10
use bedezign\yii2\audit\panels\ErrorPanel;
11
use Exception;
12
use Yii;
13
14
/**
15
 * ErrorHandlerTrait
16
 * @package bedezign\yii2\audit\components\base
17
 */
18
trait ErrorHandlerTrait
19
{
20
    /**
21
     * @param Exception $exception
22
     */
23 33
    public function logException($exception)
24
    {
25
        try {
26
            $isMemoryError = strncmp($exception->getMessage(), 'Allowed memory size of', 22) === 0;
27 33
            /** @var Audit $audit */
28
            $audit = Audit::getInstance();
29 33
            if (!$audit && !$isMemoryError) {
30 33
                // Only attempt to load the module if this isn't an out of memory error, not enough room otherwise
31
                $audit = \Yii::$app->getModule(Audit::findModuleIdentifier());
32 6
            }
33 6
            if (!$audit) {
34 33
                throw new \Exception('Audit module cannot be loaded');
35 6
            }
36
37
            // Fake an actionEvent so we can use the track/ignore functionality using the originally requested route:
38 27
            $event = (object) ['action' => ['uniqueId' => Yii::$app->requestedRoute]];
39 27
            if ($audit->shouldTrack($event, true)) {
40
                $entry = $audit->getEntry(!$isMemoryError);
41 24
                if ($entry) {
42 24
                    /** @var ErrorPanel $errorPanel */
43 24
                    $errorPanel = $audit->getPanel($audit->findPanelIdentifier(ErrorPanel::className()));
44 24
                    $errorPanel->log($entry->id, $exception);
45
                    $entry->finalize();
46 33
                }
47
            }
48
49
        } catch (\Exception $e) {
50 33
            // if we catch an exception here, let it slide, we don't want recursive errors killing the script
51 33
        }
52
53
        parent::logException($exception);
54
    }
55
}