Completed
Push — dev ( 088902...57261c )
by Matej
04:35
created

Scp::copyFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.004

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 15
ccs 9
cts 10
cp 0.9
rs 9.4286
cc 2
eloc 9
nc 2
nop 3
crap 2.004
1
<?php
2
3
namespace Velikonja\LabbyBundle\Remote;
4
5
use Symfony\Component\Console\Output\OutputInterface;
6
use Symfony\Component\Process\Process;
7
use Symfony\Component\Process\ProcessBuilder;
8
9
class Scp
10
{
11
    /**
12
     * @var array
13
     */
14
    private $config;
15
16
    /**
17
     * @var ProcessBuilder
18
     */
19
    private $processBuilder;
20
21
    /**
22
     * @param array               $config
23
     * @param int                 $timeout
24
     * @param string|null         $executable
25
     * @param null|ProcessBuilder $processBuilder
26
     */
27 4
    public function __construct(array $config, $timeout = 60, $executable = null, ProcessBuilder $processBuilder = null)
28
    {
29 4
        $this->config = $config;
30
31 4
        if (! $executable) {
32 4
            $executable = '/usr/bin/scp';
33
        }
34
35 4
        if (! $processBuilder) {
36 4
            $processBuilder = new ProcessBuilder();
37
        }
38
39
        $processBuilder
40 4
            ->setTimeout($timeout)
41 4
            ->setPrefix($executable);
42
43 4
        $this->processBuilder = $processBuilder;
44 4
    }
45
46
    /**
47
     * @param string               $src
48
     * @param string               $dst
49
     * @param null|OutputInterface $output
50
     *
51
     * @throws \Exception
52
     */
53 3
    public function copyFile($src, $dst, OutputInterface $output = null)
54
    {
55 3
        $process = $this->processBuilder
56 3
            ->add($this->config['hostname'] . ':' . $src)
57 3
            ->add($dst)
58 3
            ->getProcess();
59
60 3
        $process->run(
61 3
            $this->getCallback($output)
62
        );
63
64 3
        if (! $process->isSuccessful()) {
65
            throw new \Exception($process->getErrorOutput());
66
        }
67 3
    }
68
69
    /**
70
     * @param OutputInterface|null $output
71
     *
72
     * @return \Closure|null
73
     */
74 3
    private function getCallback(OutputInterface $output = null)
75
    {
76 3
        $callback = null;
77
78 3
        if ($output) {
79 3
            $callback = function ($type, $buffer) use ($output) {
80
                if (Process::ERR === $type) {
81
                    $output->writeln("<error>$buffer</error>");
82
                } else {
83
                    $output->writeln($buffer);
84
                }
85 3
            };
86
        }
87
88 3
        return $callback;
89
    }
90
}
91