Simple snippet for extracting the visual selection in Vim to a PHP variable.
vnoremap <leader>e :call PHPExtractVariable()<cr>
function! PHPExtractVariable()
let l:name = input("Name of new variable: $")
normal! gvx
execute "normal! i$".l:name
execute "normal! O$".l:name." = "
normal! pa;
endfunction
Let’s see an example:
<?php
if (empty($this->userRepository->findAllByStatus('a_really_cool_status', $someUselessParameter))) {
// some cool code because we didn't find anything
}
The condition is really long, you want to extract it. Just for readability, or because you’re accessing the value later in the code again.
- Select everything in the
if
’s parenthesis visualy (manually withv
or quickly withvib
). - Hit
<leader>e
- Enter a variable name, for example
noUserExists
- Press
<enter>
Result:
<?php
$noUserExists = empty($this->userRepository->findAllByStatus('a_really_cool_status', $someUselessParameter));
if ($noUserExists) {
// some cool code because we didn't find anything
}
Known issues
- doesn’t search for multiple occurences for selected portion