Skip to content

Instantly share code, notes, and snippets.

@crisu83
Last active December 21, 2015 09:59
Show Gist options
  • Save crisu83/6288615 to your computer and use it in GitHub Desktop.
Save crisu83/6288615 to your computer and use it in GitHub Desktop.
Component for Yii for rendering configuration files.
<?php
class ConfigRenderer extends CComponent
{
/**
* @var string
*/
public $tab = ' ';
/**
* @param $array
* @return string
*/
public function render($array)
{
return "<?php\nreturn " . $this->renderArray($array) . ";\n";
}
/**
* @param $array
* @param int $depth
* @param bool $newLine
* @return string
*/
protected function renderArray($array, $depth = 0, $newLine = true)
{
$output = '';
if ($newLine) {
$output .= $this->indent($depth);
}
$output .= "array(\n";
foreach ($array as $key => $value) {
if (is_string($key)) {
$output .= $this->renderAssoc($key, $value, $depth + 1);
} else {
$output .= $this->renderValue($value, $depth + 1);
}
$output .= "\n";
}
return $output . $this->indent($depth) . ')';
}
/**
* @param $key
* @param $value
* @param $depth
* @return string
*/
protected function renderAssoc($key, $value, $depth)
{
return $this->renderKey($key, $depth) . ' => ' . $this->renderValue($value, $depth, false);
}
/**
* @param $key
* @param $depth
* @return string
*/
protected function renderKey($key, $depth)
{
return $this->indent($depth) . $this->quote($key);
}
/**
* @param $value
* @param $depth
* @param bool $newLine
* @return string
*/
protected function renderValue($value, $depth, $newLine = true)
{
$output = '';
if ($newLine) {
$output .= $this->indent($depth);
}
if (is_array($value)) {
$output .= $this->renderArray($value, $depth, false);
} else {
$output .= $this->quote($value);
}
return $output;
}
/**
* @param $string
* @return string
*/
protected function quote($string)
{
return "'" . $string . "'";
}
/**
* @param $depth
* @return string
*/
protected function indent($depth)
{
return str_repeat($this->tab, $depth);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment