Completed
Push — master ( a4b5d2...4e0c78 )
by yuuki
8s
created

LogExceptionsInterceptor::invoke()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 25
rs 8.5806
cc 4
eloc 15
nc 4
nop 1
1
<?php
2
3
/**
4
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10
 * THE SOFTWARE.
11
 *
12
 * This software consists of voluntary contributions made by many individuals
13
 * and is licensed under the MIT license.
14
 *
15
 * Copyright (c) 2015-2016 Yuuki Takezawa
16
 *
17
 */
18
namespace Ytake\LaravelAspect\Interceptor;
19
20
use Illuminate\Log\Writer;
21
use Ray\Aop\MethodInvocation;
22
use Ray\Aop\MethodInterceptor;
23
use Ytake\LaravelAspect\Annotation\AnnotationReaderTrait;
24
25
/**
26
 * Class LogExceptionsInterceptor
27
 */
28
class LogExceptionsInterceptor extends AbstractLogger implements MethodInterceptor
29
{
30
    use AnnotationReaderTrait;
31
32
    /**
33
     * @param MethodInvocation $invocation
34
     *
35
     * @return object
36
     * @throws \Exception
37
     */
38
    public function invoke(MethodInvocation $invocation)
39
    {
40
        try {
41
            $result = $invocation->proceed();
42
        } catch (\Exception $exception) {
43
            /** @var \Ytake\LaravelAspect\Annotation\LogExceptions $annotation */
44
            $annotation = $this->reader->getMethodAnnotation($invocation->getMethod(), $this->annotation);
45
46
            if ($exception instanceof $annotation->expect) {
47
                $logFormat = $this->logFormatter($annotation, $invocation);
48
                $logger = app('Psr\Log\LoggerInterface');
49
                if ($logger instanceof Writer) {
50
                    $logger = $logger->getMonolog();
51
                }
52
                /** Monolog\Logger */
53
                $logFormat['context']['code'] = $exception->getCode();
54
                $logFormat['context']['error_message'] = $exception->getMessage();
55
                $logger->log($logFormat['level'], $logFormat['message'], $logFormat['context']);
56
            }
57
            throw $exception;
58
        }
59
        // @codeCoverageIgnoreStart
60
        return $result;
61
        // @codeCoverageIgnoreEnd
62
    }
63
}
64