Completed
Push — master ( e88f06...475e3b )
by Peter
07:09
created

ExceptionHandler::handled()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 18
c 0
b 0
f 0
ccs 0
cts 18
cp 0
rs 8.8571
cc 5
eloc 10
nc 4
nop 3
crap 30
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: peter
5
 * Date: 15.06.18
6
 * Time: 14:48
7
 */
8
9
namespace Maslosoft\Manganel\Helpers;
10
11
12
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
13
use Exception;
14
use function json_decode;
15
use Maslosoft\Mangan\Events\Event;
16
use Maslosoft\Manganel\Events\ErrorEvent;
17
use Maslosoft\Manganel\Manganel;
18
use function str_replace;
19
20
class ExceptionHandler
21
{
22
23
	public static function getDecorated(Manganel $manganel, BadRequest400Exception $exception, $params)
24
	{
25
		// Throw previous exception,
26
		// as it holds more meaningful information
27
		$json = json_encode($params, JSON_PRETTY_PRINT);
28
29
		$msg = $exception->getMessage();
30
31
		$decoded = json_decode($msg);
32
		if (!empty($decoded) && !empty($decoded->error->root_cause[0]->reason))
33
		{
34
			$msg = $decoded->error->root_cause[0]->reason;
35
		}
36
37
		$prevMsg = '';
38
		$previous = $exception->getPrevious();
39
		if (!empty($previous))
40
		{
41
			$prevMsg = '(' . $previous->getMessage() . ')';
42
		}
43
44
		$params = [
45
			$msg . ' ' . $prevMsg,
46
			$manganel->indexId,
47
			$json
48
		];
49
50
51
		$message = vsprintf("Exception %s while querying `%s`: \n%s\n", $params);
52
		return new BadRequest400Exception($message, 400, $exception);
53
	}
54
55
	public static function handled(Exception $e, $model = null, $event = null)
56
	{
57
		if(empty($model))
58
		{
59
			return false;
60
		}
61
		if(empty($event))
62
		{
63
			return false;
64
		}
65
		$evt = new ErrorEvent($model);
66
		$evt->exception = $e;
67
		if(Event::hasHandler($model, $event) && Event::handled($model, $event, $evt))
68
		{
69
			return true;
70
		}
71
		return false;
72
	}
73
}