cannot use isset() on the result of an expression - php

I have a block of code in some inherited work. It appears to be running ok, but I suspect that's just because it hasn't needed to call this specific function yet.
function has($key)
{
if (isset($this) && get_class($this)) {
$obj = $key;
}
if (isset($this) && get_class($this)) {
$obj = &JSW_Request::getInstance();
}
return isset(isset($this) && get_class($this)[$key]);
}
Running it through a syntax checker it reported the following error
Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)
This is related to the code line
return isset(isset($this) && get_class($this)[$key]);
I can't relate what the suggested fix is to the code line to be honest, so I'm a bit lost. Any suggestions?

Try to use null check instead of isset as follows:
if($var !== null){
// your block of code
}

Related

File_get_contents not evaluating to false when file does not exist

I'm trying to test an exception in my code.
public function testGetFileThrowsException(){
$this->expectException(FileNotFoundException::class);
$file = "db.json";
$this->review->getData($file);
}
The "db.json" file doesn't exist. My goal is tp have the getData() file to throw the FileNotFoundException. Here is the getData() code:
public function getData($path){
if(file_get_contents($path) === false){
throw new FileNotFoundException;
}
return $file;
}
The problem is that instead of evaluating to False and throw the exception, the file_get_contents function returns:
1) CompanyReviewTest::testGetFileThrowsException
file_get_contents(db.json): failed to open stream: No such file or directory
So the test doesn't run successfully. Any ideas on why does this happen?
file_get_contents() generates an E_WARNING level error (failed to open stream) which is what you'll want to suppress as you're already handling it with your exception class.
You can suppress this warning by adding PHP's error control operator # in front of file_get_contents(), example:
<?php
$path = 'test.php';
if (#file_get_contents($path) === false) {
echo 'false';
die();
}
echo 'true';
?>
The above echoes false, without the # operator it returns both the E_WARNING and the echoed false. It may be the case that the warning error is interfering with your throw function, but without seeing the code for that it's hard to say.
You have 2 solution the poor one is to hide the error like that
public function getData($path){
if(#file_get_contents($path) === false){
throw new FileNotFoundException;
}
return $file;
}
Or check maybe if the file exist (better solution i guess)
public function getData($path){
if(file_exists($path) === false){
throw new FileNotFoundException;
}
return $file;
}

How to check if a variable contains mysqli result?

I am trying to mod a script written for MySQL to mysqli and have been successful up to this error:
Warning: get_resource_type() expects parameter 1 to be resource, object given (etc)
Here is the code:
function free_result($queryid=-1)
{
if($queryid != -1)
{
$this->queryid = $queryid;
}
if((get_resource_type($this->queryid)==='mysql result') && is_resource($this->queryid))
return #mysql_free_result($this->queryid);
else
{
return false;
}
}
I can't for the life of me figure out how to change this to update it to mysqli.
Unlike the old MySQL functions, MySQLi methods don't return resources. They either return an object or some other string/integer/boolean/null type. The error message is crystal clear. The function get_resource_type() expects a resource, as an argument, and you're giving it an object.
Be sure to read about Types in PHP for clarification on the differences between resource types and object types.
My guess here is that you expect $this->queryid to be a MySQLi_Result object, and that's what you're trying to check for. So rather than get_resource_type() use the instanceof operator instead, to check the object's type.
function free_result($queryid = -1) {
if($queryid != -1) {
$this->queryid = $queryid;
}
if($this->queryid instanceof MySQLi_Result)
return mysqli_free_result($this->queryid);
} else {
return false;
}
}
Alternatively, you can just Type Hint the function's prototype to only accept objects of type MySQLi_Result to simplify your code and make it easier to test.
function free_result(MySQLi_Result $queryid = null) {
if($queryid) {
$this->queryid = $queryid;
}
if($this->queryid instanceof MySQLi_Result) {
return mysqli_free_result($this->queryid);
} else {
return false;
}
}
Also, please stop using the error silence operator #. No good can ever come of that.
Make sure you're calling mysqli_free_result() and not the old mysql_free_result() function, also, as mentioned in the comments.
You need to understand that MySQli returns an object instead of a resource. So you should test for that
If($query instanceof mysqli_result)

Function name must be a string fatal error

I have this Fatal error, I've been staring at my code for hours.. I think it has nothing to do with the name of the function action_send, it must be some silly 'missing parenthesis' or something...
can you help me please ?
if (...) {}
else if (!historic_exist($id)) {
action_send($req, '0', (strpos($req['TAG'], 'ADMD') !== false) ? $req['ID_ACT'] : '');
//the error is in this line :
if ((strpos($req['WF'],'Install') !== false) && $req('ID_EQU') !== '')
action_send($req, '', '0');
}
In PHP you can call functions dynamically using variables. In your code you are using $req('ID_EQU') which PHP considers a function call.
But $req is an array so PHP parser throws a fatal error:
Fatal error: Function name must be a string in \..\file.php on line ..
You must change $req('ID_EQU') to $req['ID_EQU'].
try to change,
if ((strpos($req['WF'],'Install') !== false) && $req('ID_EQU') !== '')
to
if ((strpos($req['WF'],'Install') !== false) && $req['ID_EQU'] !== '')

Try except in PHP

How could I perform the equivalent to an open try:this except:pass in Python?
I have the following code:
$banana = true;
unserialize($banana);
And it returns the error:
Warning: array_keys() expects parameter 1 to be array, boolean given
Which is expected, as I fed it a boolean.
This is just an example; I am using unserialize(), but I'm not purposely feeding it booleans. I need it to work this way.
Since unserialize doesn't throw an exception, there is nothing to catch.
One of the workarounds is using the silence operator (#) and check whether the
outcome of the unserialize method equals false.
$foo = #unserialize($bar);
if ($foo === false && $bar !== 'b:0;') {
// Unserialize went wrong
}
set_error_handler(function ($errno, $errstr) {
throw new Exception($errstr, 0);
}, E_NOTICE);
try {
$result = unserialize($banana); // correct
} catch (Exception $e) {
$result = array(); // default value
}
restore_error_handler();
print_r($result);

Mkdir throws a warning, when it should be a bool?

so the popular mkdir() function in php throws me a warning in the following code:
public function check_dir($dir, $create_dir = false) {
if (is_dir ( $dir )) {
return true;
} elseif ($create_dir == true) {
return mkdir ( $dir );
}
return false;
}
Its simple to know whats going on. So I won't explain. But on the mkdir() line I get:
Warning: mkdir(): Permission denied in /var/www/wordpress/wp-content/themes/Aisis-Framework/AisisCore/FileHandling/File.php on line 70
So while its a warning and nothing more, you should never turn of warnings in live, or any kind of error for that fact. So how do I deal with this when its clearly states it returns true or false and not a warning or fatal?
You can establish a custom error handler, which is a good practice in general: http://www.php.net/set-error-handler
You can use this to handle any PHP errors in any way you find appropriate. Short of that, you would have to either turn off error/warning logging (as you say, not a good practice), or use # suppression (which should be avoided in general, but might be suitable in this case.)
Personally I would agree that a function that returns true/false to indicate failure already doesn't need to issue a warning if it fails. But, that's PHP for you.
You should turn warning off in production servers ... But better still .. you can check for permission in your code ...
function checkDir($dir, $createDir = false) {
if ($createDir === true) {
if (is_dir($dir))
return true;
$baseDir = dirname($dir);
if (! is_dir($baseDir) || ! is_writable($baseDir)) {
return false;
}
return mkdir($dir);
} else {
return is_dir($dir);
}
return false;
}

Categories