Files
Alexandre Gain 9d81d6c815 refactor(naming): normalise the Smart Links domain to the bundle's canonical names (0.18.1)
One bundle, two domains (Marketing Programs and Smart Links), one naming scheme.\nNothing in the database changed (no tables, columns, URLs or stored data);\nthe runtime was rebuilt and verified live.\n\n- Route names mautic_smartlinks_* -> mt3s_smartlinks_* (paths unchanged);\n  the menu ids follow\n- Model service aliases collapsed to one canonical alias per model:\n  mautic.mt3smarketingprogram.model.<entity> (core's mautic.<x>.model.<x>\n  pattern), so getModel('mt3smarketingprogram.smart_link'); the dead\n  mt3s.* and mautic.mt3smp.*-era aliases are gone\n- Translation keys mautic.smartlinks.* -> mt3s.smart_links.*\n  (mautic.config.tab.smartlinksconfig stays: core derives it)\n- Settings parameters smartlinks_utm_config/smartlinks_config ->\n  mt3s_smart_links_utm_config/mt3s_smart_links_config, with both legacy\n  keys (smartlinks_* of the standalone bundle, utm_manager_* of the\n  UtmManagerBundle era) still readable until the settings are saved again\n- JS loader prefixes smartlinksSmartLink/smartlinksUtmTaxonomy ->\n  mt3sMpSmartLink/mt3sMpUtmTaxonomy (the mt3sMp* family of the program\n  domain)\n- Integration/Support/ConfigSupport -> SmartlinksConfigSupport; integration\n  display names aligned ('MT3S Marketing Program' / 'Smart Links'); the\n  dead mautic.plugin.smartlinks.name catalog keys removed\n- phpunit suite renamed UtmManagerBundle -> MT3SMarketingProgramBundle;\n  version 0.18.1\n\nVerified: full php -l, 90/90 unit tests (phpunit 11.5 phar), cache clear +\nwarm + assets regenerate + plugins reload (as www-data), live: both lists\nand forms (mauticContent mt3sMpSmartLink/mt3sMpUtmTaxonomy), both config\ntabs, the menu labels, the program pages (regression), the public /l/y32b\nredirect through the legacy utm_manager_* settings (302 with the taxonomy's\nUTM values, wrong host and unknown slug 404), all ini catalogs parse, zero\nnew log errors.
2026-11-16 15:47:30 +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:mt3s.smart_links.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('mt3s.smart_links.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('mt3s.smart_links.form.legacy_warning', $field->getConfig()->getOption('help'));
$view = $form->createView()['utmSource'];
$this->assertSame('Old Source', $view->vars['value'], 'Legacy value selected');
$this->assertSame('trans:mt3s.smart_links.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('mt3s.smart_links.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, 'mt3s.smart_links.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);
}
}