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:
1 parent
debce4ba4a
commit
dce849610c
69 files changed
+8225
-43
No files matched your search
@@ -0,0 +1,347 @@
|
||||
<?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.smartlinks.model.smart_link, or getModel('smartlinks.smart_link').
|
||||
*
|
||||
* @extends FormModel<SmartLink>
|
||||
*/
|
||||
class SmartLinkModel extends FormModel
|
||||
{
|
||||
public const MODEL_NAME = 'smartlinks.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 from < 0.5.0 keep the domain in local.php under the legacy key; serve it until
|
||||
// the Configuration page is saved again (which writes the new key).
|
||||
if (!is_array($stored) || '' === trim((string) ($stored['short_link_domain'] ?? ''))) {
|
||||
$legacy = $this->coreParametersHelper->get(\MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType::LEGACY_CONFIG_PARAMETER, []);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
<?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 MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomy;
|
||||
use MauticPlugin\MT3SMarketingProgramBundle\Entity\UtmTaxonomyRepository;
|
||||
use MauticPlugin\MT3SMarketingProgramBundle\Form\Type\UtmTaxonomyType;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
||||
use Symfony\Component\Form\FormFactoryInterface;
|
||||
use Symfony\Component\Form\FormInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
|
||||
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
|
||||
/**
|
||||
* Available as mautic.smartlinks.model.utm_taxonomy, or getModel('smartlinks.utm_taxonomy').
|
||||
*
|
||||
* @extends FormModel<UtmTaxonomy>
|
||||
*/
|
||||
class UtmTaxonomyModel extends FormModel
|
||||
{
|
||||
public const MODEL_NAME = 'smartlinks.utm_taxonomy';
|
||||
|
||||
public function __construct(
|
||||
EntityManagerInterface $em,
|
||||
CorePermissions $security,
|
||||
EventDispatcherInterface $dispatcher,
|
||||
UrlGeneratorInterface $router,
|
||||
TranslatorInterface $translator,
|
||||
UserHelper $userHelper,
|
||||
LoggerInterface $logger,
|
||||
CoreParametersHelper $coreParametersHelper,
|
||||
) {
|
||||
parent::__construct($em, $security, $dispatcher, $router, $translator, $userHelper, $logger, $coreParametersHelper);
|
||||
}
|
||||
|
||||
public function getRepository(): UtmTaxonomyRepository
|
||||
{
|
||||
$repository = $this->em->getRepository(UtmTaxonomy::class);
|
||||
\assert($repository instanceof UtmTaxonomyRepository);
|
||||
|
||||
return $repository;
|
||||
}
|
||||
|
||||
public function getPermissionBase(): string
|
||||
{
|
||||
return 'mt3smarketingprogram:taxonomies';
|
||||
}
|
||||
|
||||
public function getEntity($id = null): ?UtmTaxonomy
|
||||
{
|
||||
if (null === $id) {
|
||||
return new UtmTaxonomy();
|
||||
}
|
||||
|
||||
$entity = parent::getEntity($id);
|
||||
|
||||
return $entity instanceof UtmTaxonomy ? $entity : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $options
|
||||
*/
|
||||
public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface
|
||||
{
|
||||
if (!$entity instanceof UtmTaxonomy) {
|
||||
throw new MethodNotAllowedHttpException(['UtmTaxonomy']);
|
||||
}
|
||||
|
||||
if (!empty($action)) {
|
||||
$options['action'] = $action;
|
||||
}
|
||||
|
||||
return $formFactory->create(UtmTaxonomyType::class, $entity, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the canonical shape to the value lists (trimmed, de-duplicated, sorted), then saves.
|
||||
*/
|
||||
public function saveEntity($entity, $unlock = true): void
|
||||
{
|
||||
if ($entity instanceof UtmTaxonomy) {
|
||||
$entity->setParameters($this->normalizeParameters($entity->getParameters()));
|
||||
}
|
||||
|
||||
parent::saveEntity($entity, $unlock);
|
||||
}
|
||||
|
||||
/**
|
||||
* The canonical shape of the `parameters` array: parameter key => list of {value, label} rows.
|
||||
* Empty keys and values are dropped, duplicates keep their first label, labels fall back to
|
||||
* the value, keys and rows keep a stable order. The UtmTaxonomyValidator guarantees the
|
||||
* technical pattern of the values; this is the safety net behind it.
|
||||
*
|
||||
* @param array<string, mixed> $parameters
|
||||
*
|
||||
* @return array<string, list<array{value: string, label: string}>>
|
||||
*/
|
||||
public function normalizeParameters(array $parameters): array
|
||||
{
|
||||
$clean = [];
|
||||
foreach ($parameters as $key => $rows) {
|
||||
$key = trim((string) $key);
|
||||
if ('' === $key || !is_array($rows)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$values = [];
|
||||
foreach ($rows as $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = trim((string) ($row['value'] ?? ''));
|
||||
if ('' === $value || isset($values[$value])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$label = trim((string) ($row['label'] ?? ''));
|
||||
$values[$value] = ['value' => $value, 'label' => '' !== $label ? $label : $value];
|
||||
}
|
||||
|
||||
if ([] !== $values) {
|
||||
$clean[$key] = array_values($values);
|
||||
}
|
||||
}
|
||||
|
||||
ksort($clean);
|
||||
|
||||
return $clean;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when another saved taxonomy already uses this name. $ignoreId keeps a taxonomy being
|
||||
* edited from colliding with itself.
|
||||
*/
|
||||
public function isNameTaken(string $name, ?int $ignoreId = null): bool
|
||||
{
|
||||
return $this->getRepository()->nameExists($name, $ignoreId);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user