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

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

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

254 lines
9.5 KiB
PHP

<?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;
}
}