Created
March 13, 2018 16:19
-
-
Save sybrew/034059824dbba4f49bfbbff36df184f2 to your computer and use it in GitHub Desktop.
A readable if this-then-that-and-else-this-then-that-and... function wrapper.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function if_( $value ) { | |
return new class( (bool) $value ) { | |
public $run, $and; | |
public $cb = []; | |
function __construct( $run ) { $this->run = $run; } | |
function __destruct() { | |
foreach ( $this->cb as $cb ) { | |
$cb ? $cb() : null; | |
} | |
} | |
function then_( $cb ) { | |
if ( $this->run ) { | |
$this->cb[] = $cb; | |
$this->run = false; | |
$this->and = true; | |
} else { | |
$this->run = true; | |
$this->and = false; | |
} | |
return $this; | |
} | |
function else_( $cb ) { | |
return $this->then_( $cb ); | |
} | |
function and_( $cb ) { | |
if ( $this->and ) { | |
$this->run = true; | |
$this->and = false; | |
} else{ | |
$this->run = false; | |
$this->and = false; | |
} | |
return $this->then_( $cb ); | |
} | |
}; | |
} | |
/** | |
* Example: | |
*/ | |
if_( true )->then_( '_do' )->and_( '_do_that' )->else_( '_dont' )->and_( '_dont_that' ); | |
echo "\n"; | |
if_( false )->then_( '_do' )->and_( '_do_that' )->else_( '_dont' )->and_( '_dont_that' ); | |
function _do() { | |
print 'yay1'; | |
} | |
function _do_that() { | |
print '-yay2'; | |
} | |
function _dont() { | |
print 'nay1'; | |
} | |
function _dont_that() { | |
print '-nay2'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment