Skip to content

Instantly share code, notes, and snippets.

@alexander-schranz
Last active March 12, 2025 14:08
Show Gist options
  • Save alexander-schranz/ba6b2fd888637eea93ee21fa9802d284 to your computer and use it in GitHub Desktop.
Save alexander-schranz/ba6b2fd888637eea93ee21fa9802d284 to your computer and use it in GitHub Desktop.
FormTestHelper
<?php
use Symfony\Component\Form\FormView;
/**
* The following converts a form view into a snapshot able format, to test different form types and form builders.
*/
class FormTestHelper
{
/**
* @param array<string, array{
* type: string,
* required?: true,
* disabled?: true,
* }|string> $fields
*
* @return array<string, array{
* type: string,
* required?: true,
* disabled?: true,
* }|string>
*/
public static function extractFormFields(FormView $formView, array &$fields = []): array
{
foreach ($formView as $child) {
if (\count($child) > 0) {
self::extractFormFields($child, $fields);
continue;
}
$fullName = $child->vars['full_name'];
$types = $child->vars['block_prefixes'];
$type = $types[\count($types) - 2] ?? null;
\assert(null !== $type, 'A type should always be present.');
$fieldConfig = [
'type' => $type,
];
if ($child->vars['required']) {
$fieldConfig['required'] = true;
}
if ($child->vars['disabled']) {
$fieldConfig['disabled'] = true;
}
if (1 === \count($fieldConfig)) {
$fieldConfig = $type;
}
$fields[$fullName] = $fieldConfig;
}
return $fields;
}
}
<?php
use Symfony\Component\Form\FormView
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use FormTestHelper;
class SomeTest extends KernelTestCase
{
public function testForm(): void
{
$form = self::getContainer()->get('form.factory')->create(MyFormType::class, [], []);
$this->assertSame([
// ..
], FormTestHelper->extractFormFields($form->createView()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment