Files
mautic-marketing-program-bu…/Tests/Unit/Form/UtmFieldsApplicatorTest.php
T
Alexandre Gain dce849610c Merge the Smartlinks plugin (SmartlinksBundle 0.6.0) into the bundle as the Smart Links domain (0.18.0)
Two domains, one MT3S bundle: Marketing Programs (unchanged) and the
imported Smart Links (smart links + UTM taxonomies), each keeping its
own menu, tables, routes and translations.

- Code moved from MauticPlugin\SmartlinksBundle\ to
  MauticPlugin\MT3SMarketingProgramBundle\; template namespace
  @Smartlinks/ -> @MT3SMarketingProgram/; smartlinks.js ->
  Assets/js/mt3s-mp-smartlinks.js; icon -> Assets/img/smartlinks-icon.svg.
- Incoming migrations renamed Version_0_X_0_SmartLinks.php to avoid
  the class-name collision; schema untouched, data intact.
- Permissions folded into MT3SMarketingProgramPermissions:
  smart_links + taxonomies under the mt3smarketingprogram: base
  (roles that had the old smartlinks: grants must be re-granted).
- config.php: Smart Links routes + menu group, public /l/{slug},
  SmartlinksIntegration services, smartlinks_* parameters (legacy
  utm_manager_* keys still readable), version 0.18.0. The 0.17.0
  placeholder /s/marketing-program-utm-taxonomies is replaced by the
  real /s/utm-taxonomies.
- Translations merged (en_US) and added (fr_FR); Tests/ + phpunit moved
  in; readme documents both domains and the 0.18.0 merge history.

Verified live: menus, both config tabs, both lists + forms, program
pages, public redirect with taxonomy UTM values, host + unknown-slug
404s, 90/90 unit tests, full php -l, all ini catalogs parse.
2026-11-16 13:48:13 +01:00

268 lines
12 KiB
PHP

