Passed
Push — main ( f0ef6e...5d2f0b )
by Daniel
13:27
created

FfmpegTranscoder::__invoke()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 9
rs 10
ccs 5
cts 5
cp 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Uxmp\Core\Component\Io\Transcoder;
6
7
use RuntimeException;
8
use Uxmp\Core\Component\Config\ConfigProviderInterface;
9
use Uxmp\Core\Component\Io\Lib\PopenWrapperInterface;
10
11
final class FfmpegTranscoder implements TranscoderInterface
12
{
13
    private ?string $file_path = null;
14
15 3
    public function __construct(
16
        private readonly ConfigProviderInterface $configProvider,
17
        private readonly PopenWrapperInterface $popenWrapper,
18
        private string $codec,
19
        private int $bitrate,
20
    ) {
21
    }
22
23 2
    public function setFilePath(string $file_path): self
24
    {
25 2
        $this->file_path = $file_path;
26 2
        return $this;
27
    }
28
29
    /**
30
     * @return resource
31
     */
32 2
    public function getHandle()
33
    {
34 2
        $transcodingConfig = $this->configProvider->getTranscodingConfig();
35
36 2
        if (!in_array($this->bitrate, $transcodingConfig['allowed_bitrates'], true)) {
37 1
            $this->bitrate = $transcodingConfig['bitrate'];
38
        }
39
40 2
        if (!in_array($this->codec, $transcodingConfig['allowed_codecs'], true)) {
41 1
            $this->codec = $transcodingConfig['codec'];
42
        }
43
44 2
        $command = sprintf(
45
            'ffmpeg -i %s -vn -nostats -ar 44100 -ac 2 -b:a %dk -f %s pipe:1 2>/dev/null',
46 2
            escapeshellarg((string)$this->file_path),
47 2
            $this->bitrate,
48 2
            escapeshellarg($this->codec),
49
        );
50
51 2
        $handle = $this->popenWrapper->run($command);
52
53 2
        if ($handle === null) {
54
            // throw dedicated exception
55 1
            throw new RuntimeException();
56
        }
57
58 1
        return $handle;
59
    }
60
}
61