Fatal error: Can't use function return value in write context SOMETIMES - mysql

I get so annoyed when I transfer websites from one machine to another and I get a bunch of errors, such as this case. But this one made it to my curiosity and this is why I'm asking a question. I have the following code:
namsepace MF;
class Box {
private static $dumpYard = array();
public static function get($name) {
return self::$dumpYard[$name];
}
public static function set($name, $value, $overwrite=false) {
if($overwrite || !isset(self::$dumpYard[$name])){
self::$dumpYard[$name] = $value;
}else{
if(DEBUG_MODE){
echo('Value for "'.$name.'" already set in box, can\'t overwrite');
}
}
}
}
So when my application gets to the following line on my LOCAL testing server:
if(!empty(\MF\Box::get('requestsSpam'))){
throw new \Exception('Please don\'t spam');
}
I get a Fatal error: Can't use function return value in write context. However this code does not throw an error on the actual hosting server of my website. How come is that?

empty() works only with a variable. It should be:
$result = \MF\Box::get('requestsSpam');
if(!empty($result)){
throw new \Exception('Please don\'t spam');
}
Why? empty() is a language construct and not a function. It will work only with declared variables, that's just how it is designed, no magic.

Related

Yii2 beginner. Display REST exception handling

In my controller, I extend the Controller class instead of ActiveController
I have a simple actionIndex() method:
public function actionIndex(){
return json_encode(["text" => "some text"]);
}
When I access the certain route in browser, in the debugger, I see that this function is executing (the breakpoint stops inside the function), but I get 500 status code (Internal server error). How can I find the cause of the error? I have implemented the actionError() method, but it is not executing.
public function actionError() {
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
return $this->render('error', ['exception' => $exception]);
}
}
If I put the logic of the actionError() method in the actionIndex(), the $exception variable is null
The only output I get is:
{
name: "PHP Warning",
message: "Expected array for frame 0",
code: 2,
type: "yii\base\ErrorException",
file: "Unknown",
line: 0,
stack-trace: []
}
but it's warning, not error. May this cause the status code 500?
How can I get the error? Thanks!
According to this thread https://github.com/yiisoft/yii2/issues/11120 this is related to Xdebug for Yii 2 < 2.0.9.
When handling an exception, XDebug modifies the exception and Yii2 was not able to handle it correctly.
So several possible solutions here
The best idea is to update Yii2 to a version >= 2.0.9
Also you sould correct the source of the exception (the warning). It is never a good idea to have warnings. It can hide some more issues.
And as a workaround, you can disable XDebug. It is very useful during development but must be disabled in production in all cases.
Don't know about your error, but there is generally no need to return a response as json encoded. Yii checks the Accept-header of the request and adjust output accordingly. In your case I would just use:
public function actionIndex()
{
return ["text" => "some text"];
}
Possibly it might also solve your error...

Getting data from Android device in laravel

I am trying to get data from android in server in laravel. What I did till now is :
here in my route:
Route::any('jsondata','JsonController#jsonFunction');
And in my controller:
public function jsonFunction()
{
$jsonPostedData = Input::all();
return response(['jsonobjtest'=>$jsonPostedData]);
}
}
What it gives in browser is:
{"jsonobjtest":[]}
Actually i want to do is i want to send a success message to android device when it sends data. And get data here in server.
You can write like this
In your Controller
public function jsonFunction()
{
$jsonPostedData = Input::all();
// do something with your data insert or update or anything
if(count($jsonPostedData) > 0) // here you might write any of your condition.
{
return response()->json(['success'=>true]);
}
return response()->json(['success'=>false,'error'=>'your error message']);
}
You can try following code
public function jsonFunction(){
$requestObj=Input::all();
return response()->json(['success'=>true,'request_param'=>$requestObj]);
}
You can check whether
$jsonPostedData = Input::all();
input contain data or not by by simply
die and dumping $jsonPostedData variable
example
dd($jsonPostedData);

Skipping Lines of Code & Setting Variables inside Public Function within PHPUnit When Testing

