Completed
Push — version-4 ( b70e7e )
by Tyler
10:17
created

Notifier::wrapValueInClosure()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 8
rs 9.4285
c 1
b 0
f 0
ccs 3
cts 3
cp 1
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Tylercd100\LERN\Components;
4
5
use Exception;
6
use Monolog\Handler\HandlerInterface;
7
use Monolog\Logger;
8
use Tylercd100\LERN\Exceptions\NotifierFailedException;
9
use Tylercd100\Notify\Drivers\FromConfig as Notify;
10
use View;
11
12
class Notifier extends Component
13
{
14
    protected $config;
15
    protected $log;
16
    protected $messageCb;
17
    protected $subjectCb;
18
    protected $contextCb;
19
20
    /**
21
     * You can provide a Monolog Logger instance to use in the constructor
22
     * @param Logger|null $log Logger instance to use
23
     */
24 63
    public function __construct(Logger $log = null)
25
    {
26 63
        if ($log === null) {
27 63
            $log = new Logger(config('lern.notify.channel'));
28 63
        }
29
30 63
        $this->config = config('lern.notify');
31 63
        $this->log = $log;
32 63
    }
33
34
    /**
35
     * Transforms a value into a closure that returns itself when called
36
     * @param  callable|string $cb The value that you want to wrap in a closure
37
     * @return callable
38
     */
39 15
    private function wrapValueInClosure($cb)
40
    {
41 15
        if (is_callable($cb)) {
42 9
            return $cb;
43
        } else {
44
            return function () use ($cb) { return $cb; };
45
        }
46
    }
47
48
    /**
49
     * Set a string or a closure to be called that will generate the message body for the notification
50
     * @param callable|string $cb A closure or string that will be set for the message
51
     * @return $this
52
     */
53 6
    public function setMessage($cb)
54
    {
55 6
        $this->messageCb = $this->wrapValueInClosure($cb);
56 6
        return $this;
57
    }
58
59
    /**
60
     * Returns the result of the message closure
61
     * @param  Exception $e The Exception instance that you want to build the message around
62
     * @return string       The message string
63
     */
64 21
    public function getMessage(Exception $e)
65
    {
66 21
        if (!empty($this->config["view"])) {
67 15
            return View::make($this->config["view"], ["exception" => $e])->render();
68 6
        } elseif (is_callable($this->messageCb)) {
69 6
            return $this->messageCb->__invoke($e);
70
        } else {
71
            $msg = get_class($e)." was thrown! \n".$e->getMessage();
72
            if ($this->config['includeExceptionStackTrace'] === true) {
73
                $msg .= "\n\n".$e->getTraceAsString();
74
            }
75
            return $msg;
76
        }
77
    }
78
79
    /**
80
     * Set a string or a closure to be called that will generate the subject line for the notification
81
     * @param callable|string $cb A closure or string that will be set for the subject line
82
     * @return $this
83
     */
84 6
    public function setSubject($cb)
85
    {
86 6
        $this->subjectCb = $this->wrapValueInClosure($cb);
87 6
        return $this;
88
    }
89
90
    /**
91
     * Returns the result of the subject closure
92
     * @param  Exception $e The Exception instance that you want to build the subject around
93
     * @return string       The subject string
94
     */
95 18
    public function getSubject(Exception $e)
96
    {
97 18
        if (is_callable($this->subjectCb)) {
98 6
            return $this->subjectCb->__invoke($e);
99
        } else {
100 12
            return get_class($e);
101
        }
102
    }
103
104
    /**
105
     * Set an array or a closure to be called that will generate the context array for the notification
106
     * @param callable|array $cb A closure or array that will be set for the context
107
     * @return $this
108
     */
109 3
    public function setContext($cb)
110
    {
111 3
        $this->contextCb = $this->wrapValueInClosure($cb);
112 3
        return $this;
113
    }
114
115
    /**
116
     * Returns the result of the context closure
117
     * @param  Exception $e The Exception instance that you want to build the context around
118
     * @return array        The context array
119
     */
120 15
    public function getContext(Exception $e, $context = [])
121
    {
122
        //This needs a better solution. How do I set specific context needs for different drivers?
123 15
        if (in_array('pushover', $this->config['drivers'])) {
124 12
            $context['sound'] = $this->config['pushover']['sound'];
125 12
        }
126
127
        // Call the callback or return the default
128 15
        if (is_callable($this->contextCb)) {
129 3
            return $this->contextCb->__invoke($e, $context);
130
        } else {
131 12
            return $context;
132
        }
133
    }
134
135
    /**
136
     * Pushes on another Monolog Handler
137
     * @param  HandlerInterface $handler The handler instance to add on
138
     * @return Notifier                  Returns this
139
     */
140 6
    public function pushHandler(HandlerInterface $handler) {
141 6
        $this->log->pushHandler($handler);
142 6
        return $this;
143
    }
144
145
    /**
146
     * Triggers the Monolog Logger instance to log an error to all handlers
147
     * @param  Exception $e The exception to use
148
     * @param  array $context Additional information that you would like to pass to Monolog
149
     * @return bool
150
     * @throws NotifierFailedException
151
     */
152 15
    public function send(Exception $e, array $context = [])
153
    {
154 15
        if ($this->shouldntHandle($e)) {
155 3
            return false;
156
        }
157
158 12
        $message = $this->getMessage($e);
159 12
        $subject = $this->getSubject($e);
160 12
        $context = $this->getContext($e, $context);
161
162
        try {
163 12
            $notify = new Notify($this->config, $this->log, $subject);
164
165 12
            $level = (array_key_exists('log_level', $this->config) && !empty($this->config['log_level']))
166 12
                ? $this->config['log_level']
167 12
                : 'critical';
168
169 12
            $notify->{$level}($message, $context);
170
171 9
            return true;
172 3
        } catch (Exception $e) {
173 3
            $code = (is_int($e->getCode()) ? $e->getCode() : 0);
174 3
            throw new NotifierFailedException($e->getMessage(), $code, $e);
175
        }
176
    }
177
}
178