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

355 lines
12 KiB
PHP

<?php
declare(strict_types=1);
namespace MauticPlugin\MT3SMarketingProgramBundle\Model;
use Doctrine\ORM\EntityManagerInterface;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\CoreBundle\Model\FormModel;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use Mautic\PageBundle\Model\PageModel;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLinkHit;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLinkHitRepository;
use MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLinkRepository;
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinkType;
use MauticPlugin\MT3SMarketingProgramBundle\Service\UtmConfigurationProvider;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Available as mautic.mt3smarketingprogram.model.smart_link, or getModel('mt3smarketingprogram.smart_link').
*
* @extends FormModel<SmartLink>
*/
class SmartLinkModel extends FormModel
{
public const MODEL_NAME = 'mt3smarketingprogram.smart_link';
/** Random slugs offered by the "Generate" button: 4 characters, letters and digits. */
public const GENERATED_SLUG_LENGTH = 4;
public function __construct(
EntityManagerInterface $em,
CorePermissions $security,
EventDispatcherInterface $dispatcher,
UrlGeneratorInterface $router,
TranslatorInterface $translator,
UserHelper $userHelper,
LoggerInterface $logger,
CoreParametersHelper $coreParametersHelper,
private readonly UtmConfigurationProvider $utmConfiguration,
private readonly PageModel $pageModel,
) {
parent::__construct($em, $security, $dispatcher, $router, $translator, $userHelper, $logger, $coreParametersHelper);
}
public function getRepository(): SmartLinkRepository
{
$repository = $this->em->getRepository(SmartLink::class);
\assert($repository instanceof SmartLinkRepository);
return $repository;
}
public function getPermissionBase(): string
{
return 'mt3smarketingprogram:smart_links';
}
public function getEntity($id = null): ?SmartLink
{
if (null === $id) {
return new SmartLink();
}
$entity = parent::getEntity($id);
return $entity instanceof SmartLink ? $entity : null;
}
/**
* @param array<string, mixed> $options
*/
public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface
{
if (!$entity instanceof SmartLink) {
throw new MethodNotAllowedHttpException(['SmartLink']);
}
if (!empty($action)) {
$options['action'] = $action;
}
return $formFactory->create(SmartLinkType::class, $entity, $options);
}
/**
* Applies the UTM Manager settings to everything the user typed (slug and values), then saves.
*/
public function saveEntity($entity, $unlock = true): void
{
if ($entity instanceof SmartLink) {
$this->applySlugRules($entity);
$entity->setUtmParameters($this->normalizeUtmValues($entity->getUtmParameters()));
}
parent::saveEntity($entity, $unlock);
}
/**
* Slug rules from Settings > Configuration > UTM Settings: spaces become the configured
* separator (or hyphen), lowercase is enforced when configured. Kept here (not in the form)
* so a manually typed slug, an imported one and a generated one all follow the same rules.
*/
public function applySlugRules(SmartLink $entity, ?string $rawSlug = null): void
{
$raw = $rawSlug ?? (string) ($entity->getSlug() ?? '');
$slug = str_replace(' ', $this->utmConfiguration->getSeparatorReplacement(), trim($raw));
if ($this->utmConfiguration->isLowercaseEnforced()) {
$slug = mb_strtolower($slug);
}
// The user never edits the slug of a saved link (the form field is disabled): the entity
// keeps the stored one. onPersistentEntityChange checks it in the background.
if (null === $entity->getId()) {
$entity->setSlug('' !== $slug ? $slug : null);
} elseif (null !== $rawSlug) {
$entity->setSlug($slug); // throws when it differs from the stored slug
}
}
/**
* @param array<string, string> $utmParameters
*
* @return array<string, string>
*/
public function normalizeUtmValues(array $utmParameters): array
{
$clean = [];
foreach ($utmParameters as $key => $value) {
$key = trim((string) $key);
$value = trim((string) $value);
if ('' === $key || '' === $value) {
continue;
}
if ($this->utmConfiguration->isLowercaseEnforced()) {
$value = mb_strtolower($value);
}
$clean[$key] = $value;
}
ksort($clean);
return $clean;
}
/**
* The slug of a saved link never changes; saveEntity() only re-applies the rules to a slug
* the user could have typed on the "new" form. Drops the form value on edit so the immutable
* one is kept.
*/
public function onPersistentEntityChange(SmartLink $entity, ?string $submittedSlug): void
{
$this->applySlugRules($entity, $submittedSlug);
}
/**
* True when another saved link already uses this slug. $ignoreId keeps a link being
* edited from colliding with itself.
*/
public function isSlugTaken(string $slug, ?int $ignoreId = null): bool
{
return $this->getRepository()->slugExists($slug, $ignoreId);
}
/**
* The short links domain configured in Settings > Configuration > Smart Links Settings,
* without scheme or trailing slash, for example lnk.example.com. Empty when not configured.
*/
public function getShortLinkDomain(): string
{
$stored = $this->coreParametersHelper->get(\MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType::CONFIG_PARAMETER, []);
// Upgrades keep the domain in local.php under a legacy key (the standalone
// SmartlinksBundle wrote `smartlinks_config`, the UtmManagerBundle before it
// `utm_manager_smart_links`); serve it until the Configuration page is saved again.
$legacyKeys = [
\MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType::LEGACY_SMARTLINKS_PARAMETER,
\MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType::LEGACY_CONFIG_PARAMETER,
];
foreach ($legacyKeys as $legacyKey) {
if (!is_array($stored) || '' === trim((string) ($stored['short_link_domain'] ?? ''))) {
$legacy = $this->coreParametersHelper->get($legacyKey, []);
if (is_array($legacy) && '' !== trim((string) ($legacy['short_link_domain'] ?? ''))) {
$stored = $legacy;
}
}
}
$domain = trim(is_array($stored) ? (string) ($stored['short_link_domain'] ?? '') : '');
return '' === $domain ? '' : rtrim($domain, '/');
}
/**
* A random slug of 4 lowercase letters and digits, for example a7f3, that no saved link
* uses yet. Used by the "Generate" button of the form and to prefill a new link.
*/
public function generateSlug(): string
{
$alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';
do {
$slug = '';
for ($i = 0; $i < self::GENERATED_SLUG_LENGTH; ++$i) {
$slug .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
} while ($this->isSlugTaken($slug));
return $slug;
}
/**
* The final URL of the redirect, whatever the link's type: the destination with the link's
* UTM parameters appended to its query string. The link's values override same-named
* parameters of the destination; the query of the short link call itself is ignored (the
* stored parameters are the canonical ones).
*
* External redirects go to the configured URL; Mautic redirects go to the public URL of
* the linked landing page (/{slug}) or standalone form (/form/{id}).
*/
public function buildRedirectUrl(SmartLink $link): string
{
$destination = $link->getRedirectType()->isMautic()
? $this->buildMauticDestinationUrl($link)
: trim((string) $link->getDestinationUrl());
return self::appendUtmParameters($destination, $link->getUtmParameters());
}
/**
* The public URL of the Mautic destination: the landing page or the standalone form.
* Empty when the link has no (or no longer a) destination.
*/
public function buildMauticDestinationUrl(SmartLink $link): string
{
if (null !== $link->getPage()) {
// PageModel::generateUrl() handles variants, category and language slugs.
return $this->pageModel->generateUrl($link->getPage());
}
if (null !== $link->getForm()) {
// Standalone forms have no alias URL: their landing page is the form preview.
return $this->router->generate(
'mautic_form_preview',
['id' => $link->getForm()->getId()],
UrlGeneratorInterface::ABSOLUTE_URL
);
}
return '';
}
/**
* Appends the UTM parameters to a destination URL. Pure static method, unit-testable.
*
* @param array<string, string> $utms
*/
public static function appendUtmParameters(string $destination, array $utms): string
{
if ([] === $utms || '' === $destination) {
return $destination;
}
$parts = parse_url($destination);
$query = [];
if (isset($parts['query']) && '' !== $parts['query']) {
parse_str($parts['query'], $query);
}
// The link's parameters win over the destination's own ones.
$parts['query'] = http_build_query(array_merge($query, $utms));
return self::unparseUrl($parts);
}
/**
* Records one call of the short link (date, IP, referer, user agent). Statistics never
* block the redirect: the controller wraps the call in a try/catch.
*/
public function recordHit(SmartLink $link, Request $request): SmartLinkHit
{
$hit = new SmartLinkHit();
$hit->setSmartLink($link);
$hit->setIpAddress($request->getClientIp());
$hit->setReferer($request->headers->get('referer'));
$hit->setUserAgent($request->headers->get('user-agent'));
$this->em->persist($hit);
$this->em->flush();
return $hit;
}
/**
* Hit counts of every link, in one query: link id => number of hits.
*
* @return array<int, int>
*/
public function getHitCounts(): array
{
return $this->getHitRepository()->getHitCounts();
}
private function getHitRepository(): SmartLinkHitRepository
{
$repository = $this->em->getRepository(SmartLinkHit::class);
\assert($repository instanceof SmartLinkHitRepository);
return $repository;
}
/**
* Rebuilds a URL from parse_url() parts (the scheme/host/path/query the destination had).
*
* @param array<string, mixed> $parts
*/
private static function unparseUrl(array $parts): string
{
$url = '';
if (isset($parts['scheme'])) {
$url .= $parts['scheme'].'://';
} elseif (isset($parts['host'])) {
$url .= '//';
}
$url .= $parts['host'] ?? '';
if (isset($parts['port'])) {
$url .= ':'.$parts['port'];
}
$url .= $parts['path'] ?? '';
if (isset($parts['query'])) {
$url .= '?'.$parts['query'];
}
if (isset($parts['fragment'])) {
$url .= '#'.$parts['fragment'];
}
return $url;
}
}