<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Form;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\EmailBundle\Form\Type\EmailUtmTagsType;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Extension\UtmTagsTypeExtension;
use MauticPlugin\MT3SMarketingProgramBundle\Form\UtmFieldsApplicator;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationNormalizer;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Forms;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Validation;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Runs the applicator on core's real EmailUtmTagsType (shared by the Email and Focus Item forms).
*/
final class UtmFieldsApplicatorTest extends TestCase
{
private const SOURCE_VALUES = [
['value' => 'newsletter', 'label' => 'Newsletter'],
['value' => 'linkedin', 'label' => 'LinkedIn'],
['value' => 'google', 'label' => 'Google'],
];
public function testDropdownModeRendersConfiguredValuesInOrder(): void
{
$form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)]);
$field = $form->get('utmSource');
$this->assertInstanceOf(ChoiceType::class, $field->getConfig()->getType()->getInnerType());
$this->assertSame(['newsletter', 'linkedin', 'google'], $field->getConfig()->getOption('choices'));
$this->assertSame('mautic.email.campaign_source', $field->getConfig()->getOption('label'), 'Native label kept');
$this->assertSame('trans:mautic.smartlinks.form.choose', $field->getConfig()->getOption('placeholder'));
$this->assertNull($field->getConfig()->getOption('help'));
$view = $form->createView()['utmSource'];
$labels = array_map(static fn ($choice): string => $choice->label, $view->vars['choices']);
$this->assertSame(['Newsletter', 'LinkedIn', 'Google'], array_values($labels));
}
public function testDropdownModeAcceptsConfiguredOrEmptyValue(): void
{
$form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)]);
$form->submit(['utmSource' => 'linkedin', 'utmMedium' => 'email']);
$this->assertTrue($form->isValid());
$this->assertSame('linkedin', $form->getData()['utmSource']);
$form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)]);
$form->submit(['utmSource' => '']);
$this->assertTrue($form->isValid());
$this->assertNull($form->getData()['utmSource']);
}
public function testDropdownModeRejectsValueOutsideTaxonomy(): void
{
$form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)]);
$form->submit(['utmSource' => 'hacked']);
$this->assertFalse($form->isValid());
$errors = $form->get('utmSource')->getErrors();
$this->assertCount(1, $errors);
$this->assertSame('mautic.smartlinks.form.error.not_in_taxonomy', $errors[0]->getMessageTemplate());
}
public function testFreeModeKeepsNativeTextField(): void
{
$form = $this->createForm(['utm_campaign' => ['enabled' => '1', 'label' => '', 'mode' => 'free']]);
$field = $form->get('utmCampaign');
$this->assertInstanceOf(TextType::class, $field->getConfig()->getType()->getInnerType());
$this->assertSame('mautic.email.campaign_name', $field->getConfig()->getOption('label'));
$form->submit(['utmCampaign' => 'Spring Sale_2026/FR']);
$this->assertTrue($form->isValid());
$this->assertSame('Spring Sale_2026/FR', $form->getData()['utmCampaign'], 'Value stored as typed');
}
public function testDisabledModeRemovesFieldAndClearsStoredValue(): void
{
$form = $this->createForm(
[
'utm_medium' => ['enabled' => '1', 'label' => '', 'mode' => 'disabled'],
'utm_source' => ['enabled' => '1', 'label' => '', 'mode' => 'free'],
],
['utmMedium' => 'old-medium', 'utmSource' => 'kept'],
);
$this->assertFalse($form->has('utmMedium'));
$this->assertArrayNotHasKey('utmMedium', $form->createView()->children);
// A value posted anyway (stale page, crafted request) is ignored without an "extra fields" error.
$form->submit(['utmMedium' => 'posted', 'utmSource' => 'kept']);
$this->assertTrue($form->isValid());
$this->assertNull($form->getData()['utmMedium']);
$this->assertSame('kept', $form->getData()['utmSource']);
}
public function testNotEnabledParameterIsTreatedAsDisabled(): void
{
$form = $this->createForm(
['utm_source' => $this->dropdown(self::SOURCE_VALUES, enabled: '')],
['utmSource' => 'linkedin'],
);
$this->assertFalse($form->has('utmSource'));
$form->submit([]);
$this->assertTrue($form->isValid());
$this->assertNull($form->getData()['utmSource']);
}
public function testLegacyValueIsOfferedAndCanBeKept(): void
{
$form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)], ['utmSource' => 'Old Source']);
$field = $form->get('utmSource');
$this->assertSame(['newsletter', 'linkedin', 'google', 'Old Source'], $field->getConfig()->getOption('choices'));
$this->assertSame('mautic.smartlinks.form.legacy_warning', $field->getConfig()->getOption('help'));
$view = $form->createView()['utmSource'];
$this->assertSame('Old Source', $view->vars['value'], 'Legacy value selected');
$this->assertSame('trans:mautic.smartlinks.form.legacy_choice|Old Source', end($view->vars['choices'])->label);
$form->submit(['utmSource' => 'Old Source']);
$this->assertTrue($form->isValid());
$this->assertSame('Old Source', $form->getData()['utmSource'], 'Legacy value not rewritten');
}
public function testLegacyValueCanBeReplacedButNotByAnotherUnknownValue(): void
{
$config = ['utm_source' => $this->dropdown(self::SOURCE_VALUES)];
$form = $this->createForm($config, ['utmSource' => 'Old Source']);
$form->submit(['utmSource' => 'google']);
$this->assertTrue($form->isValid());
$this->assertSame('google', $form->getData()['utmSource']);
$form = $this->createForm($config, ['utmSource' => 'Old Source']);
$form->submit(['utmSource' => 'another-unknown']);
$this->assertFalse($form->isValid());
}
public function testNumericLegacyValueWrittenByApi(): void
{
$form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)], ['utmSource' => 42]);
$form->submit(['utmSource' => '42']);
$this->assertTrue($form->isValid());
$this->assertSame('42', $form->getData()['utmSource']);
}
public function testEmptyDropdownListShowsOnlyEmptyChoiceAndNotice(): void
{
$form = $this->createForm(['utm_source' => $this->dropdown([])]);
$field = $form->get('utmSource');
$this->assertSame([], $field->getConfig()->getOption('choices'));
$this->assertSame('mautic.smartlinks.form.no_values', $field->getConfig()->getOption('help'));
$form->submit(['utmSource' => '']);
$this->assertTrue($form->isValid());
}
public function testCustomLabelReplacesNativeLabel(): void
{
$form = $this->createForm([
'utm_source' => $this->dropdown(self::SOURCE_VALUES, label: 'Traffic source'),
'utm_campaign' => ['enabled' => '1', 'label' => 'Campaign code', 'mode' => 'free'],
]);
$this->assertSame('Traffic source', $form->get('utmSource')->getConfig()->getOption('label'));
$this->assertSame('Campaign code', $form->get('utmCampaign')->getConfig()->getOption('label'));
$this->assertInstanceOf(TextType::class, $form->get('utmCampaign')->getConfig()->getType()->getInnerType());
}
public function testDropdownOnContentKeepsNativeLengthConstraint(): void
{
$form = $this->createForm(['utm_content' => $this->dropdown([['value' => 'hero', 'label' => 'Hero']])]);
$constraints = $form->get('utmContent')->getConfig()->getOption('constraints');
$this->assertNotEmpty($constraints);
$this->assertInstanceOf(Length::class, is_array($constraints) ? $constraints[0] : $constraints);
}
public function testNativeFieldOrderIsKept(): void
{
$form = $this->createForm([
'utm_source' => $this->dropdown(self::SOURCE_VALUES),
'utm_medium' => $this->dropdown([['value' => 'email', 'label' => 'Email']]),
'utm_campaign' => ['enabled' => '1', 'label' => '', 'mode' => 'free'],
'utm_content' => ['enabled' => '1', 'label' => 'Variant', 'mode' => 'free'],
]);
$this->assertSame(['utmSource', 'utmMedium', 'utmCampaign', 'utmContent'], array_keys($form->createView()->children));
}
public function testKeysWithoutNativeFieldArePreserved(): void
{
$form = $this->createForm(
['utm_source' => $this->dropdown(self::SOURCE_VALUES)],
['utmSource' => 'google', 'utmTerm' => 'from-api'],
);
$form->submit(['utmSource' => 'google']);
$this->assertTrue($form->isValid());
$this->assertSame('from-api', $form->getData()['utmTerm']);
}
/**
* @param list<array{value: string, label: string}> $values
*
* @return array<string, mixed>
*/
private function dropdown(array $values, string $enabled = '1', string $label = ''): array
{
return ['enabled' => $enabled, 'label' => $label, 'mode' => 'dropdown', 'values' => $values, 'default' => ''];
}
/**
* @param array<string, array<string, mixed>> $parameters Stored configuration (local.php shape), other parameters keep their defaults
* @param array<string, mixed> $storedTags The entity's current utmTags
*
* @return FormInterface<mixed>
*/
private function createForm(array $parameters, array $storedTags = []): FormInterface
{
$coreParameters = $this->createMock(CoreParametersHelper::class);
$coreParameters->method('get')
->with(UtmConfigurationProvider::CONFIG_PARAMETER)
->willReturn(['enforce_lowercase' => '', 'separator_replacement' => '_', 'parameters' => $parameters]);
// Catalog labels translate to themselves, so an empty configured label resolves to the catalog key.
$translator = $this->createMock(TranslatorInterface::class);
$translator->method('trans')->willReturnCallback(
static fn (string $id, array $parameters = []): string => str_starts_with($id, 'mautic.smartlinks.config.parameter.')
? $id
: 'trans:'.$id.([] === $parameters ? '' : '|'.implode(',', $parameters))
);
$catalog = new UtmParameterCatalog();
$provider = new UtmConfigurationProvider($coreParameters, new UtmConfigurationNormalizer($catalog), $catalog, $translator);
$applicator = new UtmFieldsApplicator($provider, $catalog, $translator);
$factory = Forms::createFormFactoryBuilder()
->addExtension(new ValidatorExtension(Validation::createValidator()))
->addTypeExtension(new UtmTagsTypeExtension($applicator))
->getFormFactory();
return $factory->create(EmailUtmTagsType::class, $storedTags);
}
}