I am developing an application in Laravel 5, I have a test file which extends from TestCase.php, I need to call the phpcs command in my file
class MyTest extends TestCase {
public function testFunction()
{
//here I need to call the phpcs command
}
}
In te examples here http://laravel.com/docs/5.0/testing I just found the this->call function, which I don't think is the proper choice for me, since it is returning a response object, what is the right way to do it? which Class and functions should I use to to run a command-line inside this class I also need to have the result of the command in a variable
I don't Laravel has something built in for calling the command line. However it doesn't really need to because you can simply use the exec() function. Basically something like this:
public function testFunction()
{
exec('phpcs', $output);
echo $output[0]; // output line 1
}
As second argument you can pass a variable that will contain every line of the output as an array. The exec() function itself returns the last line from the output as string. (Especially useful when running single line commands like php -v)
Related
namespace Admin\Shell;
use Cake\Console\Shell;
class AdminAlertShell extends Shell{
...
...
}
Here 'Admin' is plugin, So I created this file inside the plugins folder structure.
File path : /plugins/Admin/src/Shell/AdminAlertShell.php
Tried to run this in CLI
bin/cake admin_alert
But an exception throws
Exception: Unknown command cake admin_alert. Run cake --help to get the list of valid commands. in [localpath/vendor/cakephp/cakephp/src/Console/CommandRunner.php, line 346]
It was working. But I don't know what happened to this. I had upgraded cakephp 3.5 to 3.7. But, I am not sure this caused the issue.
I just tracked down the source of the issue in my project.
Inside my plugin there was a file: src/Plugin.php
Inside this class there was the following lines of code:
/**
* #inheritDoc
*/
public function console(CommandCollection $commands): CommandCollection
{
// Add console commands here.
return $commands;
}
This was probably generated via bake.
I saw that the parent was not called. In the path is added in the parent.
Change this method to look like this:
/**
* #inheritDoc
*/
public function console(CommandCollection $commands): CommandCollection
{
// Add console commands here.
$commands = parent::console($commands);
return $commands;
}
Now the parent is called and the path is added to the command collection.
As a side note I also see the middleware is not calling its parent.
Think it would be a good idea to fix that one aswell.
As an alternative you can just clear out the class and all defaults should be used.
Hope this saves someone the hours it cost me to figure this one out.
So here is my issue. I'm trying to create function, which goes on straight away, but also have second exec output, which goes after let's say completing loop.
I tried to make this work with this: thread i googled.
However my issue is when i tried doing it with accepted answer provided i got this error:
E0434 a reference of type "TEnumAsByte<EMyEnum> &" (not const-qualified) cannot be initialized with a value of type "EMyEnum"
Going furthere below there is second answer, which work but it always goes off form last possible pin.In case I show below it always fire "FinishOutput". Is there any way i can force code to output from both pins i provide? Here is how it looks in my code:
.h file
UENUM(BlueprintType)
enum class EMyEnum : uint8
{
Output,
FinishOutput
};
UFUNCTION(BLueprintCallable, Category = "Test", Meta = (ExpandEnumAsExecs = "Branches"))
static void OutputTest(TEnumAsByte<EMyEnum>& Branches);
.cpp file
void UAudioController::OutputTest(TEnumAsByte<EMyEnum>& Branches)
{
Branches = EMyEnum::Output;
//some code to execute before second output
Branches = EMyEnum::FinishOutput;
}
I would make a Macro since it can have multiple Exec outputs. This is in blueprint, not code.
typical debugging pattern:
class Button : public MyBaseViewClass
{
...
};
....
void MyBaseViewClass::Resized()
{
//<---- here I want to stop in case MyBaseViewClass is really a Button, but not a ScrollBar, Checkbox or something else. I.e. I want a breakpoint condition on a dynamic (most derived) type
}
trivial approaches like a breakpoint on strstr(typeid(*this).name(), "Button") don't work because on typeid lldb console tells:
(lldb) p typeid(*this)
error: you need to include <typeinfo> before using the 'typeid' operator
error: 1 errors parsing expression
surely #include in console before making the call doesn't help
You can do this in Python pretty easily. Set the breakpoint - say it is breakpoint 1 - then do:
(lldb) break command add -s python 1
Enter your Python command(s). Type 'DONE' to end.
def function (frame, bp_loc, internal_dict):
"""frame: the lldb.SBFrame for the location at which you stopped
bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
internal_dict: an LLDB support object not to be used"""
this_value = frame.FindVariable("this", lldb.eDynamicDontRunTarget)
this_type = this_value.GetType().GetPointeeType().GetName()
if this_type == "YourClassNameHere":
return True
return False
DONE
The only tricky bit here is that when calling FindVariable I passed lldb.eDynamicDontRunTarget which told lldb to fetch the "dynamic" type of the variable, as opposed to the static type. As an aside, I could have also used lldb.eDynamicRunTarget but I happen to know lldb doesn't have to run the target go get C++ dynamic types.
This way of solving the problem is nice in that you don't have to have used RTTI for it to work (though then we'll only be able to get the type of classes that have some virtual method - since we use the vtable to do this magic.) It will also be faster than a method that requires running code in the debugee as your expression would have to do.
BTW, if you like this trick, you can also put the breakpoint code into a python function in some python file (just copy the def above), then use:
(lldb) command script import my_functions.py
(lldb) breakpoint command add -F my_functions.function
so you don't have to keep retyping it.
Would love some opinions on this problem I'm trying to workout. I'm trying to improve my OO experience and fully leverage C++'s polymorphic capabilities. I'm trying to write some code for a basic command parser. They command structure goes as so:
[command name] [arguments]
The command name will just be limited to a one word string. The arguments can be a 0 to N list of strings.
Each command and list of arguments could be directed to any variety of software objects in my system. So for example I could have an rtp statistics command map to my rtp module, the user statistics to my user module. Something like that.
Right now the entry point for my CLI provides the entire command string as a standard string. And it provides a standard output stream for displaying results to the user.
I really want to avoid using a parser function and then doing an if then else kind of deal. So I was thinking something like this:
I would have a base class called command. Its constructor would take the string command, the stdout, and an interface for the object it needs to interact with.
I would create a command factory that would match the command name to the object that handles it. This would instantiate the right command object for the right command.
Each separate command object would parse the given arguments and make the right choices for this command.
What I'm struggling with is how to give the right module to the right command. Is this where I should use a template argument? So that each command can take any interface and I'll let the factory decide which module to pass in to the command object?
I'm also open to other opinions as well. I'm just trying to learn and hoping the community can give me some tips :-).
What you're looking for is a common pattern in OOP. Design Patterns (the Gang of Four book) referred to this as a Command Pattern.
There's generally no need for templates. Everything is parsed and dispatched at runtime, so dynamic polymorphism (virtual functions) is probably a better choice.
In another answer, Rafael Baptista suggested a basic design. Here is how I would modify his design to be more complete:
Command objects and CommandDispatcher
Commands are handled by subclasses of the Command class. Commands are dispatched by a CommandDispatcher object that handles the basic parsing of the command string (basically, splitting at spaces, possibly handling quoted strings, etc.).
The system registers an instance of Command with the CommandDispatcher, and associates each instance of Command with a command name (std::string). The association is handled by a std::map object, although that could be replaced by a hash table (or similar structure to associate key-value pairs).
class Command
{
public:
virtual ~Command(void);
virtual void execute(FILE* in, const std::vector<std::string>& args) = 0;
};
class CommandDispatcher
{
public:
typedef std::map<std::string, Command*> CommandMap;
void registerCommand(const std::string& commandName, Command* command)
{
CommandMap::const_iterator cmdPair = registeredCommands.find(commandName);
if (cmdPair != registeredCommands.end())
{
// handle error: command already registered
}
else
{
registeredCommands[commandName] = command;
}
}
// possibly include isRegistered, unregisterCommand, etc.
void run(FILE* in, const std::string& unparsedCommandLine); // parse arguments, call command
void dispatch(FILE* in, const std::vector<std::string>& args)
{
if (! args.empty())
{
CommandMap::const_iterator cmdPair = registeredCommands.find(args[0]);
if (cmdPair == registeredCommands.end())
{
// handle error: command not found
}
else
{
Command* cmd = cmdPair->second;
cmd->execute(in, args);
}
}
}
private:
CommandMap registeredCommands;
};
I've left the parsing, and other details out, but this is a pretty common structure for command patterns. Notice how the std::map handles associating the command name with the command object.
Registering commands
To make use of this design, you need to register commands in the system. You need to instantiate CommandDispatcher, either using a Singleton pattern, in main, or in another central location.
Then, you need to register the command objects. There are several ways to do this. The way I prefer, because you have more control, is to have each module (set of related commands) provide its own registration function. For example, if you have a 'File IO' module, then you might have a function fileio_register_commands:
void fileio_register_commands(CommandDispatcher* dispatcher)
{
dispatcher->registerCommand( "readfile", new ReadFileCommand );
dispatcher->registerCommand( "writefile", new WriteFileCommand );
// etc.
}
Here ReadFileCommand and WriteFileCommand are subclasses of Command that implement the desired behavior.
You have to make sure to call fileio_register_commands before the commands become available.
This approach can be made to work for dynamically loaded libraries (DLLs or shared libraries). Make sure that the function to register commands has a regular pattern, based on the name of the module: XXX_register_commands, where XXX is, for example, the lower cased module name. After you load the shared library or DLL, your code can determine whether such a function exists, and then call it.
Templates is overkill. I imagine you want something where the command interpreter just figures out what commands are possible from the objects that are available.
For each class that wants to support this CLI, I'd give it a function that registers the class, and the command name that triggers that class.
class CLIObject
{
virtual void registerCli( Cli& cli ) = 0;
virtual bool doCommand( FILE* file, char** args ) = 0;
}
class HelloWorld : public ClIObject
{
void registerCli( Cli& cli ) { cli.register( this, "helloworld" ); }
bool doCommand( FILE* file, char** args )
{
if ( !args[0] ) return false;
fprintf( file, "hello world! %s", args[0] );
return true;
}
}
Now your cli can support any class that derives from CLIObject.
I have embedded Ruby inside my C++ application. I have generated the bindings using SWIG.
Basically, I run the ruby file and then Ruby takes over and calls my C++ class.
Based on my previous question, I would like to get the current instance of the class that is defined in the ruby file back to the C++ class so that I may execute instance methods.
I execute the ruby file as follows:
rb_eval_string_protect(<ruby script string>, &status );
rb_funcall(Qnil, rb_intern("main"), 0);
The global main method in the script creates an instance of the defined class in the file. That's the instance I am after.
If I have to, I will add a parameter or another function to pass the instance back, however, I'm not sure how to define that in C++ so that when SWIG generates the binding, it all works ok.
Any help would be appreciated.
Previous Question: Calling Ruby class methods from C++
The C api for ruby does its best to preserve ruby's functional nature, so rb_eval_string_protect() returns the VALUE of the last line of the script given, and rb_funcall() returns the VALUE of the last line of the method invoked.
So the trick is really to think of it as how would you get that instance value in pure ruby? If it's just the return value of main, like
# I'm a ruby script!
main_retval = main()
Then capturing the return value in C is similar:
// I'm some C (or C++) code
VALUE main_retval;
// ...
rb_eval_string_protect("...", &status);
main_retval = rb_funcall(Qnil, rb_intern("main"), 0);
And would give you a reference to the ruby object returned by main.
You can use this object as normal, calling methods and the like
VALUE main_retval_as_string = rb_funcall(main_retval, rb_intern("to_s"), 0);