Last active
March 12, 2025 14:08
-
-
Save alexander-schranz/ba6b2fd888637eea93ee21fa9802d284 to your computer and use it in GitHub Desktop.
FormTestHelper
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\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; | |
} | |
} |
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\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