Non-null assertion operator equivalent in PHP? - php-7

in php I see myself doing often something like this:
$res->getBody()->getContents();
but if body returns null, the next call will throw a fatal.
In Eloquent this can be even worse.
Is there a cleaner solution instead of
if ($res and $res->getBody()) {
return $res->getBody()->getContent();
} else {
return null;
}

You can use the ternary operator (always used in Laravel for example):
return $res and $res->getBody() ? $res->getBody()->getContents() : null;
or in cases where you want to return the same think you check, the Elvis operator:
return $res->getBody()?: $something_else ; // this check only if the getbody() call return null, and if not, return what that call has returns, otherwise $something_else
Just as note, you can use the default operator sometimes like this:
return $res->getBody() ?? $default_or_whatever; // if getBody returns something evaluated as false, it will return the $default_or_whatever
// same thing as return $res->getBody() ? $res->getBody() : $default_or_whatever
// and return $res->getBody() ?: $default_or_whatever

what are your thoughts about this approach:
function valueOrNull(callable $closure){
try{
return $closure();
} catch (\Throwable $e){
return null;
}
}
//$rv always null or return value never matter what
$rv = valueOrNull(fn()=> $res->getBody()->getContents()->getFirstItem()->getName());;

Related

Check if an element is there but do not fail if it's not codeception

Is there a native way in codeception to just check for the presence of an element without failing the test if element is not found?
I see this answer which uses try/catch, but isn't there a native way of doing this?
try {
$this->seeElement($selector);
} catch (\PHPUnit_Framework_ExpectationFailedException $e) {
//
}
Looks like there's no other way, so here's a little function that you can use. Pass it valid xpath through $element and $I is your codeception object
/**
* If element is found return true if not return false
* #param $element
* #return bool
*/
public function elementIsPresent($I, $element)
{
try {
$I->seeElement($element);
$isFound = true;
} catch (\PHPUnit_Framework_ExpectationFailedException $e) {
$isFound = false;
}
return $isFound;
}
for simple text swap seeElement for see

Organize functions - where do you test parameters of function?

i wonder what that would be the best solution on the area to test parameters of function.
"SRP = one function, one responsibility"
few solutions :
at the beginning of the function
in a other function
// example "at the beginning of the function"
function main() {
let arr_errors = [];
// many tests
//at the end of tests, if we are errors, we return an array (how do we distinguish between this errors array and result of function ?)
if([] !== arr_errors) {
return arr_errors;
}
// many process
return result;
}
// example "in a other function"
function main() {
if([] !== (arr_errors = testA()) {
displayErrors(arr_errors);
}
else {
return A2();
}
}
What do you think about ?
Thanks in advance.

Is there any concern about returning generic type object in Dart?

I want to implement a different error handling approach in a project without chaining exceptions.
To make it simple as possible, I am tend to write my own basic either-like model.
class Either<F, T> {
final F failure;
final T value;
const Either(this.failure, this.value);
Object check (){
if (failure != null) return failure;
return value;
}
}
I am concerning about returning the type Object, is there any problem or considerations with that in Dart or any other language?
Edit:
or returning dynamic type...
dynamic check(){
if (failure != null) return failure;
return value;
}
I think in your case, it's kind of a wired implementation. The question is, what do you want to do with the actual implementation ? Do you want to replace an if else that will appear over and over? In that case, what would you do if you have to handle the error (failure) ? I think a better approach is to use functions as parameters. Here's a short suggestion.
class Either<T, F> {
T value;
F fail;
Either(this.value, this.fail);
void check(success(T value), {failure(F fail)}) {
if (fail != null && failure != null) {
failure(fail);
} else if (value != null) {
success(value);
}
}
}
class SomeClass {
void checkTheImplementation() {
Either<String, Error> maybeString = Either("testing", null);
// if you don't want to handle the error.
maybeString.check((value) => print(value));
// if you want to handle the error
maybeString.check((value) => print(value), failure: (err) {
print(err.toString());
});
}
}
I have looked over and decided to go with baihu92's either_type way. It's much more clear and comprehensible than either in the dartz package. Here is my implementation:
and the usage is like:

Why is there no compile error since the method only returns in the "if" block?

I am working with Dart in Flutter right now, and in a tutorial I came across this method:
Future getData() async {
http.Response response = await http.get(url);
if (response.statusCode == 200) {
String data = response.body;
return jsonDecode(data);
} else {
print(response.statusCode);
}
}
Why is there no compile error? In Java or C++, there would be an error because if statusCode wasn't 200, the method wouldn't return anything. Is it because Future can act like a void type? Just don't really understand what is going on.
Yes,
When you define a "Future" it automatically defaults to
Future<void> or Future<dynamic>
If you want to force it to a certain return type you must declare it like so.
Future<int> or Future<double>
You get the idea.
However Dart doesn't operate like Java or C++, if you create a function that is supposed to return a value, but in a certain if, else clause there is no return clause, then the function will return null.

Void in Objective-C

I am learning Objective-C and I am wondering when people say that when you out void in a method it means that method returns nothing. What does that exactly mean? What would it "return" if it wasn't void? Please help.
void is exactly what you said, its just a word you use to let the compiler know that this function doesnt return anything, and you may omit the return statement in the function eg
- (void) myMethod {
//do something here
}
where as if a method has a return type, then you would get a compile error if you didnt return something of that type
- (BOOL) myMethod {
BOOL x = false;
//do something
return x;
}
so here we can see, in your words "What would it "return" if it wasn't void?" that it would return whatever you tell it to, the return type when you declare the method just needs to match what you are actually returning and thats all really.
note you can still return in a void function, but all it does is prematurely end the functions execution, eg
- (void) myMethod {
BOOL x = false;
if(x == false)
return;
x = true;
}
here we can see that the statement x = true will never execute, because it will go into the if statement and return, which will end the function (and not return anything)
It would return whatever it has been declared/written to.