-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathEditorHelper.php
106 lines (84 loc) · 2.43 KB
/
EditorHelper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
/*
* This file is part of the PHPCR Shell package
*
* (c) Daniel Leech <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace PHPCR\Shell\Console\Helper;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Filesystem\Filesystem;
/**
* Helper for launching external editor.
*
* @author Daniel Leech <[email protected]>
*/
class EditorHelper extends Helper
{
/**
* Launch an external editor and open a temporary
* file containing the given string value.
*
* An file extension can be provided which will be appended
* to the name of the temporary file, providing a type hint
* to the editor.
*
* @param string $string
* @param string $extension
*
* @return string
*/
public function fromString($string, $extension = null)
{
$fs = new Filesystem();
$dir = sys_get_temp_dir().DIRECTORY_SEPARATOR.'phpcr-shell';
if (!file_exists($dir)) {
$fs->mkdir($dir);
}
$tmpName = tempnam($dir, '');
if ($extension) {
$tmpName .= '.'.$extension;
}
file_put_contents($tmpName, $string);
$editor = getenv('EDITOR');
if (!$editor) {
throw new \RuntimeException('No EDITOR environment variable set.');
}
system($editor.' '.$tmpName.' > `tty`');
$contents = file_get_contents($tmpName);
$fs->remove($tmpName);
return $contents;
}
public function fromStringWithMessage($string, $message, $messagePrefix = '# ', $extension = null)
{
if (null !== $message) {
$message = explode("\n", $message);
foreach ($message as $line) {
$source[] = $messagePrefix.$line;
}
$source = implode("\n", $source).PHP_EOL;
} else {
$source = '';
}
$source .= $string;
$res = $this->fromString($source, $extension);
$res = explode("\n", $res);
$line = current($res);
while (str_starts_with($line, $messagePrefix)) {
$line = next($res);
}
$out = [];
while ($line) {
$out[] = $line;
$line = next($res);
}
return implode("\n", $out);
}
public function getName(): string
{
return 'editor';
}
}