I'm sure something like this has been asked before, but I've read several forums and have not come to a solution. I am using PHPUnit version 3.7.38, if that makes any difference.
I'm in PHPUnit testing a function.
public function someFunction()
{
$variable2 = Input::get('someValue');
if (strlen($variable2) == 0) {
return Redirect::to('/somepage')->with(
'notification',
array(
'type' => 'danger',
'text' => 'text.'
)
);
}
...More Code that needs to be tested
My problem is that everytime PHPUnit runs, $variable2 returns null because it can't get someValue. The code the returns and skips the rest of the function. I want to somehow skip over $variable2's declaration and assign it to a value that has a strlen() greater than zero, so the test covers the rest of the function. Is there a way to do this?
I have read the documentation on PHPUnit's site about ignoring codeblocks, but have not had any luck with that. Maybe I'm not implementing the
/**
* #codeCoverageIgnore
*/
properly or maybe that's not even what codeCoverageIgnore is meant for. I tried putting the #codeCoverage in the actual code I'm testing, but I don't think that would be right either seeing how I still want to test the if branch if it is true. I wouldn't think you would have to edit the code being tested in order to test it either.
#CodeCoverageIgnore
This is used to tell the code coverage calculations to skip the this section and not include it in the calculation of test coverage. Therefore, this module would not be included in the counts for covered/uncovered lines of the test.
However, you really want to handle the Input:: method and set it. The best way to do this is to refactor your code, to move the Input rountine out, to be supplied by dependency injection, which would then allow you to Mock the Input routine to set your text string, and allow your test to continue.
class ToTest
{
private $InputObject
public function __construct($Input = NULL)
{
if(! is_null($Input) )
{
if($Input instanceof Input) // The class that you were referencing Input::
{
$this->SetInput($Input);
}
}
}
public function SetInput(Input $Input)
{
$this->InputObject = $Input
}
public function someFunction()
{
$variable2 = $this->InputObject::get('someValue');
if (strlen($variable2) == 0) {
return Redirect::to('/somepage')->with(
'notification',
array(
'type' => 'danger',
'text' => 'text.'
)
);
}
...More Code that needs to be tested
}
}
Test:
class InputTest extends PHPUnit_Framework_TestCase
{
// Simple test for someFunctione to work Properly
// Could also use dataProvider to send different returnValues, and then check with Asserts.
public function testSomeFunction()
{
// Create a mock for the Your Input class,
// only mock the someFunction() method.
$MockInput = $this->getMock('YourInput', array('someFunction'));
// Set up the expectation for the someFunction() method
$MockInput->expects($this->any())
->method('get')
->will($this->returnValue('Test String'));
// Create Test Object - Pass our Mock as the Input
$TestClass = new ToTest($MockInput);
// Or
// $TestClass = new ToTest();
// $TestClass->SetInput($MockInput);
// Test someFunction
$this->assertEquals('Test String', $TestClass->someFunction());
}
}

zend framework 2 set_exception_handler in ActionController

I try use the "set_exception_handler" function for capture my ActionController exceptions.
Inside any view e.g. index.phtml this code works ok, the view show Helloooo.
<?php
namespace App;
echo $this->doctype();
class Fun {
static function exception_handler(\Exception $ex){
echo "Heloooo";
}
function method(){
set_exception_handler('App\Fun::exception_handler');
throw new \Exception('One Exception');
}
}
$f = new Fun();
$f->method();
I don't understand because the same code inside ActionController.php, set_exception_handler() doesn't catch the exception.
In this case the view shows the zend exception template with the "One Exception" message.
By the way, the exception stack doesn't show any Warning message, then I assume that set_exception_handler() parameter is well.
namespace App\Controller;
use Zend\....... //All namespaces used
class Fun {
static function exception_handler(\Exception $ex){
echo "Helloooo";
}
function method(){
set_exception_handler('App\Controller\Fun::exception_handler');
throw new \Exception('One Exception');
}
}
$f = new Fun();
$f->method();
class MainController extends AbstractActionController {
//The Controller Code (in this test it doesn't execute).
}
I think Zend Framework uses any technique for catching Controller exceptions in other level.
Please does somebody have any idea for do it?
I have to correct my previous post.
It seems to be a known bug of ZF. Have a look at this:
http://grokbase.com/t/php/php-bugs/128zn2emcx/php-bug-bug-62985-new-set-exception-handler-doesnt-work-from-command-line

Groovy end exception different from exception thrown

I am running into an extremely strange behavior in Groovy. When I throw an exception from a closure in a Script, the end exception that was thrown was different.
Here are the code and the details:
public class TestDelegate {
def method(Closure closure) {
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
closure.delegate = this;
closure.call();
}
public static void main(String[] args) {
// Make Script from File
File dslFile = new File("src/Script.dsl");
GroovyShell shell = new GroovyShell();
Script dslScript = shell.parse(dslFile);
TestDelegate myDelegate = new TestDelegate();
dslScript.metaClass.methodMissing = {
// will run method(closure)
String name, arguments ->
myDelegate.invokeMethod(name, arguments);
}
dslScript.metaClass.propertyMissing = {
String name ->
println "Will throw error now!"
throw new MyOwnException("errrrror");
}
dslScript.run();
}
}
class MyOwnException extends Exception {
public MyOwnException(String message) {
super(message);
}
}
Script.dsl:
method {
println a;
}
So the plan is that when I run the main() method in TestDelegate, it will run the DSL script, which calls for the method method(). Not finding it in the script, it will invoke methodMissing, which then invokes method() from myDelegate, which in turns invoke the closure, setting the delegate to the testDelegate. So far, so good. Then the closure is supposed to try printing out "a", which is not defined and will thus set off propertyMissing, which will will throw MyOwnException.
When I run the code, however, I get the following output:
Will throw error now!
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: a for class: TestDelegate
Now, it must have reached that catch block, since it printed "Will throw error now!" It must have thrown MyOwnException too! But somewhere along the lines, MyOwnException was converted to MissingPropertyException, and I have no idea why. Does anyone have any idea?
P.S. if I remove closure.setResolveStrategy(Closure.DELEGATE_FIRST) from TestDelegate#method(), the code acts as expected and throws MyOwnException. But I really need the setResolveStrategy(Closure.DELEGATE_FIRST) for my DSL project. And I would prefer to know the root cause of this rather than just removing a line or two and see that it works without understanding why.
I think this is what essentially happens: With a delegate-first resolve strategy, the Groovy runtime first tries to access property a on myDelegate, which results in a MissingPropertyException because no such property exists. Then it tries propertyMissing, which causes a MyOwnException to be thrown. Eventually the runtime gives up and rethrows the first exception encountered (a design decision), which happens to be the MissingPropertyException.
With an owner-first resolve strategy, propertyMissing is consulted first, and hence MyOwnException is eventually rethrown.
Looking at the stack trace and source code underneath should provide more evidence.