Editor::editFile()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
namespace Nubs\Sensible;
3
4
use Symfony\Component\Process\ProcessBuilder;
5
6
/**
7
 * Wraps the editor to execute it.
8
 */
9
class Editor
10
{
11
    /** @type string The editor command to use. */
12
    private $_editorCommand;
13
14
    /**
15
     * Initialize the editor command.
16
     *
17
     * @api
18
     * @param string $editorCommand The editor command to use.
19
     */
20
    public function __construct($editorCommand)
21
    {
22
        $this->_editorCommand = $editorCommand;
23
    }
24
25
    /**
26
     * Edit the given file using the symfony process builder to build the
27
     * symfony process to execute.
28
     *
29
     * @api
30
     * @param \Symfony\Component\Process\ProcessBuilder $processBuilder The
31
     *     process builder.
32
     * @param string $filePath The path to the file to edit.
33
     * @return \Symfony\Component\Process\Process The already-executed process.
34
     */
35
    public function editFile(ProcessBuilder $processBuilder, $filePath)
36
    {
37
        $proc = $processBuilder->setPrefix($this->_editorCommand)->setArguments([$filePath])->getProcess();
38
        $proc->setTty(true)->run();
39
40
        return $proc;
41
    }
42
43
    /**
44
     * Edit the given data using the symfony process builder to build the
45
     * symfony process to execute.
46
     *
47
     * @api
48
     * @param \Symfony\Component\Process\ProcessBuilder $processBuilder The
49
     *     process builder.
50
     * @param string $data The data to edit.
51
     * @return string The edited data (left alone if the editor returns a
52
     *     failure).
53
     */
54
    public function editData(ProcessBuilder $processBuilder, $data)
55
    {
56
        $filePath = tempnam(sys_get_temp_dir(), 'sensibleEditor');
57
        file_put_contents($filePath, $data);
58
59
        $proc = $this->editFile($processBuilder, $filePath);
60
        if ($proc->isSuccessful()) {
61
            $data = file_get_contents($filePath);
62
        }
63
64
        unlink($filePath);
65
66
        return $data;
67
    }
68
}
69