Passed
Push — master ( abfb73...066355 )
by Cesar
38s queued 12s
created

ErrorHandler::then()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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