Skip to content

Commit

Permalink
refactoring meta()
Browse files Browse the repository at this point in the history
  • Loading branch information
hirak committed Apr 19, 2015
1 parent 3f64eca commit 320254e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
43 changes: 24 additions & 19 deletions src/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,44 +280,49 @@ public static function meta($meta, $isXhtml=false, $escape=true)
}

$html = array();

$TAGEND = $isXhtml ? ' />' : '>';
$escape = (bool)$escape;

foreach ($meta as $attr => $defs) {
$attr = $escape ? static::h($attr, \ENT_COMPAT) : $attr;

if (is_scalar($defs)) {
$html[] = self::_generateMeta($attr, $defs, $TAGEND, $escape);
$html[] = array('meta', $attr => $defs);
continue;
}

foreach ($defs as $label => $val) {
$label = $escape ? static::h($label, \ENT_COMPAT) : $label;

if (is_scalar($val)) {
$html[] = self::_generateMeta($attr, $label, $TAGEND, $escape, $val);
$html[] = array('meta', $attr => $label, 'content' => $val);
continue;
}

foreach ($val as $v) {
$html[] = self::_generateMeta($attr, $label, $TAGEND, $escape, $v);
$html[] = array('meta', $attr => $label, 'content' => $v);
}
}
}

sort($html, \SORT_STRING);
return implode(PHP_EOL, $html);
$metatags = array();
foreach ($html as $def) {
$metatags[] = self::_generateTag($def, $isXhtml, $escape);
}

sort($metatags, \SORT_STRING);
return implode(PHP_EOL, $metatags);
}

private static function _generateMeta($type, $val, $TAGEND, $escape, $content=null)
private static function _generateTag(array $def, $isXhtml=false, $escape=true)
{
if ($content) {
$content = $escape ? static::h($content, \ENT_COMPAT) : $content;
return '<meta ' . $type . '="' . $val . '" content="' . $content . '"' . $TAGEND;
$tag = $def[0];
unset($def[0]);

$html = array();
if ($escape) {
foreach ($def as $key => $val) {
$html[] = $key . '="' . static::h($val, \ENT_COMPAT) . '"';
}
} else {
$val = $escape ? static::h($val, \ENT_COMPAT) : $val;
return '<meta ' . $type . '="' . $val . '"' . $TAGEND;
foreach ($def as $key => $val) {
$html[] = $key . '="' . $val . '"';
}
}

return "<$tag " . implode(' ', $html) . ($isXhtml ? ' />' : '>');
}
}
5 changes: 5 additions & 0 deletions tests/ViewTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,11 @@ function meta()
file_get_contents(__DIR__ . '/../example/07_meta/result.html'),
$view->render()
);

// no escape
$meta = array('hoge' => '<');

self::assertEquals('<meta hoge="<">', View::meta($meta, false, false));
}

/**
Expand Down

0 comments on commit 320254e

Please sign in to comment.