Ternary operator sort syntax can't work in laravel blade - laravel-5.3

laravel blade ternary operator
{{ isset($name) ? $name : 'Default' }}
we can write short form
{{ $name or 'Default' }}
but it returns the Boolean value when implement like:
{{$videos->count() or 'no video' }} //if count return 1 always,
but this code
{{ $videos->count()}} // return 4
how to implement this by short form in blade ternary operator

You want to show the count if it's > 0. Else you want to show the text.
Your count() is always not null (0 or higher). So what you want to do is this:
{{$videos->count() > 0 ? $vides->count() : 'no video'}}

Seen as you are using PHP 7.1 you can use the new Null Coalescing Operator.
All PHP 7's new features can be found in the docs:
http://php.net/manual/en/migration70.new-features.php
Your code would then look like this:
{{$videos->count() ?? 'no video' }}
There is a detailed description of the operator in the docs:
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

Related

What is the cause for this odd OR and ternary output [Javascript]

Hey so I am having an issue with an OR and ternary operation. I have this code here.
console.log(this.state.records)
Before: {
AllowCheck: "1"
Checked: "0"
}
const records = this.state.records.map((record) => {
return {
...record,
Checked: checked || record.AllowCheck === '0' ? '1' : '0',
}
});
console.log(records)
After: {
AllowCheck: "1"
Checked: "1"
}
When you look at the log before the ternary operation, you see that the object has a property called “AllowCheck”. You can see here that it evaluates as a 1 in the record. If you look at the function below, you’ll see a map operation that iterates over a list of records. The variable “checked” comes from a checkbox onChange operation that will evaluate as true in this situation. In the OR operation you can see that “checked” will be true, and the ternary on the right is where the “record.AllowCheck” will evaluated as a 1 from before. The ternary should result in a 0 since “record.AllowCheck” is 1. You’ll see in the after object that Checked is equal to 1. I don't know why it's not equal to two from the "checked" variables, and I really don't understand how it's equal to 1. Am I missing something? Have I been looking at this for too long? Any opinions or answers would be much appreciated, thank you.
The ternary should result in a 0 since “record.AllowCheck” is 1
Nope. The condition in this ternary operation is not what you think it is (record.AllowCheck === '0'). It's actually checked || record.AllowCheck === '0' and, since checked is truthy, it short-circuits on the first step, evaluates to true overall and that's how the ternary operator evaluates to '1'.
See the operator precedence table for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table

Intershop: checking for not null in .isml template

I'm not finding a function to test for the existence of a value in the ISML template code. There's 'isDefined' but not 'isNull'.
isDefined returns true on null values:
<isset name="woot" value="" scope="request">
<isif condition="#isDefined(woot)#">
<h1>woot</h1>
</isif>
For now I'm using:
<isif condition="#woot EQ null#">
or
<isif condition="#woot EQ ''#">
I don't know if this will work for Boolean values.
isDefined is how you would check for a null value. In AbstractTemplate you have the method isDefined(Object anObject) that is called. Checkout the compiled jsp and java versions of your isml template.
In AbstractTemplate
public Boolean isDefined(Object anObject){
...
return anObject != null ? Boolean.TRUE : Boolean.FALSE;
}
The code in your example is a bit misleading, it doesn't actually test for a null reference. Bear with me.
First statement :
<isset name="woot" value="" scope="request">
Compiles to :
Object temp_obj = ("");
getPipelineDictionary().put("woot", temp_obj);
This just sets the woot variable to an empty string. If you add the following scriptlet to your isml you will see that it really isn't a null.
Disclaimer: don't use scriptlets in production code, this is only for demonstrating a point
<%
Object woot = getPipelineDictionary().get("woot");
out.print(woot == null); //print false
%>
Second line:
<isif condition="#isDefined(woot)#">
Evaluates if the variable exist and it does. It has an empty string as a value, not null like you might think.
So what happens here then?
<isif condition="#woot EQ null#">
Looking at the compiled version:
context.getFormattedValue(getObject("woot"),null).equals(context.getFormattedValue(getObject("null"),null))
The context.getFormattedValue(getObject("null"),null) is the important bit here. It tries to retreive the variable called null, it doesnt exist so returns null. The getFormattedValue method then returns an empty string for the null argument (see TemplateExecutionConfig::getFormattedValue). The whole statement then evals to true. Not because woot is null, but because you are comparing it to a variable that doesnt exist, so you are inadvertently evaluating two empty strings. This behaviour is consistent with the EQ operator because it is use to compare strings.
You would get the same result if u would use this statement too.
<isif condition="#woot EQ iDontExistButImAlsoNotNull#"> //true
The third statement compares the woot variable to an empty string value, which returns true.
<isif condition="#woot EQ ''#">
Compiled version:
context.getFormattedValue(getObject("woot"),null).equals(context.getFormattedValue("",null))
So the real problem is that woot doesn't have the literal value null. See the following code:
<isset name="foo" value="#IDontExitPrettySureAboutThat#" scope="request">
<%
Object foo = getPipelineDictionary().get("foo");
out.print("foo is null? ");
out.print(foo == null);
//prints : foo is null? true
%>
<isif condition="#isDefined(foo)#">
<h1>foo1</h1> //is never printed
</isif>
I'm abusing the fact that IDontExitPrettySureAboutThat doesn't exist to set a null value to foo. isDefined then starts to work like you would expect. That is until someone initializes my variable to something other than null.
I wouldn't advocate that you use this method, however. I think the best advice is not to use null to represent a missing value or invalid state.
This thread goes into some details on this topic.

Assert a function result of boolean/string in PHPUnit

I'm using PHPUnit to auto-test my app. I want to assert the result of a function call which can return a boolean or a string. My code looks like this:
$myExample = new MyExample();
$value = $myExample->getValue();
if ($value !== false) {
assertNotNull($value);
assertFalse(empty($value));
}
But is it also possible to check whether the method executes successfully? Is "assertTrue($value)" the correct way?
UPDATE: Deprecated methods
Please use the following ones in case you want to check the data type:
assertIsArray()
assertIsBool()
assertIsFloat()
assertIsInt()
assertIsNumeric()
assertIsObject()
assertIsResource()
assertIsString()
assertIsScalar()
assertIsCallable()
assertIsIterable()
assertIsNotArray()
assertIsNotBool()
assertIsNotFloat()
assertIsNotInt()
assertIsNotNumeric()
assertIsNotObject()
assertIsNotResource()
assertIsNotString()
assertIsNotScalar()
assertIsNotCallable()
assertIsNotIterable()
UPDATE: As per mtiziani's comment below, this answer applies for PHPUnit versions below 9.#
If you want to assert the data type of the value, the correct way would be:
$this->assertInternalType('[expected_data_type]', $value);
The [expected_data_type] PHPUnit can validate can be any of these:
'array'
'boolean'
'bool'
'float'
'integer'
'int'
'null'
'numeric'
'object'
'resource'
'string'
'scalar'
'callable'
So, to assert that the returned value is a boolean, you would:
$this->assertInternalType('bool', $value);
You can use:
$this->assertSame($expect, $actual)
It will test for type and value (i.e. $expected===$actual).
If you want to test if the function returns false for certain data then you might consider doing that in a separate test method. The same with testing for a string. If you test for one value type at a time, the asserts are less complicated. Some people consider it to be good unit testing practice to have one assert per test method.
$this->assertFalse( $returnVal );
$this->assertInternalType('string', $returnValue);

Jade Template in Meteor - Conditional Comparison Syntax Error

Trying to compare two template variables is resulting in an error. This seems consistent with jade syntax. What's wrong here?
Code:
if name == current_project.name
| Current
else
a.nav-project-selection Set as Current
Error:
While building the application:
client/templates/account.jade: Jade syntax error: Expected identifier, number, string, boolean, or null
{{#if name == current_project.na...
^
SOLVED
Since Jade compiles down to Spacebars which doesn't support comparison, you have to do it via a helper function. The following worked for me:
client.js
UI.registerHelper('equals', function(a, b) {
return (a === b);
});
template
if equals name current_project.name
| Current
else
a.nav-project-selection Set as Current
An easier way is to use the Meteor-handlebar-helpers package.
meteor add raix:handlebar-helpers
Check the readme file to get an overview of the helpers. In your case:
if $eq name current_project.name
| Current

twig if block broken for int 0 comparison. symfony2

Can someone explain why this code outputs false instead of true?
Or is this a bug in twig?
{% set key = 0 %}
{% if(key != 'new') %}
{{'true' }}
{% else %}
{{ 'false' }}
{% endif %}
I use twig in symfony version 2.1.8-dev
Thank you
Be aware of Type Juggling in PHP. You can also have a look to the comparison with various types table to see that if you compare 2 different types from integer, string or reource, the manual says:
Translate strings and resources to numbers, usual math
To convert a string to a number, PHP reads your string from left to right and try to convert it. For example, if your string were '42new', it should have been juggled to 42. In your case, your string is 'new', so PHP just leave it to 0.
To correct this issue, always compare things of the same type, such as, '0' != 'new'. Or if you want to have fun, you can create a Twig extension to handle type-strict operators (===, !==) and you'll not get in trouble anymore.
The answer I got from github ( https://github.com/fabpot/Twig/issues/1079 ) is
Because key != new translates to key != (int) new not (bool) key != (bool) new
And this is actually correct and same behaviour as PHP.
easy solution for this is {% if(key ~ '' != 'new') %} and everything works again as expected.

Resources