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,146 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\DataTransformer;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationNormalizer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Converts between the stored `smartlinks_utm_config` array (parameters keyed by their key)
* and the form structure (catalog parameters + a collection of custom parameters).
*
* @implements DataTransformerInterface<mixed, array<string, mixed>>
*/
final class UtmSettingsTransformer implements DataTransformerInterface
{
public function __construct(
private readonly UtmConfigurationNormalizer $normalizer,
private readonly UtmParameterCatalog $catalog,
private readonly TranslatorInterface $translator,
) {
}
/**
* Stored configuration => form data.
*
* @return array<string, mixed>
*/
public function transform(mixed $value): array
{
$config = $this->normalizer->normalize($value);
$parameters = [];
$custom = [];
foreach ($config['parameters'] as $key => $parameter) {
$definition = $this->catalog->get($key);
$row = [
'enabled' => $parameter['enabled'],
'label' => $parameter['label'],
'mode' => $parameter['mode'],
'values' => $this->valuesToForm($parameter['values'] ?? [], $parameter['default'] ?? null),
];
if (null === $definition) {
$custom[] = ['key' => $key] + $row;
continue;
}
if ('' === $row['label']) {
$row['label'] = $this->translator->trans($definition->getLabelKey());
}
$parameters[$key] = $row;
}
return [
'enforce_lowercase' => $config['enforce_lowercase'],
'separator_replacement' => $config['separator_replacement'],
'parameters' => $parameters,
'custom_parameters' => $custom,
];
}
/**
* Form data => stored configuration.
*
* @return array<string, mixed>
*/
public function reverseTransform(mixed $value): array
{
$value = is_array($value) ? $value : [];
$parameters = [];
foreach ($value['parameters'] ?? [] as $key => $parameter) {
$parameters[(string) $key] = $this->parameterToStorage($parameter);
}
foreach ($value['custom_parameters'] ?? [] as $parameter) {
$key = trim((string) ($parameter['key'] ?? ''));
if ('' !== $key) {
$parameters[$key] = $this->parameterToStorage($parameter);
}
}
return [
'enforce_lowercase' => UtmConfigurationNormalizer::toBool($value['enforce_lowercase'] ?? true),
'separator_replacement' => (string) ($value['separator_replacement'] ?? UtmConfigurationNormalizer::DEFAULT_SEPARATOR),
'parameters' => $parameters,
];
}
/**
* Only `dropdown` parameters keep values and a default; nothing else is stored for the other modes.
*
* @param array<string, mixed> $parameter
*
* @return array<string, mixed>
*/
private function parameterToStorage(array $parameter): array
{
$mode = (string) ($parameter['mode'] ?? UtmParameterMode::DISABLED);
$stored = [
'enabled' => UtmConfigurationNormalizer::toBool($parameter['enabled'] ?? false),
'label' => trim((string) ($parameter['label'] ?? '')),
'mode' => $mode,
];
if (UtmParameterMode::DROPDOWN !== $mode) {
return $stored;
}
$stored['values'] = [];
$stored['default'] = '';
foreach ($parameter['values'] ?? [] as $row) {
$rowValue = trim((string) ($row['value'] ?? ''));
if ('' === $rowValue) {
continue;
}
$stored['values'][] = ['value' => $rowValue, 'label' => trim((string) ($row['label'] ?? ''))];
if ('' === $stored['default'] && !empty($row['is_default'])) {
$stored['default'] = $rowValue;
}
}
return $stored;
}
/**
* @param list<array{value: string, label: string}> $values
*
* @return list<array{value: string, label: string, is_default: bool}>
*/
private function valuesToForm(array $values, ?string $default): array
{
return array_map(
fn (array $row): array => $row + ['is_default' => $row['value'] === $default],
$values
);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Extension;
use Mautic\EmailBundle\Form\Type\EmailUtmTagsType;
use MauticPlugin\MT3SMarketingProgramBundle\Form\UtmFieldsApplicator;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Applies the UTM taxonomy to the "UTM tags" subform. Core uses EmailUtmTagsType for both
* the Email form (EmailType) and the Focus Item form (FocusType), so this covers both.
*
* Registered as `form.type_extension` by autoconfiguration (Config/services.php).
*
* @extends AbstractTypeExtension<mixed>
*/
final class UtmTagsTypeExtension extends AbstractTypeExtension
{
public function __construct(
private readonly UtmFieldsApplicator $applicator,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$this->applicator->apply($builder);
}
/**
* @return iterable<class-string>
*/
public static function getExtendedTypes(): iterable
{
return [EmailUtmTagsType::class];
}
}
+606
View File
@@ -0,0 +1,606 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Mautic\CoreBundle\Form\Type\FormButtonsType;
use Mautic\FormBundle\Entity\Form as MauticForm;
use Mautic\PageBundle\Entity\Page;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectCode;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectType;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\SmartLinkValidator;
use MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel;
use MauticPlugin\MT3SMarketingProgramBundle\Service\SmartLinkShortUrlBuilder;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Create / edit a Smart Link.
*
* - the slug is disabled once the link is saved (a saved link can only be deleted, never renamed);
* - a "Generate" button (JavaScript) offers a random 4-character slug of letters and digits;
* - the destination URL only applies to external redirect types (Mautic redirects are not
* processed yet);
* - the link carries a UTM Taxonomy (required): one fieldset per taxonomy is rendered, each
* field a select restricted to the values the taxonomy allows for its parameter. Mautic's
* data-show-on switcher shows the fieldset of the chosen taxonomy; the values posted for
* the others are dropped on submit. A stored value outside the list stays selectable,
* labelled "(not in taxonomy)", so an old link is still editable.
*
* @extends AbstractType<SmartLink>
*/
final class SmartLinkType extends AbstractType
{
/**
* The values the link carried when the form was built: a value outside its taxonomy stays
* acceptable (it was chosen when the taxonomy allowed it), so a plain re-save never errors.
*
* @var array<string, string>
*/
private array $originalUtmParameters = [];
public function __construct(
private readonly SmartLinkValidator $validator,
private readonly SmartLinkShortUrlBuilder $shortUrlBuilder,
private readonly UtmConfigurationProvider $utmConfiguration,
private readonly SmartLinkModel $smartLinkModel,
private readonly TranslatorInterface $translator,
private readonly EntityManagerInterface $entityManager,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
/** @var SmartLink $smartLink */
$smartLink = $options['data'];
$isSaved = null !== $smartLink->getId();
$this->originalUtmParameters = $smartLink->getUtmParameters();
// -- Slug --------------------------------------------------------------
// Spaces are replaced by the configured character and lowercase is enforced by the model
// on save, exactly like the live preview does. The constraints only guard the raw input;
// spaces are allowed here because they are turned into the separator on save.
$builder->add('slug', TextType::class, [
'label' => 'mautic.smartlinks.smart_links.slug',
'required' => true,
'disabled' => $isSaved,
'attr' => [
'class' => 'form-control smart-link-slug',
'maxlength' => SmartLink::SLUG_MAX_LENGTH,
'tooltip' => 'mautic.smartlinks.smart_links.slug.tooltip',
// Live preview of the short link: the JS fills the span next to the field.
'data-preview' => 'smart-link-preview',
],
'constraints' => $isSaved ? [] : [
new NotBlank(message: 'mautic.smartlinks.smart_links.error.slug_required'),
new Length(max: SmartLink::SLUG_MAX_LENGTH, maxMessage: 'mautic.smartlinks.smart_links.error.slug_length'),
new Regex(
pattern: '/^[\p{L}0-9\-_. ]*$/u',
message: 'mautic.smartlinks.smart_links.error.slug_characters'
),
new Callback(callback: $this->validateSlug(...)),
],
]);
// -- Redirect ------------------------------------------------------------
$builder->add('redirectType', EnumType::class, [
'label' => 'mautic.smartlinks.smart_links.redirect_type',
'class' => SmartLinkRedirectType::class,
'choice_label' => fn (SmartLinkRedirectType $type): string => $this->translator->trans($type->getLabelKey()),
'attr' => ['class' => 'form-control smart-link-redirect-type'],
]);
$builder->add('redirectCode', EnumType::class, [
'label' => 'mautic.smartlinks.smart_links.redirect_code',
'class' => SmartLinkRedirectCode::class,
'choice_label' => fn (SmartLinkRedirectCode $code): string => $code->getTranslatedLabel($this->translator),
'attr' => ['class' => 'form-control smart-link-redirect-code'],
]);
$builder->add('destinationUrl', UrlType::class, [
'label' => 'mautic.smartlinks.smart_links.destination_url',
'required' => false,
'attr' => [
'class' => 'form-control smart-link-destination',
'tooltip' => 'mautic.smartlinks.smart_links.destination_url.tooltip',
],
'constraints' => [new Callback(callback: $this->validateDestination(...))],
]);
// -- Mautic destination: a landing page or a standalone form -------------------------
$builder->add('destination', ChoiceType::class, [
'label' => 'mautic.smartlinks.smart_links.destination',
'required' => false,
'mapped' => false,
'attr' => [
'class' => 'form-control smart-link-mautic-destination',
'tooltip' => 'mautic.smartlinks.smart_links.destination.tooltip',
],
'choices' => $this->buildMauticDestinationChoices($smartLink),
'placeholder' => 'mautic.smartlinks.form.choose',
'data' => $this->currentMauticDestination($smartLink),
]);
// -- UTM Taxonomy ------------------------------------------------------------
// The taxonomy of the link drives its UTM values. Required: a link always carries one
// from now on; a link that predates the feature picks one on its next edit. A stored
// taxonomy that is no longer published stays selectable, so an old link is still
// editable (a new one can always be chosen instead).
$builder->add('taxonomy', ChoiceType::class, [
'label' => 'mautic.smartlinks.smart_links.taxonomy',
'required' => true,
'placeholder' => 'mautic.smartlinks.form.choose',
'choices' => $this->buildTaxonomyChoices($smartLink),
'choice_value' => fn (?UtmTaxonomy $taxonomy): string => (string) ($taxonomy?->getId() ?? ''),
'attr' => [
'class' => 'form-control smart-link-taxonomy',
'tooltip' => 'mautic.smartlinks.smart_links.taxonomy.tooltip',
],
'constraints' => [new NotBlank(message: 'mautic.smartlinks.smart_links.error.taxonomy_required')],
]);
// -- UTM parameters ------------------------------------------------------------
// One fieldset per taxonomy, one select per parameter the taxonomy defines: the choices
// are the values the taxonomy allows. All the fieldsets are rendered at once;
// Mautic's data-show-on switcher (form.vars.smart_link_utm_fieldsets) shows the one of
// the chosen taxonomy, and the SUBMIT listener below drops the values of the others.
$builder->add('utmParameters', FormType::class, [
'label' => false,
'constraints' => [new Callback(callback: $this->validateUtmParameters(...))],
]);
$taxonomies = $this->getFormTaxonomies($smartLink);
foreach ($taxonomies as $taxonomy) {
// The dropdown parameters the taxonomy limits: a select with its subset as choices.
foreach ($this->getTaxonomyParameterKeys($taxonomy) as $key) {
$builder->get('utmParameters')->add(
self::fieldsetChildName($taxonomy, $key),
ChoiceType::class,
$this->buildTaxonomyFieldOptions($taxonomy, $key, $smartLink)
);
}
}
// The stored values (parameter key => value) feed the fieldset children
// (t<taxonomyId>_<key>): every select shows what the link already carries.
$builder->get('utmParameters')->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($taxonomies): void {
$stored = is_array($event->getData()) ? $event->getData() : [];
$expanded = [];
foreach ($taxonomies as $taxonomy) {
foreach ($this->getTaxonomyFieldsetKeys($taxonomy) as $key) {
$expanded[self::fieldsetChildName($taxonomy, $key)] = (string) ($stored[$key] ?? '');
}
}
$event->setData($expanded);
});
// Back to the stored shape: only the fieldset of the chosen taxonomy survives,
// stripped of its prefix, without the empty values, keys in display order.
$builder->get('utmParameters')->addEventListener(FormEvents::SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (!is_array($data)) {
$event->setData([]);
return;
}
$taxonomy = $this->submittedTaxonomy($event->getForm());
$flat = [];
if (null !== $taxonomy) {
$prefix = self::fieldsetPrefix($taxonomy);
foreach ($data as $name => $value) {
if (\is_string($value) && '' !== trim($value) && str_starts_with((string) $name, $prefix)) {
$flat[substr((string) $name, \strlen($prefix))] = trim($value);
}
}
}
ksort($flat);
$event->setData($flat);
});
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($isSaved): void {
$data = $event->getData();
if (!is_array($data)) {
return;
}
$type = SmartLinkRedirectType::tryFrom((string) ($data['redirectType'] ?? ''));
// The URL only exists for external redirects; the Mautic destination only for
// Mautic ones. Drop whatever doesn't apply before the form is processed.
if (null === $type || $type->isMautic()) {
unset($data['destinationUrl']);
} else {
unset($data['destination']);
}
// Never accept a modified slug from a stale form (the field is disabled on edit).
if ($isSaved && \array_key_exists('slug', $data)) {
unset($data['slug']);
}
$event->setData($data);
});
// The unmapped "destination" choice becomes the page or the form of the link.
$builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event): void {
$link = $event->getData();
$form = $event->getForm();
$value = $form->has('destination') ? $form->get('destination')->getData() : null;
if (!$link instanceof SmartLink) {
return;
}
[$kind, $id] = false !== strpos((string) $value, ':') ? explode(':', (string) $value, 2) : [null, null];
$page = 'page' === $kind && null !== $id ? $this->getPageRepository()->find($id) : null;
$form = 'form' === $kind && null !== $id ? $this->getFormRepository()->find($id) : null;
$link->setPage($page instanceof Page ? $page : null);
$link->setForm($form instanceof MauticForm ? $form : null);
});
$builder->add('buttons', FormButtonsType::class);
if (!empty($options['action'])) {
$builder->setAction($options['action']);
}
}
/**
* The taxonomies rendered on the form: the published ones, plus the taxonomy the link
* carries even when it is no longer published (so an old link stays editable).
*
* @return list<UtmTaxonomy>
*/
private function getFormTaxonomies(SmartLink $smartLink): array
{
$taxonomies = $this->getTaxonomyRepository()->findBy(['isPublished' => true], ['name' => 'ASC']);
$stored = $smartLink->getTaxonomy();
if (null !== $stored && !\in_array($stored, $taxonomies, true)) {
$taxonomies[] = $stored;
}
return $taxonomies;
}
/**
* The parameter keys a taxonomy offers on the Smart Link form: the ones it defines values
* for and that are still enabled in Smart Links Settings.
*
* @return list<string>
*/
private function getTaxonomyParameterKeys(UtmTaxonomy $taxonomy): array
{
return array_values(array_intersect(
$taxonomy->getParameterKeys(),
array_keys($this->utmConfiguration->getEnabledParameters())
));
}
/**
* The choices of the taxonomy select: the published taxonomies (label = name), plus the
* taxonomy the link carries even when it is no longer published.
*
* @return array<string, UtmTaxonomy>
*/
private function buildTaxonomyChoices(SmartLink $smartLink): array
{
$choices = [];
foreach ($this->getFormTaxonomies($smartLink) as $taxonomy) {
$label = (string) $taxonomy->getName();
if (!$taxonomy->isPublished()) {
$label = $this->translator->trans('mautic.smartlinks.taxonomies.unpublished_choice', ['%name%' => $label]);
}
$choices[$label] = $taxonomy;
}
return $choices;
}
/**
* One UTM parameter select of a taxonomy fieldset: the choices are the values the taxonomy
* allows. A stored value outside the list stays selectable, labelled "(not in taxonomy)",
* so an old link is still editable (it is rejected on save by SmartLinkValidator).
*
* @return array<string, mixed>
*/
private function buildTaxonomyFieldOptions(UtmTaxonomy $taxonomy, string $key, SmartLink $smartLink): array
{
$choices = [];
foreach ($taxonomy->getParameterValues($key) as $row) {
$choices[$row['label']] = $row['value'];
}
$stored = (string) ($smartLink->getUtmParameters()[$key] ?? '');
if ('' !== $stored && !\in_array($stored, $choices, true)) {
$choices = [
$this->translator->trans('mautic.smartlinks.form.legacy_choice', ['%value%' => $stored]) => $stored,
] + $choices;
}
$parameter = $this->utmConfiguration->getParameter($key);
return [
'label' => (string) ($parameter['label'] ?? $key),
'required' => false,
'choices' => $choices,
'placeholder' => 'mautic.smartlinks.form.choose',
'attr' => ['class' => 'form-control smart-link-utm'],
];
}
/**
* The keys of one taxonomy fieldset: the dropdown parameters the taxonomy limits plus the
* parameters the admin left free, in display order.
*
* @return list<string>
*/
private function getTaxonomyFieldsetKeys(UtmTaxonomy $taxonomy): array
{
return $this->getTaxonomyParameterKeys($taxonomy);
}
/**
* The prefix of the utmParameters children of one taxonomy fieldset: t<taxonomyId>_.
*/
private static function fieldsetPrefix(UtmTaxonomy $taxonomy): string
{
return 't'.(string) $taxonomy->getId().'_';
}
private static function fieldsetChildName(UtmTaxonomy $taxonomy, string $key): string
{
return self::fieldsetPrefix($taxonomy).$key;
}
/**
* The submitted taxonomy of the form (null when none was chosen).
*/
private function submittedTaxonomy(FormInterface $utmParameters): ?UtmTaxonomy
{
$taxonomy = $utmParameters->getParent()?->get('taxonomy')->getData();
return $taxonomy instanceof UtmTaxonomy ? $taxonomy : null;
}
private function getTaxonomyRepository(): EntityRepository
{
$repository = $this->entityManager->getRepository(UtmTaxonomy::class);
\assert($repository instanceof EntityRepository);
return $repository;
}
public function buildView(FormView $view, FormInterface $form, array $options): void
{
/** @var SmartLink $smartLink */
$smartLink = $form->getData();
$view->vars['smart_link_domain'] = $this->shortUrlBuilder->getShortLinkDomain();
$view->vars['smart_link_is_saved'] = null !== $smartLink->getId();
$view->vars['smart_link_slug'] = (string) ($smartLink->getSlug() ?? '');
$view->vars['smart_link_preview'] = $this->shortUrlBuilder->buildShortUrl($smartLink);
$view->vars['smart_link_separator'] = $this->utmConfiguration->getSeparatorReplacement();
$view->vars['smart_link_lowercase'] = $this->utmConfiguration->isLowercaseEnforced();
// Slug proposed by the "Generate" button; the empty "new" form starts with one.
$view->vars['smart_link_generated'] = null === $smartLink->getId() ? $this->smartLinkModel->generateSlug() : '';
// One rendered fieldset per taxonomy: the template wraps each in a data-show-on container
// keyed by the taxonomy select, so Mautic's switcher shows the chosen one.
$view->vars['smart_link_utm_fieldsets'] = [];
foreach ($this->getFormTaxonomies($smartLink) as $taxonomy) {
$view->vars['smart_link_utm_fieldsets'][(string) $taxonomy->getId()] = [
'id' => (string) $taxonomy->getId(),
'name' => (string) $taxonomy->getName(),
'prefix' => self::fieldsetPrefix($taxonomy),
'keys' => $this->getTaxonomyFieldsetKeys($taxonomy),
];
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['data_class' => SmartLink::class]);
}
public function getBlockPrefix(): string
{
return 'smartlinks_smart_link';
}
private function separator(): string
{
return $this->utmConfiguration->getSeparatorReplacement();
}
/**
* The repositories of the Mautic destinations, resolved lazily (the entity manager is
* injected once; the repositories are cheap Doctrine lookups).
*/
private function getPageRepository(): EntityRepository
{
$repository = $this->entityManager->getRepository(Page::class);
\assert($repository instanceof EntityRepository);
return $repository;
}
private function getFormRepository(): EntityRepository
{
$repository = $this->entityManager->getRepository(MauticForm::class);
\assert($repository instanceof EntityRepository);
return $repository;
}
private function validateSlug(mixed $slug, ExecutionContextInterface $context): void
{
/** @var SmartLink $smartLink */
$smartLink = $context->getRoot()->getData();
if (!$smartLink instanceof SmartLink) {
return;
}
$this->addViolations($context, $this->validator->validateSlug(
$this->normalizeSlug((string) $slug),
$smartLink->getId()
));
}
private function validateDestination(mixed $url, ExecutionContextInterface $context): void
{
/** @var SmartLink $smartLink */
$smartLink = $context->getRoot()->getData();
if (!$smartLink instanceof SmartLink) {
return;
}
$this->addViolations($context, $this->validator->validateDestination(
$smartLink->getRedirectType(),
is_string($url) ? $url : null,
$smartLink->getPage(),
$smartLink->getForm()
));
}
/**
* The published landing pages and standalone forms of the instance, grouped, with the
* link's current destination preselected. Only activated (published) ones are offered.
*
* @return array<string, string>
*/
private function buildMauticDestinationChoices(SmartLink $smartLink): array
{
$choices = [];
$values = [];
$pages = $this->getPageRepository()->findBy(['isPublished' => true], ['title' => 'ASC']);
foreach ($pages as $page) {
$value = 'page:'.$page->getId();
$choices['mautic.smartlinks.smart_links.destination.pages'][$page->getTitle()] = $value;
$values[] = $value;
}
$forms = $this->getFormRepository()->findBy(['isPublished' => true], ['name' => 'ASC']);
foreach ($forms as $form) {
$value = 'form:'.$form->getId();
$choices['mautic.smartlinks.smart_links.destination.forms'][$form->getName()] = $value;
$values[] = $value;
}
// A stored destination that is no longer published stays selectable, so an old link
// is still editable (it 404s until the page or the form is activated again). The
// guard must skip the "no destination" case: a null choice would make Symfony fall
// back to index-based values for every option.
$current = $this->currentMauticDestination($smartLink);
if (null !== $current && !in_array($current, $values, true)) {
$label = $smartLink->getPage()?->getTitle() ?? $smartLink->getForm()?->getName() ?? '';
$choices['mautic.smartlinks.smart_links.destination.unpublished'][$label] = $current;
}
return $choices;
}
/**
* The value of the unmapped destination field for the link's current page or form.
*/
private function currentMauticDestination(SmartLink $smartLink): ?string
{
if (null !== $smartLink->getPage()) {
return 'page:'.$smartLink->getPage()->getId();
}
if (null !== $smartLink->getForm()) {
return 'form:'.$smartLink->getForm()->getId();
}
return null;
}
/**
* Applies the UTM Manager settings to a typed slug, the same way the model will on save,
* so the uniqueness check compares the final slug.
*/
private function normalizeSlug(string $slug): string
{
$slug = str_replace(' ', $this->separator(), trim($slug));
if ($this->utmConfiguration->isLowercaseEnforced()) {
$slug = mb_strtolower($slug);
}
return $slug;
}
/**
* Runs SmartLinkValidator::validateUtmParameters() on the submitted values: against the
* chosen taxonomy, and with the values the link carried before the edit as allowed extras
* (a stored value outside the list can be saved unchanged: it was chosen when the list
* allowed it, and a plain re-save must never error).
*/
private function validateUtmParameters(mixed $values, ExecutionContextInterface $context): void
{
$form = $context->getObject();
if (!$form instanceof FormInterface) {
return;
}
// The model rebuilds the values (lowercase, filtered) in saveEntity(); the form hands
// the raw array: keys the user left empty are removed before validating.
$submitted = [];
foreach (is_array($values) ? $values : [] as $key => $value) {
if (\is_string($value) && '' !== trim($value)) {
$submitted[(string) $key] = trim($value);
}
}
$this->addViolations($context, $this->validator->validateUtmParameters(
$submitted,
$this->submittedTaxonomy($form),
$this->originalUtmParameters
));
}
/**
* @param list<array{0: string, 1: array<string, string>}> $errors
*/
private function addViolations(ExecutionContextInterface $context, array $errors): void
{
foreach ($errors as [$key, $parameters]) {
$context->buildViolation($key)->setParameters($parameters)->addViolation();
}
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* The single "Smart Links Settings" tab of Settings > Configuration: the general UTM rules and
* the short link domain (section "UTM Settings"), the catalog and custom parameters (section
* "Parameters"). Each child is a local.php parameter.
*
* @extends AbstractType<array<string, mixed>>
*/
final class SmartLinksConfigType extends AbstractType
{
/** Stored in local.php under this key (an array: short_link_domain => domain). */
public const CONFIG_PARAMETER = 'smartlinks_config';
/** Key of the UtmManagerBundle era (< 0.5.0); still honored until the domain is saved again. */
public const LEGACY_CONFIG_PARAMETER = 'utm_manager_smart_links';
public function buildForm(FormBuilderInterface $builder, array $options): void
{
// The general rules and the parameters: read everywhere through UtmConfigurationProvider.
$builder->add(UtmConfigurationProvider::CONFIG_PARAMETER, SmartlinksSettingsType::class);
$builder->add(self::CONFIG_PARAMETER, FormType::class, ['label' => false]);
$builder->get(self::CONFIG_PARAMETER)->add('short_link_domain', TextType::class, [
'label' => 'mautic.smartlinks.settings.short_link_domain',
'required' => false,
'attr' => [
'class' => 'form-control',
'tooltip' => 'mautic.smartlinks.settings.short_link_domain.tooltip',
],
]);
}
public function getBlockPrefix(): string
{
// The Configuration tab title key: mautic.config.tab.smartlinksconfig.
return 'smartlinksconfig';
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use Mautic\CoreBundle\Form\Type\YesNoButtonGroupType;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Form\DataTransformer\UtmSettingsTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* The `smartlinks_utm_config` parameter: general settings, catalog parameters and custom parameters.
*
* @extends AbstractType<array<string, mixed>>
*/
final class SmartlinksSettingsType extends AbstractType
{
public function __construct(
private readonly UtmParameterCatalog $catalog,
private readonly UtmSettingsTransformer $transformer,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('enforce_lowercase', YesNoButtonGroupType::class, [
'label' => 'mautic.smartlinks.config.enforce_lowercase',
'attr' => ['tooltip' => 'mautic.smartlinks.config.enforce_lowercase.tooltip'],
]);
$builder->add('separator_replacement', ChoiceType::class, [
'label' => 'mautic.smartlinks.config.separator_replacement',
'choices' => [
'mautic.smartlinks.config.separator.hyphen' => '-',
'mautic.smartlinks.config.separator.underscore' => '_',
'mautic.smartlinks.config.separator.dot' => '.',
],
'placeholder' => false,
'attr' => [
'class' => 'form-control',
'tooltip' => 'mautic.smartlinks.config.separator_replacement.tooltip',
],
'invalid_message' => 'mautic.smartlinks.config.error.separator_invalid',
]);
$parameters = $builder->create('parameters', FormType::class, ['label' => false]);
foreach ($this->catalog->all() as $key => $definition) {
$parameters->add($key, UtmParameterType::class, ['definition' => $definition]);
}
$builder->add($parameters);
$builder->add('custom_parameters', CollectionType::class, [
'label' => false,
'entry_type' => UtmParameterType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__param__',
'prototype_data' => [
'key' => '',
'enabled' => true,
'label' => '',
'mode' => UtmParameterMode::FREE,
'values' => [],
],
'by_reference' => false,
'error_bubbling' => false,
'required' => false,
]);
$builder->addModelTransformer($this->transformer);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['label' => false]);
}
public function getBlockPrefix(): string
{
return 'smartlinks_utm_settings';
}
}
+219
View File
@@ -0,0 +1,219 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use Mautic\CoreBundle\Form\Type\YesNoButtonGroupType;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterDefinition;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\UtmSettingsValidator;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* One parameter row: a catalog entry (option `definition`) or a custom parameter (`definition` = null).
*
* @extends AbstractType<array<string, mixed>>
*/
final class UtmParameterType extends AbstractType
{
public function __construct(
private readonly UtmSettingsValidator $validator,
private readonly TranslatorInterface $translator,
) {
}
/**
* Labels are written to local.php, where "%" would be read as a container parameter.
*
* @return Constraint[]
*/
public static function labelConstraints(): array
{
return [
new NotBlank(message: 'mautic.smartlinks.config.error.label_required'),
new Length(max: UtmSettingsValidator::MAX_LENGTH, maxMessage: 'mautic.smartlinks.config.error.label_length'),
new Regex(pattern: '/%/', match: false, message: 'mautic.smartlinks.config.error.label_invalid'),
];
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
/** @var UtmParameterDefinition|null $definition */
$definition = $options['definition'];
$allowedModes = $definition?->getAllowedModes() ?? UtmParameterMode::ALL;
if (null === $definition) {
$builder->add('key', TextType::class, [
'label' => 'mautic.smartlinks.config.parameter.key',
'attr' => [
'class' => 'form-control utm-custom-key',
'tooltip' => 'mautic.smartlinks.config.parameter.key.tooltip',
'maxlength' => 41,
],
'constraints' => [
new NotBlank(message: 'mautic.smartlinks.config.error.key_required'),
new Callback(callback: $this->validateCustomKey(...)),
],
]);
}
$builder->add('enabled', YesNoButtonGroupType::class, [
'label' => 'mautic.smartlinks.config.parameter.enabled',
]);
$builder->add('label', TextType::class, [
'label' => 'mautic.smartlinks.config.parameter.label',
'attr' => ['class' => 'form-control', 'maxlength' => UtmSettingsValidator::MAX_LENGTH],
'constraints' => self::labelConstraints(),
]);
$modeAttr = ['class' => 'form-control utm-mode'];
if ($definition?->autoGenerated) {
$modeAttr['tooltip'] = 'mautic.smartlinks.config.auto_generated.tooltip';
}
$builder->add('mode', ChoiceType::class, [
'label' => 'mautic.smartlinks.config.parameter.mode',
'choices' => array_combine(
array_map(fn (string $mode): string => 'mautic.smartlinks.config.mode.'.$mode, $allowedModes),
$allowedModes
),
'placeholder' => false,
'attr' => $modeAttr,
'invalid_message' => 'mautic.smartlinks.config.error.mode_invalid',
'constraints' => [new NotBlank(message: 'mautic.smartlinks.config.error.mode_invalid')],
]);
// Values only exist in dropdown mode: drop anything submitted for other modes (or for parameters
// that can't be dropdowns) before it is processed.
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (is_array($data) && (UtmParameterMode::DROPDOWN !== ($data['mode'] ?? null) || !$event->getForm()->has('values'))) {
unset($data['values']);
$event->setData($data);
}
});
if (!in_array(UtmParameterMode::DROPDOWN, $allowedModes, true)) {
return;
}
$builder->add('values', CollectionType::class, [
'label' => false,
'entry_type' => UtmValueType::class,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'prototype_name' => '__value__',
'by_reference' => false,
'error_bubbling' => false,
'required' => false,
'constraints' => [new Callback(callback: $this->validateValueList(...))],
]);
}
public function buildView(FormView $view, FormInterface $form, array $options): void
{
/** @var UtmParameterDefinition|null $definition */
$definition = $options['definition'];
$view->vars['utm_custom'] = null === $definition;
$view->vars['utm_key'] = $definition?->key;
$view->vars['utm_group'] = $definition?->group ?? UtmParameterCatalog::GROUP_CUSTOM;
$view->vars['utm_description_key'] = $definition?->getDescriptionKey();
$view->vars['utm_auto_generated'] = $definition?->autoGenerated ?? false;
$view->vars['utm_suggestions'] = array_map(
fn (string $value): array => [
'value' => $value,
'label' => $this->translator->trans(UtmParameterDefinition::getSuggestionLabelKey($value)),
],
$definition?->suggestions ?? []
);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'definition' => null,
'label' => false,
]);
$resolver->setAllowedTypes('definition', ['null', UtmParameterDefinition::class]);
}
public function getBlockPrefix(): string
{
return 'utm_parameter';
}
private function validateCustomKey(mixed $key, ExecutionContextInterface $context): void
{
$key = (string) $key;
if ('' === $key) {
return;
}
$errors = $this->validator->validateCustomKey($key);
$keyForm = $context->getObject();
$collection = $keyForm instanceof FormInterface ? $keyForm->getParent()?->getParent() : null;
if ([] === $errors && null !== $collection) {
$keys = [];
foreach ($collection as $parameterForm) {
if ($parameterForm->has('key')) {
$keys[] = (string) $parameterForm->get('key')->getData();
}
}
$errors = $this->validator->validateKeyIsUnique($key, $keys);
}
$this->addViolations($context, $errors);
}
private function validateValueList(mixed $values, ExecutionContextInterface $context): void
{
$valuesForm = $context->getObject();
$parameter = $valuesForm instanceof FormInterface ? $valuesForm->getParent() : null;
if (null === $parameter) {
return;
}
$errors = $this->validator->validateValueList(
(string) $parameter->get('mode')->getData(),
(bool) $parameter->get('enabled')->getData(),
array_values(is_array($values) ? $values : [])
);
$this->addViolations($context, $errors);
}
/**
* @param list<array{0: string, 1: array<string, string>}> $errors
*/
private function addViolations(ExecutionContextInterface $context, array $errors): void
{
foreach ($errors as [$message, $parameters]) {
$context->buildViolation($message)
->setParameters($parameters)
->setTranslationDomain('validators')
->addViolation();
}
}
}
+368
View File
@@ -0,0 +1,368 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use Mautic\CoreBundle\Form\Type\FormButtonsType;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\UtmSettingsValidator;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\UtmTaxonomyValidator;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Create / edit a UTM Taxonomy.
*
* Every parameter enabled in Smart Links Settings appears, exactly as the admin defined it:
* a `dropdown` parameter offers its admin-configured values as a checkbox list (a subset
* selection -- nothing can be typed), and a `free` parameter gets its own editable value
* list here (one `value` or `value;Label` per line): a Smart Link using this taxonomy picks
* a value from it instead of typing freely.
*
* @extends AbstractType<UtmTaxonomy>
*/
final class UtmTaxonomyType extends AbstractType
{
public function __construct(
private readonly UtmConfigurationProvider $utmConfiguration,
private readonly UtmTaxonomyValidator $validator,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('name', TextType::class, [
'label' => 'mautic.smartlinks.taxonomies.name',
'required' => true,
'attr' => [
'class' => 'form-control',
'maxlength' => UtmTaxonomy::NAME_MAX_LENGTH,
'tooltip' => 'mautic.smartlinks.taxonomies.name.tooltip',
],
'constraints' => [
new NotBlank(message: 'mautic.smartlinks.taxonomies.error.name_required'),
new Length(max: UtmTaxonomy::NAME_MAX_LENGTH, maxMessage: 'mautic.smartlinks.taxonomies.error.name_length'),
new Callback(callback: $this->validateName(...)),
],
]);
$builder->add('description', TextareaType::class, [
'label' => 'mautic.smartlinks.taxonomies.description',
'required' => false,
'attr' => [
'class' => 'form-control',
'tooltip' => 'mautic.smartlinks.taxonomies.description.tooltip',
'rows' => 3,
],
]);
$this->buildParameters($builder);
$builder->add('buttons', FormButtonsType::class);
if (!empty($options['action'])) {
$builder->setAction($options['action']);
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => UtmTaxonomy::class,
]);
}
public function getBlockPrefix(): string
{
return 'smartlinks_utm_taxonomy';
}
/**
* The values section: one field per enabled parameter. Dropdown parameters offer the
* admin's values as checkboxes; free ones get an editable textarea (one value per line).
* A transformer maps the children shapes to the stored rows, and the textarea lines are
* validated on POST_SUBMIT (pattern, duplicates).
*/
private function buildParameters(FormBuilderInterface $builder): void
{
$builder->add('parameters', FormType::class, [
'label' => false,
'error_bubbling' => false,
]);
$dropdowns = $this->getDropdownParameters();
$frees = $this->getFreeParameterKeys();
foreach ($this->utmConfiguration->getEnabledParameters() as $key => $parameter) {
if (isset($dropdowns[$key])) {
$attr = ['class' => 'utm-taxonomy-values'];
if ([] === $dropdowns[$key]) {
$attr['tooltip'] = 'mautic.smartlinks.taxonomies.no_values.tooltip';
}
$builder->get('parameters')->add($key, ChoiceType::class, [
'label' => (string) $parameter['label'],
'required' => false,
'multiple' => true,
'expanded' => true,
'choices' => array_flip($dropdowns[$key]),
'attr' => $attr,
]);
continue;
}
if (in_array($key, $frees, true)) {
$builder->get('parameters')->add($key, TextareaType::class, [
'label' => (string) $parameter['label'],
'required' => false,
'attr' => [
'class' => 'form-control utm-taxonomy-free-values',
'rows' => 2,
'tooltip' => 'mautic.smartlinks.taxonomies.free_values.tooltip',
'placeholder' => 'mautic.smartlinks.taxonomies.free_values.placeholder',
],
]);
}
}
$builder->get('parameters')->addModelTransformer(new CallbackTransformer(
fn (mixed $rows): array => $this->rowsToChildren($rows, $dropdowns, $frees),
fn (mixed $children): array => $this->childrenToRows($children, $dropdowns, $frees),
));
$builder->get('parameters')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($frees): void {
$form = $event->getForm();
foreach ($frees as $key) {
if (!$form->has($key)) {
continue;
}
$rows = $this->parseTextarea((string) $form->get($key)->getData());
$this->addErrorsOn($form->get($key), $this->validator->validateValues($rows));
}
});
}
/**
* The admin's dropdown parameters: key => [value => label].
*
* @return array<string, array<string, string>>
*/
private function getDropdownParameters(): array
{
$dropdowns = [];
foreach ($this->utmConfiguration->getEnabledParameters() as $key => $parameter) {
if (UtmParameterMode::DROPDOWN !== $parameter['mode']) {
continue;
}
// Present even when the admin hasn't configured values yet: the parameter stays
// visible on the form (an empty checkbox list), mirroring the settings.
$dropdowns[$key] = [];
foreach ($this->utmConfiguration->getDropdownValues($key) as $row) {
$dropdowns[$key][$row['value']] = $row['label'];
}
}
return $dropdowns;
}
/**
* The parameters the admin left free text: they get an editable value list here.
*
* @return list<string>
*/
private function getFreeParameterKeys(): array
{
$free = [];
foreach ($this->utmConfiguration->getEnabledParameters() as $key => $parameter) {
if (UtmParameterMode::FREE === $parameter['mode']) {
$free[] = $key;
}
}
return $free;
}
/**
* The stored rows become the children data: checkbox arrays for dropdowns (only the
* values the admin still configures stay checked), one-value-per-line text for the
* free ones (a `value;Label` line when the label differs from the value).
*
* @param array<string, array<string, string>> $dropdowns
* @param list<string> $frees
*
* @return array<string, mixed>
*/
private function rowsToChildren(mixed $rows, array $dropdowns, array $frees): array
{
$children = [];
foreach (array_keys($dropdowns) as $key) {
$children[$key] = [];
}
foreach ($frees as $key) {
$children[$key] = '';
}
foreach (is_array($rows) ? $rows : [] as $key => $list) {
if (!\is_array($list) || !\array_key_exists((string) $key, $children)) {
continue;
}
if (\is_array($children[$key])) {
$children[$key] = [];
} else {
$children[$key] = '';
}
$lines = [];
foreach ($list as $row) {
$value = \is_array($row) ? (string) ($row['value'] ?? '') : '';
if ('' === $value) {
continue;
}
if (isset($dropdowns[$key])) {
if (isset($dropdowns[$key][$value])) {
$children[$key][] = $value;
}
continue;
}
$label = \is_array($row) ? trim((string) ($row['label'] ?? '')) : '';
$lines[] = ('' !== $label && $label !== $value) ? $value.';'.$label : $value;
}
if (\is_string($children[$key])) {
$children[$key] = implode("\n", $lines);
}
}
return $children;
}
/**
* Back to the stored shape: checkbox arrays become rows with the admin's labels,
* textarea lines become rows (labels default to the value); empty lists drop the key.
*
* @param array<string, array<string, string>> $dropdowns
* @param list<string> $frees
*
* @return array<string, list<array{value: string, label: string}>>
*/
private function childrenToRows(mixed $children, array $dropdowns, array $frees): array
{
$rows = [];
foreach (is_array($children) ? $children : [] as $key => $data) {
if (isset($dropdowns[$key])) {
$clean = [];
foreach (\is_array($data) ? $data : [] as $value) {
$value = (string) $value;
if (isset($dropdowns[$key][$value]) && !isset($clean[$value])) {
$clean[$value] = ['value' => $value, 'label' => $dropdowns[$key][$value]];
}
}
if ([] !== $clean) {
$rows[$key] = array_values($clean);
}
continue;
}
if (!in_array((string) $key, $frees, true)) {
continue;
}
$clean = [];
foreach ($this->parseTextarea((string) $data) as [$value, $label]) {
if (!isset($clean[$value])) {
$clean[$value] = ['value' => $value, 'label' => '' !== $label ? $label : $value];
}
}
if ([] !== $clean) {
$rows[$key] = array_values($clean);
}
}
ksort($rows);
return $rows;
}
/**
* One value (or `value;Label`) per line.
*
* @return list<array{0: string, 1: string}>
*/
private function parseTextarea(string $text): array
{
$parsed = [];
foreach (preg_split('/\r?\n/', $text) ?: [] as $line) {
$line = trim($line);
if ('' === $line) {
continue;
}
$parts = explode(';', $line, 2);
$parsed[] = [trim($parts[0]), isset($parts[1]) ? trim($parts[1]) : ''];
}
return $parsed;
}
/**
* Runs UtmTaxonomyValidator::validateName() on the typed name, skipping the entity's own.
*/
private function validateName(mixed $name, ExecutionContextInterface $context): void
{
$name = trim((string) $name);
if ('' === $name) {
return;
}
/** @var FormInterface $form */
$form = $context->getObject();
$ignored = $form instanceof FormInterface && $form->getParent()?->getData() instanceof UtmTaxonomy
? $form->getParent()->getData()->getId()
: null;
$this->addErrorsOn($form, $this->validator->validateName($name, $ignored));
}
/**
* @param FormInterface|FormBuilderInterface $form
* @param list<array{0: string, 1: array<string, string>}> $errors
*/
private function addErrorsOn(object $form, array $errors): void
{
foreach ($errors as [$message, $parameters]) {
$form->addError(new FormError($message, null, $parameters));
}
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Type;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Validator\UtmSettingsValidator;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
/**
* One allowed value of a `dropdown` parameter.
*
* @extends AbstractType<array<string, mixed>>
*/
final class UtmValueType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('value', TextType::class, [
'label' => 'mautic.smartlinks.config.values.value',
'attr' => [
'class' => 'form-control utm-value-input',
'placeholder' => 'mautic.smartlinks.config.values.value',
'maxlength' => UtmSettingsValidator::MAX_LENGTH,
],
'constraints' => [
new NotBlank(message: 'mautic.smartlinks.config.error.value_required'),
new Length(max: UtmSettingsValidator::MAX_LENGTH, maxMessage: 'mautic.smartlinks.config.error.value_length'),
new Regex(pattern: UtmSettingsValidator::VALUE_PATTERN, message: 'mautic.smartlinks.config.error.value_invalid'),
],
]);
$builder->add('label', TextType::class, [
'label' => 'mautic.smartlinks.config.values.label',
'attr' => [
'class' => 'form-control utm-label-input',
'placeholder' => 'mautic.smartlinks.config.values.label',
'maxlength' => UtmSettingsValidator::MAX_LENGTH,
],
'constraints' => UtmParameterType::labelConstraints(),
]);
$builder->add('is_default', CheckboxType::class, [
'label' => 'mautic.smartlinks.config.values.default',
'required' => false,
'attr' => ['class' => 'utm-value-default'],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['label' => false]);
}
public function getBlockPrefix(): string
{
return 'utm_value';
}
}
+253
View File
@@ -0,0 +1,253 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Makes the native "UTM tags" subform (Email, Focus Item) follow the UTM Manager configuration.
*
* Per native field: `dropdown` replaces the text input with a select restricted to the configured values
* (plus the value already stored, if it isn't in the taxonomy), `free` keeps the native field,
* `disabled` (or not enabled) removes the field and stores null.
*
* Only the form is enforced: API and import write the entity directly.
*/
final class UtmFieldsApplicator
{
/**
* Native subform fields => configuration keys. utm_term has no native field and is left alone.
*/
public const FIELDS = [
'utmSource' => 'utm_source',
'utmMedium' => 'utm_medium',
'utmCampaign' => 'utm_campaign',
'utmContent' => 'utm_content',
];
/** Native options carried over to the select. */
private const KEPT_OPTIONS = ['label_attr', 'constraints', 'help', 'help_attr', 'help_html', 'help_translation_parameters'];
public function __construct(
private readonly UtmConfigurationProvider $configurationProvider,
private readonly UtmParameterCatalog $catalog,
private readonly TranslatorInterface $translator,
) {
}
public function apply(FormBuilderInterface $builder): void
{
// Fields are rebuilt once the stored values are known, to offer legacy values as choices.
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event): void {
$this->buildFields($event->getForm(), $event->getData());
});
// A value posted for a removed field would raise an "extra fields" error: drop it.
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (!is_array($data)) {
return;
}
foreach ($this->getDisabledFields() as $field) {
unset($data[$field]);
}
$event->setData($data);
});
// A removed field leaves its key untouched in the stored array: clear it so no stale value survives.
$builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event): void {
$data = $event->getData();
if (null !== $data && !is_array($data)) {
return;
}
$data ??= [];
foreach ($this->getDisabledFields() as $field) {
// null, as the native empty field: an empty string would add "utm_x=" to every link.
$data[$field] = null;
}
$event->setData($data);
});
}
/**
* @param FormInterface<mixed> $form
*/
private function buildFields(FormInterface $form, mixed $storedTags): void
{
$storedTags = is_array($storedTags) ? $storedTags : [];
$nativeOrder = array_keys($form->all());
foreach (self::FIELDS as $field => $key) {
if (!$form->has($field)) {
continue;
}
$parameter = $this->configurationProvider->getParameter($key);
if (null === $parameter) {
continue;
}
$mode = $this->getMode($parameter);
if (UtmParameterMode::DISABLED === $mode) {
$form->remove($field);
continue;
}
$label = $this->getCustomLabel($key, $parameter);
if (UtmParameterMode::DROPDOWN === $mode) {
$this->addDropdown($form, $field, $key, $label, $storedTags[$field] ?? null);
} elseif (null !== $label) {
$this->replaceField($form, $field, null, ['label' => $label]);
}
}
// A replaced field is appended last: re-append every field in core's order.
foreach ($nativeOrder as $name) {
if ($form->has($name)) {
$child = $form->get($name);
$form->remove($name);
$form->add($child);
}
}
}
/**
* @param FormInterface<mixed> $form
*/
private function addDropdown(FormInterface $form, string $field, string $key, ?string $label, mixed $stored): void
{
// A non-scalar value can't be shown in a select: keep the native field rather than lose it.
if (null !== $stored && !is_scalar($stored)) {
return;
}
// value => label, in configured order. Numeric values become int keys: compare as strings.
$labels = [];
foreach ($this->configurationProvider->getDropdownValues($key) as $row) {
$labels[(string) $row['value']] = (string) $row['label'];
}
$options = [];
$storedValue = null === $stored ? '' : (string) $stored;
if ('' !== $storedValue && !array_key_exists($storedValue, $labels)) {
// Legacy value: kept as the last choice so it displays and re-saves without data loss.
$labels[$storedValue] = $this->translator->trans('mautic.smartlinks.form.legacy_choice', ['%value%' => $storedValue]);
$options['help'] = 'mautic.smartlinks.form.legacy_warning';
$options['help_attr'] = ['class' => 'text-warning'];
} elseif ([] === $labels) {
$options['help'] = 'mautic.smartlinks.form.no_values';
$options['help_attr'] = ['class' => 'text-warning'];
}
$options += [
'choices' => array_map('strval', array_keys($labels)),
'choice_label' => static fn (string $value): string => $labels[$value],
// Configured labels are shown as typed. The placeholder is translated here for the same reason.
'choice_translation_domain' => false,
'placeholder' => $this->translator->trans('mautic.smartlinks.form.choose'),
'required' => false,
'multiple' => false,
'expanded' => false,
'attr' => ['class' => 'form-control'],
'invalid_message' => 'mautic.smartlinks.form.error.not_in_taxonomy',
];
if (null !== $label) {
$options['label'] = $label;
}
$this->replaceField($form, $field, ChoiceType::class, $options);
}
/**
* Re-adds a field with its native options (label, constraints...) overridden by $options.
*
* @param FormInterface<mixed> $form
* @param class-string|null $type null keeps the native type and all native options
* @param array<string, mixed> $options
*/
private function replaceField(FormInterface $form, string $field, ?string $type, array $options): void
{
$config = $form->get($field)->getConfig();
$native = $config->getOptions();
if (null === $type) {
$type = $config->getType()->getInnerType()::class;
$options = array_replace($this->getOverridableOptions($native), $options);
} else {
$kept = array_intersect_key($native, array_flip(self::KEPT_OPTIONS));
$kept += ['label' => $native['label'] ?? null];
// Our help (legacy warning, empty list) wins over the native one; otherwise keep the native help.
$options = array_replace($kept, $options);
}
$form->remove($field);
$form->add($field, $type, $options);
}
/**
* Native options a type accepts again when re-added (resolved-only options are excluded).
*
* @param array<string, mixed> $native
*
* @return array<string, mixed>
*/
private function getOverridableOptions(array $native): array
{
return array_intersect_key($native, array_flip(['label', 'label_attr', 'attr', 'required', 'constraints', 'help', 'help_attr', 'help_html']));
}
/**
* @param array<string, mixed> $parameter
*/
private function getMode(array $parameter): string
{
return $parameter['enabled'] ? (string) $parameter['mode'] : UtmParameterMode::DISABLED;
}
/**
* The configured label, or null when it is the catalog default (the native label is kept then).
*
* @param array<string, mixed> $parameter
*/
private function getCustomLabel(string $key, array $parameter): ?string
{
$label = (string) ($parameter['label'] ?? '');
$definition = $this->catalog->get($key);
if ('' === $label || (null !== $definition && $label === $this->translator->trans($definition->getLabelKey()))) {
return null;
}
return $label;
}
/**
* @return list<string>
*/
private function getDisabledFields(): array
{
$disabled = [];
foreach (self::FIELDS as $field => $key) {
$parameter = $this->configurationProvider->getParameter($key);
if (null !== $parameter && UtmParameterMode::DISABLED === $this->getMode($parameter)) {
$disabled[] = $field;
}
}
return $disabled;
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Validator;
use Mautic\FormBundle\Entity\Form;
use Mautic\PageBundle\Entity\Page;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectType;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel;
/**
* Business rules of the Smart Link form. The form type calls these methods from Callback
* constraints; each method returns translation keys (validators domain) and parameters.
*/
final class SmartLinkValidator
{
public const ERROR_SLUG_TAKEN = 'mautic.smartlinks.smart_links.error.slug_taken';
public const ERROR_SLUG_REQUIRED = 'mautic.smartlinks.smart_links.error.slug_required';
public const ERROR_SLUG_LENGTH = 'mautic.smartlinks.smart_links.error.slug_length';
public const ERROR_DESTINATION_REQUIRED = 'mautic.smartlinks.smart_links.error.destination_required';
public const ERROR_DESTINATION_REQUIRED_MAUTIC = 'mautic.smartlinks.smart_links.error.destination_required_mautic';
public const ERROR_DESTINATION_INVALID = 'mautic.smartlinks.smart_links.error.destination_invalid';
public const ERROR_UTM_VALUE_INVALID = 'mautic.smartlinks.smart_links.error.utm_value_invalid';
public const ERROR_UTM_VALUE_NOT_ALLOWED = 'mautic.smartlinks.smart_links.error.utm_value_not_allowed';
public const ERROR_TAXONOMY_PARAMETER_UNKNOWN = 'mautic.smartlinks.smart_links.error.taxonomy_parameter_unknown';
public function __construct(
private readonly SmartLinkModel $smartLinkModel,
private readonly UtmConfigurationProvider $utmConfiguration,
) {
}
/**
* Unique slug. The rules (lowercase, separator replacement) are applied by the model
* before this check, so the comparison uses the final slug.
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateSlug(string $slug, ?int $ignoreId = null): array
{
if ('' === $slug) {
return [[self::ERROR_SLUG_REQUIRED, []]];
}
if ($this->smartLinkModel->isSlugTaken($slug, $ignoreId)) {
return [[self::ERROR_SLUG_TAKEN, ['%slug%' => $slug]]];
}
return [];
}
/**
* A destination is required for every redirect type: an URL for external ones, a landing
* page or a standalone form for Mautic ones. Only http(s) URLs are accepted.
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateDestination(SmartLinkRedirectType $redirectType, ?string $url, ?Page $page = null, ?Form $form = null): array
{
if ($redirectType->isMautic()) {
if (null === $page && null === $form) {
return [[self::ERROR_DESTINATION_REQUIRED_MAUTIC, []]];
}
return [];
}
$url = trim((string) $url);
if ('' === $url) {
return [[self::ERROR_DESTINATION_REQUIRED, []]];
}
if (!filter_var($url, FILTER_VALIDATE_URL)
|| !in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true)) {
return [[self::ERROR_DESTINATION_INVALID, ['%url%' => $url]]];
}
return [];
}
/**
* UTM values follow the Smart Links Settings the admin defines. With a taxonomy chosen:
* every parameter the taxonomy defines limits the value -- the checkbox subset of the
* admin's values for a dropdown, the taxonomy's own list for a free parameter. The
* values the link carried before the edit stay acceptable (they were chosen when the
* taxonomy — or, before the feature, the global configuration — allowed them), so a plain
* re-save never errors. Without a taxonomy (links that predate the feature, before their
* next edit), the values follow the rules of Smart Links Settings.
*
* @param array<string, string> $utmParameters
* @param array<string, string> $stored the values the link carried before the edit
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateUtmParameters(array $utmParameters, ?UtmTaxonomy $taxonomy = null, array $stored = []): array
{
if (null === $taxonomy) {
return $this->validateAgainstGlobalConfiguration($utmParameters, $stored);
}
$errors = [];
foreach ($utmParameters as $key => $value) {
$parameter = $this->utmConfiguration->getParameter($key);
if (null === $parameter || (!$parameter['enabled']) || UtmParameterMode::DISABLED === $parameter['mode']) {
$errors[] = [self::ERROR_UTM_VALUE_INVALID, ['%key%' => $key]];
continue;
}
// Every parameter of the taxonomy limits the value: a dropdown subset selected
// among the admin's values, or the taxonomy's own list for a free parameter.
$allowed = $taxonomy->getParameterValues($key);
if ([] === $allowed) {
$errors[] = [self::ERROR_TAXONOMY_PARAMETER_UNKNOWN, ['%key%' => $key, '%name%' => (string) $taxonomy->getName()]];
continue;
}
if (in_array($value, array_column($allowed, 'value'), true) || ($stored[$key] ?? null) === $value) {
continue;
}
$errors[] = [self::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => $key, '%value%' => $value]];
}
return $errors;
}
/**
* The rules of Smart Links Settings: the values belong to enabled parameters, respect the
* technical pattern, and dropdown values stay within the configured list — unless the link
* already carried them.
*
* @param array<string, string> $utmParameters
* @param array<string, string> $stored
*
* @return list<array{0: string, 1: array<string, string>}>
*/
private function validateAgainstGlobalConfiguration(array $utmParameters, array $stored): array
{
$valuePattern = UtmSettingsValidator::VALUE_PATTERN;
$errors = [];
foreach ($utmParameters as $key => $value) {
$parameter = $this->utmConfiguration->getParameter($key);
if (null === $parameter || (!$parameter['enabled']) || UtmParameterMode::DISABLED === $parameter['mode']) {
$errors[] = [self::ERROR_UTM_VALUE_INVALID, ['%key%' => $key]];
continue;
}
if (1 !== preg_match($valuePattern, $value)) {
$errors[] = [self::ERROR_UTM_VALUE_INVALID, ['%key%' => $key]];
continue;
}
$inList = UtmParameterMode::DROPDOWN !== $parameter['mode']
|| in_array($value, array_column($this->utmConfiguration->getDropdownValues($key), 'value'), true);
if (!$inList && ($stored[$key] ?? null) !== $value) {
$errors[] = [self::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => $key, '%value%' => $value]];
}
}
return $errors;
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Validator;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterCatalog;
use MauticPlugin\MT3SMarketingProgramBundle\Catalog\UtmParameterMode;
/**
* Business rules of the UTM Manager configuration form. The form types call these methods
* from Callback constraints; each method returns translation keys (validators domain) and parameters.
*/
final class UtmSettingsValidator
{
/** Technical value written in the URL: lowercase letters, digits, "-", "_" and ".". */
public const VALUE_PATTERN = '/^[a-z0-9._-]+$/';
public const MAX_LENGTH = 100;
public const ERROR_KEY_INVALID = 'mautic.smartlinks.config.error.key_invalid';
public const ERROR_KEY_RESERVED = 'mautic.smartlinks.config.error.key_reserved';
public const ERROR_KEY_DUPLICATE = 'mautic.smartlinks.config.error.key_duplicate';
public const ERROR_VALUES_REQUIRED = 'mautic.smartlinks.config.error.values_required';
public const ERROR_VALUE_DUPLICATE = 'mautic.smartlinks.config.error.value_duplicate';
public const ERROR_DEFAULT_MULTIPLE = 'mautic.smartlinks.config.error.default_multiple';
public function __construct(
private readonly UtmParameterCatalog $catalog,
) {
}
/**
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateCustomKey(string $key): array
{
if (1 !== preg_match(UtmParameterCatalog::CUSTOM_KEY_PATTERN, $key)) {
return [[self::ERROR_KEY_INVALID, ['%key%' => $key]]];
}
if ($this->catalog->isReservedKey($key)) {
return [[self::ERROR_KEY_RESERVED, ['%key%' => $key]]];
}
return [];
}
/**
* @param string[] $existingKeys All custom keys of the form, including $key itself
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateKeyIsUnique(string $key, array $existingKeys): array
{
$occurrences = count(array_filter($existingKeys, fn (string $other): bool => $other === $key));
return $occurrences > 1 ? [[self::ERROR_KEY_DUPLICATE, ['%key%' => $key]]] : [];
}
/**
* Rules that apply to the whole value list of a `dropdown` parameter. Nothing is checked
* for other modes: their values are never processed.
*
* @param array<array{value?: mixed, label?: mixed, is_default?: mixed}> $rows
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateValueList(string $mode, bool $enabled, array $rows): array
{
if (UtmParameterMode::DROPDOWN !== $mode) {
return [];
}
$errors = [];
if ($enabled && [] === $rows) {
$errors[] = [self::ERROR_VALUES_REQUIRED, []];
}
$seen = [];
foreach ($rows as $row) {
$value = (string) ($row['value'] ?? '');
if ('' === $value) {
continue;
}
if (isset($seen[$value]) && 1 === $seen[$value]) {
$errors[] = [self::ERROR_VALUE_DUPLICATE, ['%value%' => $value]];
}
$seen[$value] = ($seen[$value] ?? 0) + 1;
}
$defaults = array_filter($rows, fn (array $row): bool => !empty($row['is_default']));
if (count($defaults) > 1) {
$errors[] = [self::ERROR_DEFAULT_MULTIPLE, []];
}
return $errors;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Form\Validator;
use MauticPlugin\MT3SMarketingProgramBundle\Model\UtmTaxonomyModel;
/**
* Business rules of the UTM Taxonomy form. The form types call these methods from Callback
* constraints; each method returns translation keys (validators domain) and parameters.
*/
final class UtmTaxonomyValidator
{
public const ERROR_NAME_TAKEN = 'mautic.smartlinks.taxonomies.error.name_taken';
public const ERROR_NAME_CHARACTERS = 'mautic.smartlinks.taxonomies.error.name_characters';
public const ERROR_VALUE_INVALID = 'mautic.smartlinks.taxonomies.error.value_invalid';
public const ERROR_VALUE_DUPLICATE = 'mautic.smartlinks.config.error.value_duplicate';
public function __construct(
private readonly UtmTaxonomyModel $taxonomyModel,
) {
}
/**
* Unique, non-empty name. Free of the characters local.php can't carry ("%", "{", "}").
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateName(string $name, ?int $ignoreId = null): array
{
if (1 !== preg_match('/^[^%{}]+$/', $name)) {
return [[self::ERROR_NAME_CHARACTERS, []]];
}
if ($this->taxonomyModel->isNameTaken($name, $ignoreId)) {
return [[self::ERROR_NAME_TAKEN, ['%name%' => $name]]];
}
return [];
}
/**
* The value list of a `free` parameter (its editable textarea): every line must respect
* the technical pattern of the URL values, and duplicates are rejected.
*
* @param list<array{0: string, 1: string}> $parsed
*
* @return list<array{0: string, 1: array<string, string>}>
*/
public function validateValues(array $parsed): array
{
$errors = [];
$seen = [];
foreach ($parsed as [$value]) {
if ('' === $value) {
continue;
}
if (isset($seen[$value]) && 1 === $seen[$value]) {
$errors[] = [self::ERROR_VALUE_DUPLICATE, ['%value%' => $value]];
}
$seen[$value] = ($seen[$value] ?? 0) + 1;
if (1 !== preg_match(UtmSettingsValidator::VALUE_PATTERN, $value)) {
$errors[] = [self::ERROR_VALUE_INVALID, ['%value%' => $value]];
}
}
return $errors;
}
}