Last active
August 29, 2015 14:00
-
-
Save Herzult/11030803 to your computer and use it in GitHub Desktop.
Text tree renderer form Symfony forms
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 | |
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