Surrounding text with a method call - php

I have a class that has two methods that are used often:self::foo() and self::bar().
I would like to surround text, mainly variables in other methods. I can do comments, if/else, try/catch, etc, but I can't with arbitrary method calls.
I don't even know if PHPStorm does this, honestly. Does anyone know how to do this?
UPDATE
I would like to take this:
function func() {
return $variable;
}
and make it this:
function func() {
return self::foo($variable);
}
or
function func() {
return this->bar($variable);
}

You can create and use Live Template that will do what you want (surround current selection with predefined template): separate template for each method call.
http://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Early+Access+Program -- the last section "Creating Surround Templates" is what you need in particular.

You can extract a function using WebStorm's refactoring tools.
Do do so, mark the code you want to have extracted and press Ctrl + Alt + M.
For more info, have a look at JetBrains' Website:
http://blog.jetbrains.com/webide/2011/05/extract-function-method-refactoring-for-php/
Edit: Thanks for the clarification. I am not aware of a refactoring tool that fulfills this particular need. However, if you have a lot of occurrences in one file, Search and Replace might be helpful.

Related

Rearrange common functions in specific order with PhpStorm

PhpStorm has a nice little rearrange feature, but I can't seem to get it to work.
I have a set of functions that my framework uses in every page. I want them to always be in the same order (and hopefully have 2 newlines between each one). For example:
class myClass {
function head() {}
function css() {}
function html() {}
function js() {}
}
I set up up my arrange tab under Settings > Editor > Code Style > PHP to look like this:
After doing this, clicking the Rearrange Code option still did nothing. I've also tried adding method to each one, like this:
It made no difference.
Is there a way to get PhpStorm to automatically rearrange functions in a user defined order (hopefully with 2 newlines in between each)?
You need to put the rules before the method - by modifiers (default) one.
This way, your methods will always come first and then PHPStorm will order the rest like it usually does. If they're at the end, all of the methods will already have been consumed by the default rule, so the remaining rules won't matter.
Also, you need to specify method as you did in your second example.
Then, using Rearrange Code should do it (I've just tested it).

Latte - call function in TPL (ideally with parameter) instead of variable

I decided to rewrite an older website that I made years ago and use templating system. I decided to use Latte, as its generating PHP files, which makes it really fast compared to systems that parse tpl every time. But I was not able to figure out, how to call a function with latte and get its result.
I am used to our custom company TPL system which can call any function and even pass parameters to it just by calling {function_name.param} or use function constants with {function::param}.
Is something like this possible purely in Latte (I am not using Nette or any other framework)? I do not want to call every single function in PHP and add it to array of parameters that TPL has to its disposal. That just makes it slower (yep I know I could use ifs in there and then ifs in TPL, but that's also an useless code duplication).
I want it to be able to call a function within class that's rendering the TPL (or its parent classes OFC) and return its output when I need it (if I even do need it), so I can avoid unnecessary calls to functions when initializing parameters for TPL parsing.
I tried to google quite a lot, but I didn't find anything useful.
I should also mention, that I am not going to use any framework at all, except Latte with Tracy and Tester for automatic testing. I do not want to use Nette or Symfony 2 etc. as the site is not that big and using whole framework would just make it even more complicated than it needs to be.
Thanks.
.
Ps.: Could somebody create tag for Latte?
You can simply call any php function this way:
{? echo 'hello'}
or in newer versions of Latte:
{php echo 'hello'}
Also, you can pass instances of Nette\Utils\Html (small lib separated from framework, full of great tools even for small apps) which will be directly rendered.
Or if you want to use own class rendering output directly, simply implement __toString() function using IHtmlString interface:
class MyOwnClassRenderableByLatte implements \Latte\Runtime\IHtmlString
{
function __toString()
{
return 'Hi';
}
}
Template sample including your later questions:
{php
// You can instantiate needed classes in one synoptical block
// in the head of template file or reather instantiate them
// outside of template and pass them as template variables
$a = new ClassA();
$b = new ClassB();
}
<div>{$a->someFunction()}</div>
<div>
{* Or you can instantiate class inplace this way,
but I wouldn't recommend it. BTW: This is Latte comment.
*}
{php (new ClassC())->otherFunction()}
</div>
Try to use something like this, its same as with javascript
{some code} //is for latte expression
{ some other code} //with space after first bracket its no more latte expression
Not sure if your TPL will handle it, but you will see
If it will work, you can use more imagination and use something like
{
some fluffy code
}

Create a PHP Class Outline

I am looking for a function or class that can effectively outline a class:
class MyClass{
/*
* Perhaps include the function comments
* in the function.
*/
function mainFunction(){
//Does Something
}
function functionWithArgs($arg1,$arg2=false){
//Does Something
//The function I want will give e the arguments w/default values
}
}
Is there a function or library in existence that can give me some kind of access to the information about this class, or even the file.
ex.
get_file_outline('fileWithAboveClass.php');
or
get_class_outline('MyClass');
Does anybody know of either, or know a way of easily writing this?
Take a look at the PHP Reflection API
//use the ReflectionClass to find out about MyClass
$classInfo = new ReflectionClass('MyClass');
//then you can find out pretty much anything you want to know...
$methods = $classInfo->getMethods();
var_dump($methods);
//you can even extract your comments, e.g.
$comment=$classInfo->getMethod('mainFunction')->getDocComment();
Note that for the comment extraction to work, they have to be formatted like PHPDoc / Doxygen comments, and begin with an opening /**
There's also a command line option available for inspecting functions and classes.
$ php --rc DateTime
will give you all the details about the DateTime-class, while
$ php --rf in_array
will give you the arguments of the "in_array" function.
If you're using the Terminal when coding it can be quite handy to use instead of looking it up in the PHP Manual all the time ;)

Get a called functions list in PHP

In PHP, get_included_files() returns an array with the names of included files.
In a similar fashion, is there any way to get an array with the names of called functions with parameters?
In this way, Is any way to get an array with the names of called functions with parameters?
No.
What you can do is a debug_backtrace() which will show all the function calls (with parameters) that lead to the execution of the line you are doing the backtrace from (the "call stack"), but that's different from all functions that were ever called in the script.
What do you want to do? Maybe there's a different approach.
I was searching for something similar and found xdebug's tracing very useful.
Here's an example of how it could look like:
http://devzone.zend.com/1135/tracing-php-applications-with-xdebug/
I was trying to achieve what you want and finally came up with an reasonable solution.
Make a class named Debug and include that above every file you want to debug in. Build yourself a function that prints nicely the information stored in $calls.
class Debug {
private static $calls;
public static function log($message = null)
{
if(!is_array(self::$calls))
self::$calls = array();
$call = debug_backtrace(false);
$call = (isset($call[1]))?$call[1]:$call[0];
$call['message'] = $message;
array_push(self::$calls, $call);
}
}
Call this function everytime you declare a function first line in the functionbody: Debug::log($message(optional) )
Not that I'm aware.
You can however use debug_backtrace to get the currently active function/method hierarchy.
I don't think there's a way to do what you want. Sorry.
The closest I can get is the function_exists() function, which will tell you whether a specific function has been loaded.
What exactly do you want to achieve here? I can't see a use case (outside of a php_info() type screen) that would require a list of available functions.
You will have to install it as an extension, but a profiler like XHProf will give you a breakdown of which functions are called and how long they take, as well as a callgraph.
XHProf or Webgrind/KCachegrind will show you the functions called, but not their parameters.
You could also use get_defined_functions, which gives you a list of all functions defined. But it won't show you which functions have actually been called, and with what parameters.
If you really need to know the parameters, I don't know of any tools other than a custom logger like the one Henze provided in his answer.

Extracting function declarations from a PHP file

I'm looking to create an on-site API reference for my framework and application.
Basically, say I have a class file model.class.php:
class Model extends Object {
... code here ...
// Separates results into pages.
// Returns Paginator object.
final public function paginate($perpage = 10) {
... more code here ...
}
}
and I want to be able to generate a reference that my developers can refer to quickly in order to know which functions are available to be called. They only need to see the comments directly above each function and the declaration line. Something like this (similar to a C++ header file):
// Separates results into pages.
// Returns Paginator object.
final public function paginate($perpage = 10);
I've done some research and this answer looked pretty good (using Reflection classes), however, I'm not sure how I can keep the comments in.
Any ideas?
I want to keep the current comment formatting. Myself and the people who are working on the code hate the verbosity associated with PHPDocumentor. Not to mention a comment-rewrite of the entire project would take years, so I want to preserve just the // comments in plaintext.
Why don't you just run PHPDocumenter on the code?
PHPDoc is identical to JavaDoc, and will retain all the parameters and comments in the docblock above the function.
EDIT: Since you don't want PHPDoc, I think it would probably be easiest to write a RegEx parser to do it, since Reflection won't provide you with any surrounding comments.
PHP code to get the comment:
if(preg_match("#//(.+)$#",$line,$match)>0)
{
echo "Comment is: ".$match[1];
}
this is what phpdoc is for. you comment your code a specific way, following certain rules, and when you're done you run your code through a parser. It outputs exactly what you're looking for.

Categories