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,147 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Catalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterDefinition;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
final class UtmParameterCatalogTest extends TestCase
{
private const STANDARD_MODES = [
'utm_source' => UtmParameterMode::DROPDOWN,
'utm_medium' => UtmParameterMode::DROPDOWN,
'utm_campaign' => UtmParameterMode::FREE,
'utm_term' => UtmParameterMode::FREE,
'utm_content' => UtmParameterMode::FREE,
'utm_id' => UtmParameterMode::FREE,
'utm_source_platform' => UtmParameterMode::DROPDOWN,
'utm_creative_format' => UtmParameterMode::DROPDOWN,
'utm_marketing_tactic' => UtmParameterMode::DROPDOWN,
];
private const PLATFORM_KEYS = ['gclid', 'gbraid', 'wbraid', 'dclid', 'fbclid', 'msclkid', 'ttclid', 'li_fat_id', 'twclid', 'epik'];
private UtmParameterCatalog $catalog;
protected function setUp(): void
{
$this->catalog = new UtmParameterCatalog();
}
public function testCatalogContainsExactlyTheExpectedKeysInOrder(): void
{
$this->assertSame(
array_merge(array_keys(self::STANDARD_MODES), self::PLATFORM_KEYS),
array_keys($this->catalog->all())
);
}
public function testStandardParameters(): void
{
$standard = $this->catalog->getByGroup(UtmParameterCatalog::GROUP_STANDARD);
$this->assertSame(array_keys(self::STANDARD_MODES), array_keys($standard));
foreach (self::STANDARD_MODES as $key => $mode) {
$definition = $standard[$key];
$this->assertSame($mode, $definition->defaultMode, $key);
$this->assertFalse($definition->autoGenerated, $key);
$this->assertSame(UtmParameterMode::ALL, $definition->getAllowedModes(), $key);
$this->assertSame('mautic.smartlinks.config.parameter.'.$key.'.label', $definition->getLabelKey());
$this->assertSame('mautic.smartlinks.config.parameter.'.$key.'.description', $definition->getDescriptionKey());
}
}
public function testPlatformParametersAreAutoGeneratedDisabledAndCannotBeDropdowns(): void
{
$platform = $this->catalog->getByGroup(UtmParameterCatalog::GROUP_PLATFORM);
$this->assertSame(self::PLATFORM_KEYS, array_keys($platform));
foreach ($platform as $key => $definition) {
$this->assertTrue($definition->autoGenerated, $key);
$this->assertSame(UtmParameterMode::DISABLED, $definition->defaultMode, $key);
$this->assertSame([UtmParameterMode::FREE, UtmParameterMode::DISABLED], $definition->getAllowedModes(), $key);
$this->assertFalse($definition->isModeAllowed(UtmParameterMode::DROPDOWN), $key);
$this->assertSame([], $definition->suggestions, $key);
}
}
public function testSuggestionsOnlyForDropdownParameters(): void
{
$this->assertSame(
['newsletter', 'linkedin', 'facebook', 'instagram', 'google', 'youtube', 'x', 'tiktok', 'partner', 'direct'],
$this->catalog->get('utm_source')?->suggestions
);
$this->assertSame(
['email', 'cpc', 'social', 'social_paid', 'display', 'affiliate', 'referral', 'qr', 'sms', 'print', 'event'],
$this->catalog->get('utm_medium')?->suggestions
);
$this->assertSame(['google_ads', 'meta_ads', 'linkedin_ads', 'microsoft_ads', 'tiktok_ads'], $this->catalog->get('utm_source_platform')?->suggestions);
$this->assertSame(['banner', 'video', 'carousel', 'text', 'native'], $this->catalog->get('utm_creative_format')?->suggestions);
$this->assertSame(['prospecting', 'remarketing', 'retargeting', 'brand', 'nurturing'], $this->catalog->get('utm_marketing_tactic')?->suggestions);
foreach ($this->catalog->all() as $key => $definition) {
if (UtmParameterMode::DROPDOWN !== $definition->defaultMode) {
$this->assertSame([], $definition->suggestions, $key);
}
}
$this->assertSame('mautic.smartlinks.config.suggestion.google_ads', UtmParameterDefinition::getSuggestionLabelKey('google_ads'));
}
public function testGetAndHas(): void
{
$this->assertTrue($this->catalog->has('utm_source'));
$this->assertInstanceOf(UtmParameterDefinition::class, $this->catalog->get('gclid'));
$this->assertFalse($this->catalog->has('my_param'));
$this->assertNull($this->catalog->get('my_param'));
}
#[DataProvider('reservedKeys')]
public function testReservedKeys(string $key): void
{
$this->assertTrue($this->catalog->isReservedKey($key));
$this->assertFalse($this->catalog->isValidCustomKey($key));
}
/**
* @return iterable<string, array{string}>
*/
public static function reservedKeys(): iterable
{
yield 'catalog key' => ['utm_source'];
yield 'click id' => ['gclid'];
yield 'mautic click tracking' => ['ct'];
yield 'utm prefix' => ['utm_custom'];
yield 'utm prefix without underscore' => ['utmx'];
yield 'mtc prefix' => ['mtc_id'];
}
#[DataProvider('customKeys')]
public function testCustomKeyFormat(string $key, bool $valid): void
{
$this->assertSame($valid, $this->catalog->isValidCustomKey($key));
}
/**
* @return iterable<string, array{string, bool}>
*/
public static function customKeys(): iterable
{
yield 'simple' => ['ref', true];
yield 'with digits and underscore' => ['partner_id2', true];
yield 'two characters' => ['ab', true];
yield 'max 41 characters' => ['a'.str_repeat('b', 40), true];
yield 'one character' => ['a', false];
yield 'too long' => ['a'.str_repeat('b', 41), false];
yield 'starts with digit' => ['1abc', false];
yield 'starts with underscore' => ['_abc', false];
yield 'uppercase' => ['Abc', false];
yield 'hyphen' => ['my-param', false];
yield 'empty' => ['', false];
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Entity;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLinkHit;
use PHPUnit\Framework\TestCase;
final class SmartLinkHitTest extends TestCase
{
public function testHitCarriesTheRequestContext(): void
{
$link = new SmartLink();
$hit = new SmartLinkHit();
$hit->setSmartLink($link);
$hit->setIpAddress('2001:db8::1');
$hit->setReferer('https://newsletter.example.com/');
$hit->setUserAgent('curl/8.18.0');
$this->assertSame($link, $hit->getSmartLink());
$this->assertSame('2001:db8::1', $hit->getIpAddress());
$this->assertSame('https://newsletter.example.com/', $hit->getReferer());
$this->assertSame('curl/8.18.0', $hit->getUserAgent());
$this->assertNull($hit->getId());
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Entity;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectCode;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectType;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
use PHPUnit\Framework\TestCase;
final class SmartLinkTest extends TestCase
{
public function testSlugIsImmutableOnceSaved(): void
{
$link = new SmartLink();
$link->setSlug('abc');
// Not saved yet: the slug can still be set.
$link->setSlug('xyz');
$this->assertSame('xyz', $link->getSlug());
$reflection = new \ReflectionClass(SmartLink::class);
$property = $reflection->getProperty('id');
$property->setValue($link, 1);
// Saved: the same slug is accepted (no-op), a different one is refused.
$link->setSlug('xyz');
$this->assertSame('xyz', $link->getSlug());
$this->expectException(\LogicException::class);
$link->setSlug('other');
}
public function testMauticRedirectHasNoDestination(): void
{
$link = new SmartLink();
$link->setRedirectType(SmartLinkRedirectType::External);
$link->setDestinationUrl('https://www.example.com');
$this->assertSame('https://www.example.com', $link->getDestinationUrl());
$link->setRedirectType(SmartLinkRedirectType::Mautic);
$this->assertNull($link->getDestinationUrl());
}
public function testBlankDestinationIsNormalizedToNull(): void
{
$link = new SmartLink();
$link->setDestinationUrl(' ');
$this->assertNull($link->getDestinationUrl());
}
public function testUtmParametersAreStoredAsGiven(): void
{
// The model (normalizeUtmValues) cleans the values before they reach the entity.
$link = new SmartLink();
$link->setUtmParameters(['utm_source' => 'newsletter']);
$this->assertSame(['utm_source' => 'newsletter'], $link->getUtmParameters());
$link->setUtmParameters(null);
$this->assertSame([], $link->getUtmParameters());
}
public function testShortLinkIsBuiltFromDomainAndSlug(): void
{
$link = new SmartLink();
$link->setSlug('ab3x');
$this->assertSame('https://lnk.example.com/l/ab3x', $link->getShortLink('lnk.example.com'));
$this->assertSame('https://lnk.example.com/l/ab3x', $link->getShortLink('lnk.example.com/'));
$this->assertSame('', $link->getShortLink(''));
}
public function testRedirectEnums(): void
{
$this->assertTrue(SmartLinkRedirectType::External->isExternal());
$this->assertTrue(SmartLinkRedirectType::Mautic->isMautic());
$this->assertSame(SmartLinkRedirectCode::MovedPermanently, SmartLinkRedirectCode::tryFrom(301));
$this->assertSame(SmartLinkRedirectCode::PermanentRedirect, SmartLinkRedirectCode::tryFrom(308));
$this->assertNull(SmartLinkRedirectCode::tryFrom(418));
}
}
@@ -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'])
);
}
}
+250
View File
@@ -0,0 +1,250 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Model;
use Doctrine\ORM\EntityManagerInterface;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use Mautic\PageBundle\Model\PageModel;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationNormalizer;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
final class SmartLinkModelTest extends TestCase
{
/**
* A real provider with the given raw configuration, served through the normalizer.
*/
private function createProvider(array $raw): UtmConfigurationProvider
{
$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);
return new UtmConfigurationProvider(
$parameters,
new UtmConfigurationNormalizer(new UtmParameterCatalog()),
new UtmParameterCatalog(),
$translator
);
}
/**
* The model with mocked core dependencies; the UTM configuration is real.
*/
private function createModel(array $raw, ?PageModel $pageModel = null, ?UrlGeneratorInterface $router = null): SmartLinkModel
{
return new SmartLinkModel(
$this->createMock(EntityManagerInterface::class),
$this->createMock(CorePermissions::class),
$this->createMock(EventDispatcherInterface::class),
$router ?? $this->createMock(UrlGeneratorInterface::class),
$this->createMock(TranslatorInterface::class),
$this->createMock(UserHelper::class),
$this->createMock(LoggerInterface::class),
$this->createMock(CoreParametersHelper::class),
$this->createProvider($raw),
$pageModel ?? $this->createMock(PageModel::class)
);
}
public function testSlugRulesApplyOnNewLink(): void
{
$model = $this->createModel(['separator_replacement' => '_', 'enforce_lowercase' => '1']);
$link = $model->getEntity();
$model->applySlugRules($link, 'Big Camp');
$this->assertSame('big_camp', $link->getSlug());
}
public function testSlugRulesWithLowercaseDisabled(): void
{
$model = $this->createModel(['separator_replacement' => '-', 'enforce_lowercase' => '']);
$link = $model->getEntity();
$model->applySlugRules($link, 'Big Camp');
$this->assertSame('Big-Camp', $link->getSlug());
}
public function testSlugRulesKeepStoredSlugOnEdit(): void
{
$model = $this->createModel([]);
$reflection = new \ReflectionClass(\MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink::class);
$link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink();
$reflection->getProperty('id')->setValue($link, 1);
$link->setSlug('stored');
// The user never edits the slug of a saved link: the submitted value is ignored...
$model->applySlugRules($link);
$this->assertSame('stored', $link->getSlug());
// ...and passing a different slug explicitly is refused.
$this->expectException(\LogicException::class);
$model->applySlugRules($link, 'other');
}
public function testNormalizeUtmValues(): void
{
$model = $this->createModel(['enforce_lowercase' => '1']);
$this->assertSame(
// The model sorts the keys, so the stored array is deterministic.
['utm_medium' => 'email', 'utm_source' => 'acme'],
$model->normalizeUtmValues(['utm_source' => 'ACME ', 'utm_medium' => 'Email', 'utm_term' => ''])
);
$modelNoLower = $this->createModel(['enforce_lowercase' => '']);
$this->assertSame(
['utm_source' => 'ACME'],
$modelNoLower->normalizeUtmValues(['utm_source' => 'ACME'])
);
}
public function testNormalizeUtmValuesUsesValuePatternToo(): void
{
$model = $this->createModel(['enforce_lowercase' => '1']);
// Values of disabled parameters and empty values are dropped by the form; the model
// only applies the case and separator rules.
$this->assertSame(['a' => 'b'], $model->normalizeUtmValues(['a' => 'b', 'x' => null]));
}
public function testEnabledParameterDefaultModeIsRespected(): void
{
// An empty configuration leaves the utm_source dropdown switched off: an enabled
// dropdown needs values, and they are configured on the Configuration page.
$provider = $this->createProvider([]);
$source = $provider->getParameter('utm_source');
$this->assertNotNull($source);
$this->assertFalse($source['enabled']);
$this->assertSame(UtmParameterMode::DROPDOWN, $source['mode']);
$this->assertSame([], $provider->getDropdownValues('utm_source'));
// Enabled with stored values it stays a dropdown and serves them.
$enabled = $this->createProvider(['parameters' => [
'utm_source' => [
'enabled' => '1',
'label' => 'Source',
'mode' => 'dropdown',
'values' => [['value' => 'newsletter', 'label' => 'Newsletter']],
],
]]);
$source = $enabled->getParameter('utm_source');
$this->assertTrue($source['enabled']);
$this->assertSame(UtmParameterMode::DROPDOWN, $source['mode']);
$this->assertNotSame([], $enabled->getDropdownValues('utm_source'));
}
/**
* @param array<string, string> $utms
*/
#[DataProvider('redirectUrlProvider')]
public function testBuildRedirectUrl(string $destination, array $utms, string $expected): void
{
$link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink();
$link->setDestinationUrl($destination);
$link->setUtmParameters($utms);
$this->assertSame($expected, $this->createModel([])->buildRedirectUrl($link));
}
/**
* @return iterable<string, array{0: string, 1: array<string, string>, 2: string}>
*/
public static function redirectUrlProvider(): iterable
{
yield 'no utm parameters keeps destination as-is' => [
'https://www.example.com/spring',
[],
'https://www.example.com/spring',
];
yield 'parameters are appended to a bare destination' => [
'https://www.example.com/spring',
['utm_source' => 'newsletter', 'utm_medium' => 'email'],
'https://www.example.com/spring?utm_source=newsletter&utm_medium=email',
];
yield 'existing query is kept, link parameters override same-named ones' => [
'https://www.example.com/spring?foo=bar&utm_medium=paid',
['utm_medium' => 'email', 'utm_source' => 'newsletter'],
'https://www.example.com/spring?foo=bar&utm_medium=email&utm_source=newsletter',
];
yield 'fragment and parts of the destination survive' => [
'https://user.example.com:8443/path/page#section',
['utm_source' => 'x'],
'https://user.example.com:8443/path/page?utm_source=x#section',
];
}
public function testBuildMauticDestinationUrlWithoutDestinationIsEmpty(): void
{
$link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink();
$this->assertSame('', $this->createModel([])->buildMauticDestinationUrl($link));
}
public function testBuildMauticDestinationUrlUsesThePageModel(): void
{
$pageModel = $this->createMock(PageModel::class);
$pageModel->method('generateUrl')->willReturn('https://mautic.example.com/landing');
$link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink();
$reflection = new \ReflectionClass(\MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink::class);
$reflection->getProperty('page')->setValue($link, $this->createMock(\Mautic\PageBundle\Entity\Page::class));
$this->assertSame('https://mautic.example.com/landing', $this->createModel([], $pageModel)->buildMauticDestinationUrl($link));
}
public function testBuildMauticDestinationUrlUsesTheFormPreviewRoute(): void
{
$router = $this->createMock(UrlGeneratorInterface::class);
$router->method('generate')
->with('mautic_form_preview', ['id' => 7], UrlGeneratorInterface::ABSOLUTE_URL)
->willReturn('https://mautic.example.com/form/7');
$form = $this->createMock(\Mautic\FormBundle\Entity\Form::class);
$form->method('getId')->willReturn(7);
$link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink();
$reflection = new \ReflectionClass(\MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink::class);
$reflection->getProperty('form')->setValue($link, $form);
$this->assertSame('https://mautic.example.com/form/7', $this->createModel([], null, $router)->buildMauticDestinationUrl($link));
}
public function testBuildRedirectUrlAppendsUtmToMauticDestinations(): void
{
$pageModel = $this->createMock(PageModel::class);
$pageModel->method('generateUrl')->willReturn('https://mautic.example.com/landing');
$link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink();
$link->setRedirectType(\MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectType::Mautic);
$link->setUtmParameters(['utm_source' => 'newsletter']);
$reflection = new \ReflectionClass(\MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink::class);
$reflection->getProperty('page')->setValue($link, $this->createMock(\Mautic\PageBundle\Entity\Page::class));
$this->assertSame(
'https://mautic.example.com/landing?utm_source=newsletter',
$this->createModel([], $pageModel)->buildRedirectUrl($link)
);
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Model;
use Doctrine\ORM\EntityManagerInterface;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use MauticPlugin\MT3SMarketingProgramBundle\Model\UtmTaxonomyModel;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
final class UtmTaxonomyModelTest extends TestCase
{
private function createModel(): UtmTaxonomyModel
{
return new UtmTaxonomyModel(
$this->createMock(EntityManagerInterface::class),
$this->createMock(CorePermissions::class),
$this->createMock(EventDispatcherInterface::class),
$this->createMock(UrlGeneratorInterface::class),
$this->createMock(TranslatorInterface::class),
$this->createMock(UserHelper::class),
$this->createMock(LoggerInterface::class),
$this->createMock(CoreParametersHelper::class)
);
}
public function testNormalizeParametersTrimsDeduplicatesSortsAndFallsBackToTheValueAsLabel(): void
{
$clean = $this->createModel()->normalizeParameters([
'utm_source' => [
['value' => ' newsletter ', 'label' => 'Newsletter'],
['value' => 'newsletter', 'label' => 'Duplicate value, dropped'],
['value' => '', 'label' => 'Empty value, dropped'],
'not-an-array',
],
'utm_campaign' => [
['value' => 'spring', 'label' => ''],
],
' ' => [['value' => 'x', 'label' => 'X']],
'not-an-array' => 'nope',
]);
$this->assertSame([
'utm_campaign' => [
['value' => 'spring', 'label' => 'spring'],
],
'utm_source' => [
['value' => 'newsletter', 'label' => 'Newsletter'],
],
], $clean);
}
public function testNormalizeParametersDropsParametersWithoutValues(): void
{
$this->assertSame([], $this->createModel()->normalizeParameters([
'utm_source' => [['value' => '', 'label' => 'Empty']],
'gclid' => [],
]));
}
}
@@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Tests\Unit\Service;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationNormalizer;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Contracts\Translation\TranslatorInterface;
final class UtmConfigurationProviderTest extends TestCase
{
/**
* The shape Mautic writes to local.php: nested scalars are strings ('1' / '').
*/
private const STORED = [
'enforce_lowercase' => '',
'separator_replacement' => '_',
'parameters' => [
'utm_source' => [
'enabled' => '1',
'label' => 'Source',
'mode' => 'dropdown',
'values' => [
['value' => 'newsletter', 'label' => 'Newsletter'],
['value' => 'linkedin', 'label' => 'LinkedIn'],
],
'default' => 'linkedin',
],
'utm_medium' => [
'enabled' => '',
'label' => 'Medium',
'mode' => 'dropdown',
'values' => [['value' => 'email', 'label' => 'Email']],
'default' => '',
],
// Values left in storage for a free parameter must never be exposed.
'utm_campaign' => [
'enabled' => '1',
'label' => '',
'mode' => 'free',
'values' => [['value' => 'should_not_appear', 'label' => 'x']],
'default' => 'should_not_appear',
],
'utm_term' => ['enabled' => '1', 'label' => 'Term', 'mode' => 'disabled'],
'gclid' => ['enabled' => '1', 'label' => 'GCLID', 'mode' => 'free'],
// Dropdown isn't allowed for click IDs: falls back to the default mode (disabled).
'fbclid' => ['enabled' => '1', 'label' => 'FB', 'mode' => 'dropdown', 'values' => [['value' => 'a', 'label' => 'a']]],
'partner' => ['enabled' => '1', 'label' => 'Partner', 'mode' => 'dropdown', 'values' => [['value' => 'acme', 'label' => 'ACME']], 'default' => ''],
'utm_hack' => ['enabled' => '1', 'label' => 'Invalid custom key', 'mode' => 'free'],
],
];
public function testGetEnabledParameters(): void
{
$enabled = $this->createProvider(self::STORED)->getEnabledParameters();
// Enabled and not in disabled mode, catalog order first, then custom parameters.
$this->assertSame(['utm_source', 'utm_campaign', 'utm_content', 'utm_id', 'gclid', 'partner'], array_keys($enabled));
$this->assertSame([
'key' => 'utm_source',
'enabled' => true,
'label' => 'Source',
'mode' => UtmParameterMode::DROPDOWN,
'values' => [
['value' => 'newsletter', 'label' => 'Newsletter'],
['value' => 'linkedin', 'label' => 'LinkedIn'],
],
'default' => 'linkedin',
'group' => UtmParameterCatalog::GROUP_STANDARD,
'custom' => false,
'auto_generated' => false,
], $enabled['utm_source']);
$this->assertTrue($enabled['partner']['custom']);
$this->assertSame(UtmParameterCatalog::GROUP_CUSTOM, $enabled['partner']['group']);
$this->assertTrue($enabled['gclid']['auto_generated']);
}
public function testFreeParameterExposesNoValues(): void
{
$provider = $this->createProvider(self::STORED);
$campaign = $provider->getParameter('utm_campaign');
$this->assertSame([
'key' => 'utm_campaign',
'enabled' => true,
'label' => 'translated:mautic.smartlinks.config.parameter.utm_campaign.label',
'mode' => UtmParameterMode::FREE,
'group' => UtmParameterCatalog::GROUP_STANDARD,
'custom' => false,
'auto_generated' => false,
], $campaign);
$this->assertSame([], $provider->getDropdownValues('utm_campaign'));
}
public function testGetParameter(): void
{
$provider = $this->createProvider(self::STORED);
$this->assertSame(UtmParameterMode::DISABLED, $provider->getParameter('utm_term')['mode'] ?? null);
$this->assertArrayNotHasKey('values', $provider->getParameter('utm_term') ?? []);
$this->assertSame(UtmParameterMode::DISABLED, $provider->getParameter('fbclid')['mode'] ?? null);
$this->assertFalse($provider->getParameter('utm_medium')['enabled'] ?? null);
$this->assertArrayHasKey('default', $provider->getParameter('utm_medium'));
$this->assertNull($provider->getParameter('utm_medium')['default']);
$this->assertSame('Partner', $provider->getParameter('partner')['label'] ?? null);
$this->assertNull($provider->getParameter('unknown'));
$this->assertNull($provider->getParameter('utm_hack'), 'Custom keys with a reserved prefix are ignored.');
}
public function testGetDropdownValues(): void
{
$provider = $this->createProvider(self::STORED);
$this->assertSame(
[['value' => 'newsletter', 'label' => 'Newsletter'], ['value' => 'linkedin', 'label' => 'LinkedIn']],
$provider->getDropdownValues('utm_source')
);
$this->assertSame([['value' => 'acme', 'label' => 'ACME']], $provider->getDropdownValues('partner'));
$this->assertSame([['value' => 'email', 'label' => 'Email']], $provider->getDropdownValues('utm_medium'));
$this->assertSame([], $provider->getDropdownValues('utm_term'));
$this->assertSame([], $provider->getDropdownValues('gclid'));
$this->assertSame([], $provider->getDropdownValues('fbclid'));
$this->assertSame([], $provider->getDropdownValues('unknown'));
}
public function testGeneralSettings(): void
{
$provider = $this->createProvider(self::STORED);
$this->assertFalse($provider->isLowercaseEnforced());
$this->assertSame('_', $provider->getSeparatorReplacement());
}
public function testDefaultsWhenNothingIsStored(): void
{
$provider = $this->createProvider(null);
$this->assertTrue($provider->isLowercaseEnforced());
$this->assertSame('-', $provider->getSeparatorReplacement());
// Free catalog parameters are enabled by default, dropdown parameters wait for values, click IDs are disabled.
$this->assertSame(['utm_campaign', 'utm_term', 'utm_content', 'utm_id'], array_keys($provider->getEnabledParameters()));
$this->assertSame(UtmParameterMode::DROPDOWN, $provider->getParameter('utm_source')['mode'] ?? null);
$this->assertFalse($provider->getParameter('utm_source')['enabled'] ?? null);
$this->assertSame([], $provider->getDropdownValues('utm_source'));
$this->assertSame(UtmParameterMode::DISABLED, $provider->getParameter('gclid')['mode'] ?? null);
}
public function testInvalidSeparatorFallsBackToHyphen(): void
{
$this->assertSame('-', $this->createProvider(['separator_replacement' => ' '])->getSeparatorReplacement());
}
public function testLegacyParameterIsServedUntilTheNewOneIsSaved(): void
{
// Upgrades from < 0.5.0: the new key is empty, the settings live under the legacy key.
$provider = $this->createProvider([], self::STORED);
$this->assertFalse($provider->isLowercaseEnforced());
$this->assertSame('_', $provider->getSeparatorReplacement());
$this->assertSame(
['utm_source', 'utm_campaign', 'utm_content', 'utm_id', 'gclid', 'partner'],
array_keys($provider->getEnabledParameters())
);
}
private function createProvider(mixed $stored, ?array $legacy = null): UtmConfigurationProvider
{
$parameters = $this->createMock(CoreParametersHelper::class);
$parameters->method('get')
->willReturnCallback(
fn (string $name, mixed $default = null): mixed => match (true) {
UtmConfigurationProvider::CONFIG_PARAMETER === $name => $stored,
UtmConfigurationProvider::LEGACY_CONFIG_PARAMETER === $name && null !== $legacy => $legacy,
default => $default,
}
);
$translator = $this->createMock(TranslatorInterface::class);
$translator->method('trans')->willReturnCallback(fn (string $key): string => 'translated:'.$key);
$catalog = new UtmParameterCatalog();
return new UtmConfigurationProvider($parameters, new UtmConfigurationNormalizer($catalog), $catalog, $translator);
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
/*
* Finds the autoloader of the Mautic installation this plugin is mounted in
* (docroot/plugins/MT3SMarketingProgramBundle in the recommended project).
*/
$directory = __DIR__;
for ($level = 0; $level < 6; ++$level) {
$directory = dirname($directory);
if (is_file($directory.'/vendor/autoload.php')) {
require $directory.'/vendor/autoload.php';
return;
}
}
throw new RuntimeException('Mautic vendor/autoload.php not found. Run the tests from a Mautic installation.');