Skip to content

Instantly share code, notes, and snippets.

@midorikocak
Created April 3, 2016 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save midorikocak/abc9fd9b6ca30359d201bc859edba9ee to your computer and use it in GitHub Desktop.
Save midorikocak/abc9fd9b6ca30359d201bc859edba9ee to your computer and use it in GitHub Desktop.
Tests for new Null Coalescing assignment Operator
<?php
class Test extends PHPUnit_Framework_TestCase
{
// https://www.reddit.com/r/ruby/comments/l2y8m/rubyists_already_use_monadic_patterns/c2pjlt8
public function testPHPImplementation(){
$a ?? $a = 5;
$this->assertTrue($a == 5);
$a ?? $a = 9;
$this->assertTrue($a == 5);
}
public function testRubyImplementation(){
$a || $a = 5;
$this->assertTrue($a == 5);
$a || $a = 9;
$this->assertTrue($a == 5);
}
public function testOne() {
$a = null;
$b = 20;
$a ??= $b;
$this->assertTrue($a == 20);
}
public function testSecond() {
$array['key'] ??= 10;
$array['key'] ??= 10;
$this->assertTrue($array['key'] == 10);
}
public function testThird() {
$array['key'] = $array['key'] ?? 10;
$array['key'] = $array['key'] ?? 20;
$this->assertTrue($array['key'] == 10);
}
public function testFourth() {
$array['key'] = $array['key'] ?? 10;
$array['key'] = $array['key'] ?? 20;
$this->assertTrue($array['key'] == 10);
}
public function testFifth(){
$object = new Class{
__set($name, $value){
$this->$name = $value;
echo "Setting ".$name." to ".$this->$name;
}
}
$object->val ??= 'a';
$object->val ??= 'b';
$this->assertTrue($object == 'a');
}
public function testSixth(){
$object = new Class implements ArrayAccess{
public function __construct() {
$this->container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : 'default';
}
}
$object['key'] ??= 'a';
$this->assertTrue($object['key'] == null);
$object['key'] = $object['key'] ?? 'a';
$this->assertTrue($object['key'] == 'default');
}
public function testSeventh(){
$a[0][1][0] = 5;
$this->assertTrue($a[0][1][0] == 5);
$a[0][1][1] = $a[0][1][1] ?? 5;
$this->assertTrue($a[0][1][1] == 5);
$a[0][1][1] ??= 5;
$this->assertTrue($a[0][1][1] == 5);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment