Last active
December 16, 2015 05:48
-
-
Save tomsseisums/5386737 to your computer and use it in GitHub Desktop.
Smart helpers for PHP
This file contains hidden or 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 is(&$variable, $filters) | |
{ | |
$filters = explode('|', $filters); | |
$state = false; | |
foreach ($filters as $filter) | |
{ | |
switch ($filter) | |
{ | |
case 'filled': | |
$state = !empty($variable); | |
break; | |
case 'array': | |
$state = is_array($variable); | |
break; | |
} | |
if ($state === false) break; | |
} | |
return $state; | |
} | |
$a = array(4); | |
var_dump( | |
is($a, 'filled|array'), // true | |
is($b, 'filled|array') // false (notice, that $b is not even defined, yet there is no notice) | |
); |
This file contains hidden or 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 | |
// Global flags to be used all around the new methods | |
define('ITERATOR_EMPTY', 1); | |
define('ITERATOR_INT', 2); | |
// Flag resolver | |
function get_flag_methods($flags) | |
{ | |
$functions = array(); | |
if ($flags & ITERATOR_EMPTY) $functions[] = function ($value){ return empty($value); }; | |
if ($flags & ITERATOR_INT) $functions[] = function ($value){ return !is_int($value); }; | |
return $functions; | |
} | |
// foreach with filters | |
function all(array $elements, callable $callback, $flags = 0) | |
{ | |
$methods = get_flag_methods($flags); | |
foreach ($elements as $index => $element) | |
{ | |
foreach ($methods as $test) | |
{ | |
if (call_user_func($test, $element) ) continue 2; | |
} | |
$callback($index, $element); | |
} | |
} | |
// test | |
all(array('', 5, 'lol', 22), function ($key, $value) { | |
echo $value . '<br>'; | |
}, ITERATOR_EMPTY | ITERATOR_INT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment