Skip to content

Instantly share code, notes, and snippets.

@Herzult
Last active August 29, 2015 14:00
Show Gist options
  • Save Herzult/11030803 to your computer and use it in GitHub Desktop.
Save Herzult/11030803 to your computer and use it in GitHub Desktop.
Text tree renderer form Symfony forms
<?php
use Symfony\Component\Form\FormInterface;
class FormTextTreeRenderer
{
public function render(FormInterface $form)
{
$lines[] = '.';
$lines[] = $this->renderNode($form);
$lines[] = '';
return implode(PHP_EOL, $lines);
}
private function renderNode(FormInterface $form)
{
$lines[] = sprintf(
'%s%s (%s)',
$this->renderNodePad($form),
$form->getName(),
$form->getConfig()->getType()->getName()
);
foreach ($form->all() as $child) {
$lines[] = $this->renderNode($child);
}
return implode(PHP_EOL, $lines);
}
private function renderNodePad(FormInterface $form)
{
$parts = [];
do {
$parent = $form->getParent();
if (is_null($parent) || end($parent->all()) === $form) {
$parts[] = count($parts) ? ' ' : '└── ';
} else {
$parts[] = count($parts) ? '| ' : '├── ';
}
} while ($form = $parent);
return implode('', array_reverse($parts));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment