Passed
Push — master ( 4f6f8e...2905b8 )
by Cesar
01:59
created

ErrorHandler::sucessfull()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 2
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Cesargb\Log;
4
5
use Cesargb\Log\Exceptions\RotationFailed;
6
use Closure;
7
use Throwable;
8
9
trait ErrorHandler
10
{
11
    private ?Closure $thenCallback = null;
12
13
    private ?Closure $catchCallable = null;
14
15
    private ?Closure $finallyCallback = null;
16
17
    private ?string $_filename = null;
18
19
    /**
20
     * Function that will be executed when the rotation is successful.
21
     * The first argument will be the name of the destination file and
22
     * the second the name of the rotated file.
23
     */
24
    public function then(Closure $callable): self
25
    {
26
        $this->thenCallback = $callable;
27
28
        return $this;
29
    }
30
31
    /**
32
     * Call function if roteted catch any Exception.
33
     */
34
    public function catch(Closure $callable): self
35
    {
36
        $this->catchCallable = $callable;
37
38
        return $this;
39
    }
40
41
    /**
42
     * Function that will be executed when the process was finished.
43
     */
44
    public function finally(Closure $callable): self
45
    {
46
        $this->finallyCallback = $callable;
47
48
        return $this;
49
    }
50
51
    protected function setFilename(string $filename): void
52
    {
53
        $this->_filename = $filename;
54
    }
55
56
    private function successful(string $filenameSource, ?string $filenameRotated): void
57
    {
58
        $this->finished('successful', $filenameSource);
59
60
        if (is_null($this->thenCallback) || is_null($filenameRotated)) {
61
            return;
62
        }
63
64
        call_user_func($this->thenCallback, $filenameRotated, $filenameSource);
65
    }
66
67
    protected function exception(Throwable $exception): self
68
    {
69
        $this->finished($exception->getMessage(), $this->_filename);
70
71
        if ($this->catchCallable) {
72
            call_user_func($this->catchCallable, $this->convertException($exception));
73
        } else {
74
            throw $this->convertException($exception);
75
        }
76
77
        return $this;
78
    }
79
80
81
    protected function finished(string $message, ?string $filenameSource): void
82
    {
83
        if (is_null($this->finallyCallback)) {
84
            return;
85
        }
86
87
        call_user_func($this->finallyCallback, $message, $filenameSource);
88
    }
89
90
    private function convertException(Throwable $exception): RotationFailed
91
    {
92
        return new RotationFailed(
93
            $exception->getMessage(),
94
            $exception->getCode(),
95
            $exception->getPrevious(),
96
            $this->_filename
97
        );
98
    }
99
}
100