Last active
February 7, 2017 12:12
-
-
Save Flushot/d8f4c9611befb7c9b18d2b4de15b3825 to your computer and use it in GitHub Desktop.
PHP version of https://github.com/JedWatson/classnames
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 classNames() { | |
return join(' ', | |
array_map( | |
function ($arg) { | |
if (is_array($arg)) { | |
$values = []; | |
foreach ($arg as $className => $show) { | |
if ($show) { | |
$values[] = $className; | |
} | |
} | |
return join(' ', $values); | |
} elseif (is_string($arg)) { | |
return $arg; | |
} else { | |
throw new InvalidArgumentException("argument must be a string or object"); | |
} | |
}, | |
func_get_args() | |
) | |
); | |
} | |
?> | |
<!-- Test case --> | |
<? | |
$show_spangle = true; | |
$show_blah = false; | |
?> | |
<!-- Old way --> | |
<div class="foo bar <?php if ($show_spangle): ?>spangle<? endif ?> <?php if ($show_blah): ?>blah<?php endif ?>"></div> | |
<!-- New way --> | |
<div class="<?= classNames('foo', 'bar', ['spangle' => $show_spangle, 'blah' => $show_blah]) ?>"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment