Last active
August 29, 2015 13:56
-
-
Save spiechu/8905646 to your computer and use it in GitHub Desktop.
Check corresponding blog post at http://spiechu.pl/2014/02/09/playing-with-php-functional-way
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 | |
$standardTasks = [ | |
// nothing special here, take $val and return trimmed | |
'standardTrim' => function($val) { | |
return trim($val); | |
}, | |
// this one is better, check string encoding and convert to ASCII counterpart | |
'convertToASCII' => function($val) { | |
$encoding = mb_detect_encoding($val); | |
return ($encoding === 'ASCII') ? $val : iconv($encoding, 'ASCII//TRANSLIT', $val); | |
}, | |
// this function cannot be applied to $val directly, | |
// firstly you need to call function with $char which will | |
// expose closure function to work with | |
'eliminateChar' => function($char) { | |
return function ($val) use ($char) { | |
return str_replace($char, '', $val); | |
}; | |
}, | |
// same trick, but this time creates an array as result | |
'splitByChar' => function($char) { | |
return function($val) use ($char) { | |
return explode($char, $val); | |
}; | |
}, | |
]; | |
// suppose we have string on which we need to perform following tasks: | |
$jobsToDo = [ | |
$standardTasks['convertToASCII'], | |
$standardTasks['splitByChar']('|'), | |
$standardTasks['eliminateChar'](','), | |
$standardTasks['standardTrim'], | |
]; | |
// string to process | |
$strToParse = 'Ala ma kota |Używałem GG jak byłem mały, a teraz już nie '; | |
// do not modify original string | |
$result = $strToParse; | |
// `use` keyword allows us to see the variable from inside anonymous function | |
// `&` sign passes $result as reference | |
array_walk($jobsToDo, function(callable $val) use (&$result) { | |
// 'splitByChar' creates array, | |
// so we need to apply task on every array value | |
$result = is_array($result) ? array_map($val, $result) : $val($result); | |
}); | |
// The result is as expected: | |
// array [ | |
// 0 => string 'Ala ma kota' | |
// 1 => string 'Uzywalem GG jak bylem maly a teraz juz nie' | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment