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.
This commit is contained in:
Alexandre Gain committed 2026-11-16 13:48:13 +01:00
1 parent debce4ba4a
commit dce849610c
69 files changed
+8225 -43

No files matched your search

@@ -0,0 +1,275 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Form;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Form\DataTransformer\UtmSettingsTransformer;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartlinksSettingsType;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\UtmParameterType;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\UtmValueType;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\UtmSettingsValidator;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationNormalizer;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Translation\IdentityTranslator;
use Symfony\Component\Validator\Validation;
/**
* Server-side validation of the configuration form, with the real types, transformer and constraints.
*/
final class SmartlinksSettingsTypeTest extends TypeTestCase
{
protected function getExtensions(): array
{
$catalog = new UtmParameterCatalog();
$translator = new IdentityTranslator();
$transformer = new UtmSettingsTransformer(new UtmConfigurationNormalizer($catalog), $catalog, $translator);
return [
new PreloadedExtension([
new SmartlinksSettingsType($catalog, $transformer),
new UtmParameterType(new UtmSettingsValidator($catalog), $translator),
new UtmValueType(),
], []),
new ValidatorExtension(Validation::createValidator()),
];
}
public function testDefaultConfigurationIsValidAndStoresOnlyModeForFreeParameters(): void
{
$form = $this->submit($this->defaultSubmission());
$this->assertTrue($form->isSynchronized());
$this->assertSame([], $this->errorMessages($form));
$data = $form->getData();
$this->assertTrue($data['enforce_lowercase']);
$this->assertSame('-', $data['separator_replacement']);
$this->assertSame(['enabled' => true, 'label' => 'mautic.smartlinks.config.parameter.utm_campaign.label', 'mode' => 'free'], $data['parameters']['utm_campaign']);
$this->assertSame(['enabled' => false, 'label' => 'mautic.smartlinks.config.parameter.gclid.label', 'mode' => 'disabled'], $data['parameters']['gclid']);
$this->assertSame(['enabled', 'label', 'mode', 'values', 'default'], array_keys($data['parameters']['utm_source']));
}
public function testValuesSubmittedForAFreeParameterAreIgnored(): void
{
$submission = $this->defaultSubmission();
$submission['parameters']['utm_source']['mode'] = 'free';
$submission['parameters']['utm_source']['values'] = [
['value' => 'NOT VALID', 'label' => ''],
['value' => 'NOT VALID', 'label' => ''],
];
$form = $this->submit($submission);
$this->assertSame([], $this->errorMessages($form));
$this->assertSame(['enabled' => false, 'label' => 'mautic.smartlinks.config.parameter.utm_source.label', 'mode' => 'free'], $form->getData()['parameters']['utm_source']);
}
public function testEnabledDropdownWithoutValuesIsRejected(): void
{
$submission = $this->defaultSubmission();
$submission['parameters']['utm_source']['enabled'] = '1';
$form = $this->submit($submission);
$this->assertSame(
[UtmSettingsValidator::ERROR_VALUES_REQUIRED],
$this->messages($form->get('parameters')->get('utm_source')->get('values'))
);
}
public function testDropdownValuesAreStoredInOrderWithTheirDefault(): void
{
$submission = $this->defaultSubmission();
$submission['parameters']['utm_source']['enabled'] = '1';
$submission['parameters']['utm_source']['values'] = [
['value' => 'newsletter', 'label' => 'Newsletter'],
['value' => 'linkedin', 'label' => 'LinkedIn', 'is_default' => '1'],
];
$form = $this->submit($submission);
$this->assertSame([], $this->errorMessages($form));
$this->assertSame([
'enabled' => true,
'label' => 'mautic.smartlinks.config.parameter.utm_source.label',
'mode' => 'dropdown',
'values' => [
['value' => 'newsletter', 'label' => 'Newsletter'],
['value' => 'linkedin', 'label' => 'LinkedIn'],
],
'default' => 'linkedin',
], $form->getData()['parameters']['utm_source']);
}
public function testDuplicateAndInvalidValuesAreRejected(): void
{
$submission = $this->defaultSubmission();
$submission['parameters']['utm_medium']['enabled'] = '1';
$submission['parameters']['utm_medium']['values'] = [
['value' => 'email', 'label' => 'Email', 'is_default' => '1'],
['value' => 'email', 'label' => 'Email again', 'is_default' => '1'],
['value' => 'Paid Social', 'label' => 'Paid social'],
['value' => str_repeat('a', 101), 'label' => ''],
];
$form = $this->submit($submission);
$values = $form->get('parameters')->get('utm_medium')->get('values');
$this->assertSame([UtmSettingsValidator::ERROR_VALUE_DUPLICATE, UtmSettingsValidator::ERROR_DEFAULT_MULTIPLE], $this->messages($values));
$this->assertSame(['mautic.smartlinks.config.error.value_invalid'], $this->messages($values->get('2')->get('value')));
$this->assertSame(['mautic.smartlinks.config.error.value_length'], $this->messages($values->get('3')->get('value')));
$this->assertSame(['mautic.smartlinks.config.error.label_required'], $this->messages($values->get('3')->get('label')));
}
public function testDropdownModeIsRefusedForClickIds(): void
{
$submission = $this->defaultSubmission();
$submission['parameters']['gclid']['mode'] = 'dropdown';
$form = $this->submit($submission);
$this->assertSame(['mautic.smartlinks.config.error.mode_invalid'], $this->messages($form->get('parameters')->get('gclid')->get('mode')));
}
public function testCustomParameterIsStoredUnderItsKey(): void
{
$submission = $this->defaultSubmission();
$submission['custom_parameters'][] = $this->customParameter('partner', 'free');
$form = $this->submit($submission);
$this->assertSame([], $this->errorMessages($form));
$this->assertSame(['enabled' => true, 'label' => 'Partner', 'mode' => 'free'], $form->getData()['parameters']['partner']);
}
public function testCustomKeyRules(): void
{
$submission = $this->defaultSubmission();
$submission['custom_parameters'] = [
$this->customParameter('Bad-Key'),
$this->customParameter('utm_partner'),
$this->customParameter('mtc_x'),
$this->customParameter('ct'),
$this->customParameter('gclid'),
$this->customParameter('ref'),
$this->customParameter('ref'),
$this->customParameter(''),
];
$custom = $this->submit($submission)->get('custom_parameters');
$this->assertSame([UtmSettingsValidator::ERROR_KEY_INVALID], $this->messages($custom->get('0')->get('key')));
foreach (['1', '2', '3', '4'] as $index) {
$this->assertSame([UtmSettingsValidator::ERROR_KEY_RESERVED], $this->messages($custom->get($index)->get('key')), $index);
}
$this->assertSame([UtmSettingsValidator::ERROR_KEY_DUPLICATE], $this->messages($custom->get('5')->get('key')));
$this->assertSame([UtmSettingsValidator::ERROR_KEY_DUPLICATE], $this->messages($custom->get('6')->get('key')));
$this->assertSame(['mautic.smartlinks.config.error.key_required'], $this->messages($custom->get('7')->get('key')));
}
public function testLabelCannotContainPercent(): void
{
$submission = $this->defaultSubmission();
$submission['parameters']['utm_campaign']['label'] = '50% off';
$form = $this->submit($submission);
$this->assertSame(['mautic.smartlinks.config.error.label_invalid'], $this->messages($form->get('parameters')->get('utm_campaign')->get('label')));
}
public function testStoredConfigurationIsLoadedIntoTheForm(): void
{
$form = $this->factory->create(SmartlinksSettingsType::class, [
'enforce_lowercase' => '',
'parameters' => [
'utm_source' => ['enabled' => '1', 'label' => 'Src', 'mode' => 'dropdown', 'values' => [['value' => 'a', 'label' => 'A']], 'default' => 'a'],
'partner' => ['enabled' => '1', 'label' => 'Partner', 'mode' => 'free'],
],
]);
$this->assertFalse($form->get('enforce_lowercase')->getData());
$this->assertSame('Src', $form->get('parameters')->get('utm_source')->get('label')->getData());
$this->assertSame([['value' => 'a', 'label' => 'A', 'is_default' => true]], $form->get('parameters')->get('utm_source')->get('values')->getData());
$this->assertSame('partner', $form->get('custom_parameters')->get('0')->get('key')->getData());
}
/**
* @param array<string, mixed> $submission
*
* @return FormInterface<mixed>
*/
private function submit(array $submission): FormInterface
{
$form = $this->factory->create(SmartlinksSettingsType::class, []);
$form->submit($submission);
return $form;
}
/**
* What the browser posts for an untouched form.
*
* @return array<string, mixed>
*/
private function defaultSubmission(): array
{
$view = $this->factory->create(SmartlinksSettingsType::class, [])->getViewData();
$parameters = [];
foreach ($view['parameters'] as $key => $parameter) {
$parameters[$key] = [
'enabled' => $parameter['enabled'] ? '1' : '0',
'label' => $parameter['label'],
'mode' => $parameter['mode'],
'values' => [],
];
}
return [
'enforce_lowercase' => '1',
'separator_replacement' => '-',
'parameters' => $parameters,
'custom_parameters' => [],
];
}
/**
* @return array<string, mixed>
*/
private function customParameter(string $key, string $mode = 'free'): array
{
return ['key' => $key, 'enabled' => '1', 'label' => ucfirst($key) ?: 'Label', 'mode' => $mode, 'values' => []];
}
/**
* @param FormInterface<mixed> $form
*
* @return string[]
*/
private function messages(FormInterface $form): array
{
return array_map(
fn (FormError $error): string => $error->getMessageTemplate(),
iterator_to_array($form->getErrors())
);
}
/**
* @param FormInterface<mixed> $form
*
* @return string[]
*/
private function errorMessages(FormInterface $form): array
{
return array_map(
fn (FormError $error): string => $error->getOrigin()?->getName().': '.$error->getMessageTemplate(),
iterator_to_array($form->getErrors(true))
);
}
}
+267
View File
@@ -0,0 +1,267 @@
<?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);
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Form;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\UtmSettingsValidator;
use PHPUnit\Framework\TestCase;
final class UtmSettingsValidatorTest extends TestCase
{
private UtmSettingsValidator $validator;
protected function setUp(): void
{
$this->validator = new UtmSettingsValidator(new UtmParameterCatalog());
}
public function testCustomKeyRegex(): void
{
$this->assertSame([], $this->validator->validateCustomKey('partner_id'));
$this->assertSame([[UtmSettingsValidator::ERROR_KEY_INVALID, ['%key%' => 'Partner']]], $this->validator->validateCustomKey('Partner'));
$this->assertSame(UtmSettingsValidator::ERROR_KEY_INVALID, $this->validator->validateCustomKey('9lives')[0][0]);
$this->assertSame(UtmSettingsValidator::ERROR_KEY_INVALID, $this->validator->validateCustomKey('x')[0][0]);
}
public function testCustomKeyCollisions(): void
{
foreach (['utm_source', 'gclid', 'ct', 'utm_partner', 'mtc_id'] as $key) {
$this->assertSame([[UtmSettingsValidator::ERROR_KEY_RESERVED, ['%key%' => $key]]], $this->validator->validateCustomKey($key), $key);
}
}
public function testCustomKeyUniqueness(): void
{
$this->assertSame([], $this->validator->validateKeyIsUnique('ref', ['ref', 'partner']));
$this->assertSame(
[[UtmSettingsValidator::ERROR_KEY_DUPLICATE, ['%key%' => 'ref']]],
$this->validator->validateKeyIsUnique('ref', ['ref', 'partner', 'ref'])
);
}
public function testEnabledDropdownNeedsValues(): void
{
$this->assertSame(
[[UtmSettingsValidator::ERROR_VALUES_REQUIRED, []]],
$this->validator->validateValueList(UtmParameterMode::DROPDOWN, true, [])
);
$this->assertSame([], $this->validator->validateValueList(UtmParameterMode::DROPDOWN, false, []));
}
public function testDuplicateValuesAreReportedOnce(): void
{
$rows = [['value' => 'email'], ['value' => 'email'], ['value' => 'email'], ['value' => 'sms']];
$this->assertSame(
[[UtmSettingsValidator::ERROR_VALUE_DUPLICATE, ['%value%' => 'email']]],
$this->validator->validateValueList(UtmParameterMode::DROPDOWN, true, $rows)
);
}
public function testOnlyOneDefault(): void
{
$rows = [['value' => 'a', 'is_default' => true], ['value' => 'b', 'is_default' => true]];
$this->assertSame(
[[UtmSettingsValidator::ERROR_DEFAULT_MULTIPLE, []]],
$this->validator->validateValueList(UtmParameterMode::DROPDOWN, true, $rows)
);
}
public function testNothingIsCheckedOutsideDropdownMode(): void
{
$rows = [['value' => 'a', 'is_default' => true], ['value' => 'a', 'is_default' => true]];
$this->assertSame([], $this->validator->validateValueList(UtmParameterMode::FREE, true, $rows));
$this->assertSame([], $this->validator->validateValueList(UtmParameterMode::DISABLED, true, $rows));
$this->assertSame([], $this->validator->validateValueList(UtmParameterMode::FREE, true, []));
}
}
@@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Form\Validator;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\SmartLinkValidator;
use MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationNormalizer;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Contracts\Translation\TranslatorInterface;
final class SmartLinkValidatorTest extends TestCase
{
/**
* The stored configuration of a link that has no taxonomy: a dropdown utm_source
* (newsletter, linkedin) and a free utm_campaign.
*/
private const RAW_CONFIG = [
'enforce_lowercase' => '1',
'separator_replacement' => '-',
'parameters' => [
'utm_source' => [
'enabled' => '1', 'label' => 'Source', 'mode' => 'dropdown',
'values' => [
['value' => 'newsletter', 'label' => 'Newsletter'],
['value' => 'linkedin', 'label' => 'LinkedIn'],
],
],
'utm_campaign' => ['enabled' => '1', 'label' => 'Campaign', 'mode' => 'free'],
],
];
private function createValidator(array $raw = self::RAW_CONFIG): SmartLinkValidator
{
$parameters = $this->createMock(CoreParametersHelper::class);
$parameters->method('get')->willReturnMap([
[UtmConfigurationProvider::CONFIG_PARAMETER, [], $raw],
]);
$translator = $this->createMock(TranslatorInterface::class);
$translator->method('trans')->willReturnCallback(fn (string $id): string => $id);
$provider = new UtmConfigurationProvider(
$parameters,
new UtmConfigurationNormalizer(new UtmParameterCatalog()),
new UtmParameterCatalog(),
$translator
);
return new SmartLinkValidator($this->createMock(SmartLinkModel::class), $provider);
}
private function createTaxonomy(array $parameters): UtmTaxonomy
{
$taxonomy = new UtmTaxonomy();
$taxonomy->setName('Spring campaigns');
$taxonomy->setParameters($parameters);
return $taxonomy;
}
public function testTaxonomyValuesAreAccepted(): void
{
$taxonomy = $this->createTaxonomy([
'utm_source' => [['value' => 'newsletter', 'label' => 'Newsletter']],
'utm_campaign' => [['value' => 'spring', 'label' => 'Spring']],
]);
$this->assertSame([], $this->createValidator()->validateUtmParameters([
'utm_source' => 'newsletter',
'utm_campaign' => 'spring',
], $taxonomy));
}
public function testValuesOutsideTheTaxonomyAreRejected(): void
{
$taxonomy = $this->createTaxonomy([
'utm_source' => [['value' => 'newsletter', 'label' => 'Newsletter']],
]);
$errors = $this->createValidator()->validateUtmParameters([
'utm_source' => 'linkedin',
], $taxonomy);
$this->assertSame([[SmartLinkValidator::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => 'utm_source', '%value%' => 'linkedin']]], $errors);
}
public function testAStoredValueSurvivesAPlainReSave(): void
{
$taxonomy = $this->createTaxonomy([
'utm_source' => [['value' => 'newsletter', 'label' => 'Newsletter']],
]);
$this->assertSame([], $this->createValidator()->validateUtmParameters(
['utm_source' => 'legacy_banner'],
$taxonomy,
['utm_source' => 'legacy_banner']
));
}
public function testFreeParametersTakeTheirValuesFromTheTaxonomyList(): void
{
// The admin left utm_campaign free, but the taxonomy carries its own value list: the
// link picks a value from it, nothing is free-typed.
$taxonomy = $this->createTaxonomy([
'utm_campaign' => [
['value' => 'spring', 'label' => 'Spring'],
['value' => 'summer', 'label' => 'Summer'],
],
]);
$this->assertSame([], $this->createValidator()->validateUtmParameters([
'utm_campaign' => 'spring',
], $taxonomy));
$this->assertSame(
[[SmartLinkValidator::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => 'utm_campaign', '%value%' => 'autumn']]],
$this->createValidator()->validateUtmParameters(['utm_campaign' => 'autumn'], $taxonomy)
);
}
public function testParametersTheTaxonomyDoesntDefineAreRejected(): void
{
// The taxonomy defines neither the configured dropdown utm_source nor the free
// utm_campaign: both are unknown to it.
$taxonomy = $this->createTaxonomy([]);
$this->assertSame(
[[SmartLinkValidator::ERROR_TAXONOMY_PARAMETER_UNKNOWN, ['%key%' => 'utm_source', '%name%' => 'Spring campaigns']]],
$this->createValidator()->validateUtmParameters(['utm_source' => 'newsletter'], $taxonomy)
);
$this->assertSame(
[[SmartLinkValidator::ERROR_TAXONOMY_PARAMETER_UNKNOWN, ['%key%' => 'utm_campaign', '%name%' => 'Spring campaigns']]],
$this->createValidator()->validateUtmParameters(['utm_campaign' => 'spring'], $taxonomy)
);
}
public function testWithoutATaxonomyTheGlobalConfigurationApplies(): void
{
$validator = $this->createValidator();
// Free parameter: any well-formed value; dropdown: only the configured list.
$this->assertSame([], $validator->validateUtmParameters(['utm_campaign' => 'spring', 'utm_source' => 'newsletter']));
$this->assertSame([], $validator->validateUtmParameters(['utm_campaign' => 'spring'], null, ['utm_campaign' => 'spring']));
$this->assertSame(
[[SmartLinkValidator::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => 'utm_source', '%value%' => 'facebook']]],
$validator->validateUtmParameters(['utm_source' => 'facebook'])
);
}
}