HasProgressListener   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 47
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A onProgress() 0 5 1
A applyProgressListenerToFormat() 0 10 4
1
<?php
2
3
namespace ProtoneMedia\LaravelFFMpeg\Exporters;
4
5
use Closure;
6
use Evenement\EventEmitterInterface;
7
8
trait HasProgressListener
9
{
10
    /**
11
     * @var \Closure
12
     */
13
    protected $onProgressCallback;
14
15
    /**
16
     * @var float
17
     */
18
    protected $lastPercentage;
19
20
    /**
21
     * @var float
22
     */
23
    protected $lastRemaining = 0;
24
25
    /**
26
     * Setter for the callback.
27
     *
28
     * @param Closure $callback
29
     * @return self
30
     */
31
    public function onProgress(Closure $callback): self
32
    {
33
        $this->onProgressCallback = $callback;
34
35
        return $this;
36
    }
37
38
    /**
39
     * Only calls the callback if the percentage is below 100 and is different
40
     * from the previous emitted percentage.
41
     *
42
     * @param \Evenement\EventEmitterInterface $format
43
     * @return void
44
     */
45
    private function applyProgressListenerToFormat(EventEmitterInterface $format)
46
    {
47
        $format->removeAllListeners('progress');
48
49
        $format->on('progress', function ($media, $format, $percentage, $remaining = null, $rate = null) {
50
            if ($percentage !== $this->lastPercentage && $percentage < 100) {
51
                $this->lastPercentage = $percentage;
52
                $this->lastRemaining = $remaining ?: $this->lastRemaining;
53
54
                call_user_func($this->onProgressCallback, $this->lastPercentage, $this->lastRemaining, $rate);
55
            }
56
        });
57
    }
58
}
59