Created
July 29, 2012 03:50
-
-
Save ericlbarnes/3195974 to your computer and use it in GitHub Desktop.
Stringify Attributes
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
/** | |
* Stringify attributes for use in html tags. | |
* | |
* Helper function used to convert an array or object of | |
* attributes to a string | |
* | |
* @param mixed | |
* @return string | |
*/ | |
function _stringify_attributes($attributes, $js = FALSE) | |
{ | |
if (is_object($attributes) && count($attributes) > 0) | |
{ | |
$attributes = (array) $attributes; | |
} | |
if (is_array($attributes)) | |
{ | |
$atts = ''; | |
if (count($attributes) === 0) | |
{ | |
return $atts; | |
} | |
foreach ($attributes as $key => $val) | |
{ | |
if ($js) | |
{ | |
$atts .= $key.'='.$val.','; | |
} | |
else | |
{ | |
$atts .= ' '.$key.'="'.$val.'"'; | |
} | |
} | |
return rtrim($atts, ','); | |
} | |
elseif (is_string($attributes) && strlen($attributes) > 0) | |
{ | |
return ' '.$attributes; | |
} | |
return $attributes; | |
} |
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
public function test_stringify_attributes() | |
{ | |
$this->assertEquals(' class="foo" id="bar"', _stringify_attributes(array('class' => 'foo', 'id' => 'bar'))); | |
$atts = new Stdclass; | |
$atts->class = 'foo'; | |
$atts->id = 'bar'; | |
$this->assertEquals(' class="foo" id="bar"', _stringify_attributes($atts)); | |
$this->assertEquals(' class="foo" id="bar"', _stringify_attributes('class="foo" id="bar"')); | |
} | |
public function test_stringify_js_attributes() | |
{ | |
$this->assertEquals('width=800,height=600', _stringify_attributes(array('width' => '800', 'height' => '600'), TRUE)); | |
$atts = new Stdclass; | |
$atts->width = 800; | |
$atts->height = 600; | |
$this->assertEquals('width=800,height=600', _stringify_attributes($atts, TRUE)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment