Skip to content

Instantly share code, notes, and snippets.

@Boorj
Last active April 23, 2019 12:41
Show Gist options
  • Save Boorj/71544518284885bdc01f90d0bd6596c5 to your computer and use it in GitHub Desktop.
Save Boorj/71544518284885bdc01f90d0bd6596c5 to your computer and use it in GitHub Desktop.
Open file in PHP editor
  1. create a route for accepting reqeust to open
  2. create a controller and call launchEditor() from out there
  3. fix link in twig/html
  4. it requires working server to accept requests, so launch the server.

note It uses ??-operator so it's PHP7.0+

<?php
/**
* launchEditor
* @see the reference is - https://github.com/yyx990803/launch-editor
* @param null $filename
* @param null $lineNumber
* @return string|null
*/
function launchEditor($filename = null, $lineNumber = null){
/** @see https://github.com/yyx990803/launch-editor for more */
function runPowerShellCommand($cmd){
return shell_exec('powershell -Command "' . $cmd . '"');
}
function guessEditor(){
$COMMON_EDITORS_WIN = [
'Brackets.exe',
'Code.exe',
'atom.exe',
'sublime_text.exe',
'notepad++.exe',
'clion.exe',
'clion64.exe',
'idea.exe',
'idea64.exe',
'phpstorm.exe',
'phpstorm64.exe',
'pycharm.exe',
'pycharm64.exe',
'rubymine.exe',
'rubymine64.exe',
'webstorm.exe',
'webstorm64.exe'
];
# getting list of processes, i.e. "exporer.exe \nchrome.exe \nphpstorm.exe \n"
$output = runPowerShellCommand('Get-WmiObject Win32_Process | select path');
$runningProcesses = explode("\n", $output);
foreach ($runningProcesses as $fullPath) {
$fullPath = trim($fullPath, " \r"); # in case if we have \r\n line separators
if (!$fullPath)
continue; # sometimes line's empty
$baseName = basename($fullPath);
# if file's in list of editors - return full executable path.
if (in_array($baseName, $COMMON_EDITORS_WIN)) {
return $fullPath;
}
}
return '';
}
$editor = guessEditor();
$filename = $filename ?? $_GET['filename'] ?? '';
$lineNumber = $lineNumber ?? $_GET['line'] ?? 1;
if (!($editor && $filename))
return null;
// $commandLine = sprintf('cmd.exe /C "%s" --line %s "%s"',
$commandLine = sprintf('"%s" --line %s "%s"',
$editor,
$lineNumber,
$filename
);
system($commandLine);
return $commandLine;
}
public function openEditorAction(Application $app) {
# launching only in dev environment
if (PHP_OS !== "WINNT")
throw new NotFoundHttpException("No such Page ;)");
$launched = launchEditor();
return "Launched $launched.";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment